diff --git a/Gopkg.lock b/Gopkg.lock index ad0e399..02dcc7e 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -10,10 +10,9 @@ revision = "fe8f9c4593d05f029afeb2c08c3e220120306506" [[projects]] - digest = "1:83673c9b8deac2e919ef0241dde2ceeb7074f2a2637c51567818fa9489203e89" + digest = "1:b6f56ccf1cbe4f644536f701092660bf3fb9bf1832acb58ab22d4569c207c846" name = "github.com/aws/aws-sdk-go" packages = [ - ".", "aws", "aws/awserr", "aws/awsutil", @@ -153,47 +152,6 @@ revision = "5c8c8bd35d3832f5d134ae1e1e375b69a4d25242" version = "v1.0.1" -[[projects]] - digest = "1:529f54d656a5240fc1af45f291eabbea6ce904659faac0fd0b0a4cd90c5c95f2" - name = "github.com/mongodb/mongo-go-driver" - packages = [ - "bson", - "bson/bsoncodec", - "bson/bsonrw", - "bson/bsontype", - "bson/decimal", - "bson/objectid", - "bson/primitive", - "core/address", - "core/auth", - "core/auth/internal/gssapi", - "core/command", - "core/compressor", - "core/connection", - "core/connstring", - "core/description", - "core/dispatch", - "core/event", - "core/result", - "core/session", - "core/tag", - "core/topology", - "core/uuid", - "core/version", - "core/wiremessage", - "internal", - "mongo", - "mongo/readconcern", - "mongo/readpref", - "mongo/writeconcern", - "options", - "x/bsonx", - "x/bsonx/bsoncore", - ] - pruneopts = "UT" - revision = "dbffb1c211bf96fbd721b4bd6911331e5c1886ab" - version = "v0.0.18" - [[projects]] digest = "1:69b1cc331fca23d702bd72f860c6a647afd0aa9fcbc1d0659b1365e26546dd70" name = "github.com/sirupsen/logrus" @@ -211,12 +169,51 @@ revision = "7eeb5667e42c09cb51bf7b7c28aea8c56767da90" [[projects]] - digest = "1:577b99fc55ee19cbf1ffd072808c91ced78cd732bd9d0517bec9b90e532069cb" + branch = "master" + digest = "1:f5c1d04bc09c644c592b45b9f0bad4030521b1a7d11c7dadbb272d9439fa6e8e" name = "github.com/xdg/stringprep" packages = ["."] pruneopts = "UT" - revision = "bd625b8dc1e3b0f57412280ccbcc317f0c69d8db" - version = "v1.0.0" + revision = "73f8eece6fdcd902c185bf651de50f3828bed5ed" + +[[projects]] + digest = "1:026f6e643ff4f5bdbc26c673882da3c174545dd7b7d423846e1a8a4f7a4fc1b9" + name = "go.mongodb.org/mongo-driver" + packages = [ + "bson", + "bson/bsoncodec", + "bson/bsonrw", + "bson/bsontype", + "bson/primitive", + "event", + "internal", + "mongo", + "mongo/options", + "mongo/readconcern", + "mongo/readpref", + "mongo/writeconcern", + "tag", + "version", + "x/bsonx", + "x/bsonx/bsoncore", + "x/mongo/driver", + "x/mongo/driver/auth", + "x/mongo/driver/auth/internal/gssapi", + "x/mongo/driver/session", + "x/mongo/driver/topology", + "x/mongo/driver/uuid", + "x/network/address", + "x/network/command", + "x/network/compressor", + "x/network/connection", + "x/network/connstring", + "x/network/description", + "x/network/result", + "x/network/wiremessage", + ] + pruneopts = "UT" + revision = "fd38aea397a6b7fdd52b5528e4cfd683821e7b39" + version = "v1.0.1" [[projects]] branch = "master" @@ -278,7 +275,6 @@ analyzer-version = 1 input-imports = [ "github.com/PagerDuty/go-pagerduty", - "github.com/aws/aws-sdk-go", "github.com/aws/aws-sdk-go/aws", "github.com/aws/aws-sdk-go/aws/credentials", "github.com/aws/aws-sdk-go/aws/session", @@ -289,12 +285,12 @@ "github.com/gofrs/uuid", "github.com/gorilla/handlers", "github.com/gorilla/mux", - "github.com/mongodb/mongo-go-driver/bson", - "github.com/mongodb/mongo-go-driver/bson/objectid", - "github.com/mongodb/mongo-go-driver/mongo", - "github.com/mongodb/mongo-go-driver/options", - "github.com/mongodb/mongo-go-driver/x/bsonx", "github.com/sirupsen/logrus", + "go.mongodb.org/mongo-driver/bson", + "go.mongodb.org/mongo-driver/bson/primitive", + "go.mongodb.org/mongo-driver/mongo", + "go.mongodb.org/mongo-driver/mongo/options", + "go.mongodb.org/mongo-driver/x/bsonx", "golang.org/x/crypto/bcrypt", ] solver-name = "gps-cdcl" diff --git a/Gopkg.toml b/Gopkg.toml index cc67c7a..712c8a1 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -72,3 +72,7 @@ [[constraint]] name = "github.com/aws/aws-sdk-go" version = "1.16.15" + +[[constraint]] + name = "go.mongodb.org/mongo-driver" + version = "~1.0.0" diff --git a/internal/db/client.go b/internal/db/client.go index a493ec9..ebeb3b4 100644 --- a/internal/db/client.go +++ b/internal/db/client.go @@ -6,7 +6,7 @@ import ( "log" "os" - "github.com/mongodb/mongo-go-driver/mongo" + "go.mongodb.org/mongo-driver/mongo" ) var mongoClient *mongo.Client diff --git a/internal/db/utils.go b/internal/db/utils.go index 7c55bca..2980dde 100644 --- a/internal/db/utils.go +++ b/internal/db/utils.go @@ -4,15 +4,16 @@ import ( "context" "time" - "github.com/mongodb/mongo-go-driver/mongo" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/options" + "go.mongodb.org/mongo-driver/mongo/options" "github.com/defraglabs/uptime/internal/forms" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/objectid" + log "github.com/sirupsen/logrus" + "go.mongodb.org/mongo-driver/bson" ) const ( @@ -72,8 +73,8 @@ func addTextIndexesOnMonitorURLCollection(dbClient *mongo.Client, datastore *Dat } // GenerateObjectID generates a new objectid. -func GenerateObjectID() objectid.ObjectID { - return objectid.New() +func GenerateObjectID() primitive.ObjectID { + return primitive.NewObjectID() } // CreateUser func persists the user to db. diff --git a/vendor/github.com/aws/aws-sdk-go/.gitignore b/vendor/github.com/aws/aws-sdk-go/.gitignore deleted file mode 100644 index fb11cec..0000000 --- a/vendor/github.com/aws/aws-sdk-go/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -dist -/doc -/doc-staging -.yardoc -Gemfile.lock -awstesting/integration/smoke/**/importmarker__.go -awstesting/integration/smoke/_test/ -/vendor/bin/ -/vendor/pkg/ -/vendor/src/ -/private/model/cli/gen-api/gen-api diff --git a/vendor/github.com/aws/aws-sdk-go/.godoc_config b/vendor/github.com/aws/aws-sdk-go/.godoc_config deleted file mode 100644 index 0c6400b..0000000 --- a/vendor/github.com/aws/aws-sdk-go/.godoc_config +++ /dev/null @@ -1,14 +0,0 @@ -{ - "PkgHandler": { - "Pattern": "/sdk-for-go/api/", - "StripPrefix": "/sdk-for-go/api", - "Include": ["/src/github.com/aws/aws-sdk-go/aws", "/src/github.com/aws/aws-sdk-go/service"], - "Exclude": ["/src/cmd", "/src/github.com/aws/aws-sdk-go/awstesting", "/src/github.com/aws/aws-sdk-go/awsmigrate", "/src/github.com/aws/aws-sdk-go/private"], - "IgnoredSuffixes": ["iface"] - }, - "Github": { - "Tag": "master", - "Repo": "/aws/aws-sdk-go", - "UseGithub": true - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/.travis.yml b/vendor/github.com/aws/aws-sdk-go/.travis.yml deleted file mode 100644 index 185f6a1..0000000 --- a/vendor/github.com/aws/aws-sdk-go/.travis.yml +++ /dev/null @@ -1,42 +0,0 @@ -language: go - -sudo: required - -os: - - linux - - osx -go: - - 1.6.x - - 1.7.x - - 1.8.x - - 1.9.x - - 1.10.x - - 1.11.x - - tip - -matrix: - allow_failures: - - go: tip - exclude: - # OSX 1.6.4 is not present in travis. - # https://github.com/travis-ci/travis-ci/issues/10309 - - go: 1.6.x - os: osx - include: - - os: linux - go: 1.5.x - # Use Go 1.5's vendoring experiment for 1.5 tests. - env: GO15VENDOREXPERIMENT=1 - -script: - - if [ $TRAVIS_GO_VERSION == "tip" ] || - [ $TRAVIS_GO_VERSION == "1.11.x" ] || - [ $TRAVIS_GO_VERSION == "1.10.x" ]; then - make ci-test; - else - make unit-old-go-race-cover; - fi - -branches: - only: - - master diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md deleted file mode 100644 index eacdc5a..0000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG.md +++ /dev/null @@ -1,5151 +0,0 @@ -Release v1.16.15 (2019-01-07) -=== - -### Service Client Updates -* `service/appmesh`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.16.14 (2019-01-04) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * "This release provides support for running Appium Node.js and Appium Ruby tests on AWS Device Farm. -* `service/ecs`: Updates service documentation - * Documentation updates for Amazon ECS tagging feature. - -Release v1.16.13 (2019-01-03) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iotanalytics`: Updates service API and documentation - -### SDK Enhancements -* `aws/credentials`: Add support for getting credential's ExpiresAt. ([#2375](https://github.com/aws/aws-sdk-go/pull/2375)) - * Adds an Expirer interface that Providers can implement, and add a suitable implementation to Expiry class used by most Providers. Add a method on Credentials to get the expiration time of the underlying Provider, if Expirer is supported, without exposing Provider to callers. - * Fix [#1329](https://github.com/aws/aws-sdk-go/pull/1329) - -### SDK Bugs -* `aws/ec2metadata`: bounds check region identifier before split ([#2380](https://github.com/aws/aws-sdk-go/pull/2380)) - * Adds empty response checking to ec2metadata's Region request to prevent a out of bounds panic if empty response received. -* Fix SDK's generated API reference doc page's constants section links ([#2373](https://github.com/aws/aws-sdk-go/pull/2373)) - * Fixes the SDK's generated API reference documentation page's constants section links to to be clickable. -Release v1.16.12 (2019-01-03) -=== - -### Service Client Updates -* `service/opsworkscm`: Updates service documentation - * Documentation updates for opsworkscm - -Release v1.16.11 (2018-12-21) -=== - -### Service Client Updates -* `service/acm-pca`: Updates service documentation, waiters, paginators, and examples -* `service/dynamodb`: Updates service API and documentation - * Added provisionedThroughPut exception on the request level for transaction APIs. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/sms-voice`: Updates service API and documentation -* `service/states`: Updates service API and documentation - * This release adds support for cost allocation tagging. You can now create, delete, and list tags for AWS Step Functions activity and state machine resources. For more information about tagging, see AWS Tagging Strategies. - -Release v1.16.10 (2018-12-20) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/comprehend`: Updates service API and documentation -* `service/firehose`: Updates service API and documentation - * Support for specifying customized s3 keys and supplying a separate prefix for failed-records -* `service/medialive`: Updates service API and documentation - * This release provides support for ID3 tags and video quality setting for subgop_length. -* `service/transcribe`: Updates service API and documentation - -### SDK Enhancements -* `service/dynamodb/expression`: Clarify expression examples ([#2367](https://github.com/aws/aws-sdk-go/pull/2367)) - * Clarifies the expression package's examples to distinguish the pkg expression from a expr value. - -Release v1.16.9 (2018-12-19) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * This release adds support for specifying partition as a strategy for EC2 Placement Groups. This new strategy allows one to launch instances into partitions that do not share certain underlying hardware between partitions, to assist with building and deploying highly available replicated applications. -* `service/sagemaker`: Updates service API and documentation - * Batch Transform Jobs now supports TFRecord as a Split Type. ListCompilationJobs API action now supports SortOrder and SortBy inputs. -* `service/waf`: Updates service API and documentation - * This release adds rule-level control for rule group. If a rule group contains a rule that blocks legitimate traffic, previously you had to override the entire rule group to COUNT in order to allow the traffic. You can now use the UpdateWebACL API to exclude specific rules within a rule group. Excluding rules changes the action for the individual rules to COUNT. Excluded rules will be recorded in the new "excludedRules" attribute of the WAF logs. -* `service/waf-regional`: Updates service API and documentation - -Release v1.16.8 (2018-12-18) -=== - -### Service Client Updates -* `service/apigatewaymanagementapi`: Adds new service -* `service/apigatewayv2`: Adds new service - * This is the initial SDK release for the Amazon API Gateway v2 APIs. This SDK will allow you to manage and configure APIs in Amazon API Gateway; this first release provides the capabilities that allow you to programmatically setup and manage WebSocket APIs end to end. -* `service/ec2`: Updates service API and documentation - * Client VPN, is a client-based VPN service. With Client VPN, you can securely access resources in AWS as well as access resources in on-premises from any location using OpenVPN based devices. With Client VPN, you can set network based firewall rules that can restrict access to networks based on Active Directory groups. -* `service/elasticbeanstalk`: Updates service API and documentation - * This release adds a new resource that Elastic Beanstalk will soon support, EC2 launch template, to environment resource descriptions. -* `service/globalaccelerator`: Updates service documentation - -Release v1.16.7 (2018-12-17) -=== - -### Service Client Updates -* `service/ecr`: Updates service API and documentation - * This release adds support for ECR repository tagging. -* `service/quicksight`: Updates service API and documentation - * Amazon QuickSight's RegisterUser API now generates a user invitation URL when registering a user with the QuickSight identity type. This URL can then be used by the registered QuickSight user to complete the user registration process. This release also corrects some HTTP return status codes. - -Release v1.16.6 (2018-12-14) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API and documentation -* `service/cloudformation`: Updates service documentation - * Documentation updates for cloudformation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/redshift`: Updates service documentation - * Documentation updates for Amazon Redshift - -### SDK Bugs -* `private/mode/api`: Fix idempotency members not to require validation [#2353](https://github.com/aws/aws-sdk-go/pull/2353) - * Fixes the SDK's usage of API operation request members marked as idempotency tokens to not require validation. These fields will be auto populated by the SDK if the user does not provide a value. The SDK was requiring the user to provide a value or disable validation to use these APIs. -* deps: Update Go Deps lock file to correct tracking hash [#2354](https://github.com/aws/aws-sdk-go/pull/2354) -Release v1.16.5 (2018-12-13) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/organizations`: Updates service documentation - * Documentation updates for AWS Organizations -* `service/pinpoint-email`: Updates service API, documentation, and paginators - -Release v1.16.4 (2018-12-12) -=== - -### Service Client Updates -* `service/eks`: Updates service API and documentation -* `service/glue`: Updates service API and documentation - * API Update for Glue: this update enables encryption of password inside connection objects stored in AWS Glue Data Catalog using DataCatalogEncryptionSettings. In addition, a new "HidePassword" flag is added to GetConnection and GetConnections to return connections without passwords. -* `service/route53`: Updates service API and documentation - * You can now specify a new region, eu-north-1 (in Stockholm, Sweden), as a region for latency-based or geoproximity routing. -* `service/sagemaker`: Updates service API and documentation - * Amazon SageMaker Automatic Model Tuning now supports early stopping of training jobs. With early stopping, training jobs that are unlikely to generate good models will be automatically stopped during a Hyperparameter Tuning Job. - -Release v1.16.3 (2018-12-11) -=== - -### Service Client Updates -* `service/connect`: Updates service API and documentation -* `service/ecs`: Updates service documentation - * Documentation updates for Amazon ECS. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediastore`: Updates service API and documentation - * This release adds Delete Object Lifecycling to AWS MediaStore Containers. - -### SDK Bugs -* `private/model/api`: Fix SDK's unmarshaling of unmodeled response payload ([#2340](https://github.com/aws/aws-sdk-go/pull/2340)) - * Fixes the SDK's unmarshaling of API operation response payloads for operations that are unmodeled. Prevents the SDK due to unexpected response payloads causing errors in the API protocol unmarshaler. - * Fixes [#2332](https://github.com/aws/aws-sdk-go/issues/2332) -Release v1.16.2 (2018-12-07) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API, documentation, and paginators -* `service/ec2`: Updates service API - * You can now launch the larger-sized P3dn.24xlarge instance that features NVIDIA Tesla V100s with double the GPU memory, 100Gbps networking and local NVMe storage. -* `service/iam`: Updates service API, documentation, and examples - * We are making it easier for you to manage your AWS Identity and Access Management (IAM) policy permissions by enabling you to retrieve the last timestamp when an IAM entity (e.g., user, role, or a group) accessed an AWS service. This feature also allows you to audit service access for your entities. -* `service/servicecatalog`: Updates service documentation - * Documentation updates for servicecatalog. - -### SDK Enhancements -* `aws/signer/v4`: Always sign a request with the current time. ([#2336](https://github.com/aws/aws-sdk-go/pull/2336)) - * Updates the SDK's v4 request signer to always sign requests with the current time. For the first request attempt, the request's creation time was used in the request's signature. In edge cases this allowed the signature to expire before the request was sent if there was significant delay between creating the request and sending it, (e.g. rate limiting). -* `aws/endpoints`: Deprecate endpoint service ID generation. ([#2338](https://github.com/aws/aws-sdk-go/pull/2338)) - * Deprecates the service ID generation. The list of service IDs do not directly 1:1 relate to a AWS service. The set of ServiceIDs is confusing, and inaccurate. Instead users should use the EndpointID value defined in each service client's package - -Release v1.16.1 (2018-12-06) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Support personal access tokens for GitHub source and app passwords for Bitbucket source -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/medialive`: Updates service API and documentation - * This release enables the AWS Elemental MediaConnect input type in AWS Elemental MediaLive. This can then be used to automatically create and manage AWS Elemental MediaConnect Flow Outputs when you create a channel using those inputs. -* `service/rds`: Updates service documentation - * Documentation updates for Amazon RDS - -Release v1.16.0 (2018-12-05) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/mediatailor`: Updates service API and documentation -* `service/mq`: Updates service API and documentation - * This release adds support for cost allocation tagging. You can now create, delete, and list tags for AmazonMQ resources. For more information about tagging, see AWS Tagging Strategies. - -### SDK Features -* `aws/credential`: Add credential_process provider ([#2217](https://github.com/aws/aws-sdk-go/pull/2217)) - * Adds support for the shared configuration file's `credential_process` property. This property allows the application to execute a command in order to retrieve AWS credentials for AWS service API request. In order to use this feature your application must enable the SDK's support of the shared configuration file. See, https://docs.aws.amazon.com/sdk-for-go/api/aws/session/#hdr-Sessions_from_Shared_Config for more information on enabling shared config support. - -### SDK Enhancements -* `service/sqs`: Add batch checksum validation test ([#2307](https://github.com/aws/aws-sdk-go/pull/2307)) - * Adds additional test of the SQS batch checksum validation. -* `aws/awsutils`: Update not to retrun sensitive fields for StringValue ([#2310](https://github.com/aws/aws-sdk-go/pull/2310)) -* Update SDK client integration tests to be code generated. ([#2308](https://github.com/aws/aws-sdk-go/pull/2308)) -* private/mode/api: Update SDK to require URI path members not be empty ([#2323](https://github.com/aws/aws-sdk-go/pull/2323)) - * Updates the SDK's validation to require that members serialized to URI path must not have empty (zero length) values. Generally these fields are modeled as required, but not always. Fixing this will prevent bugs with REST URI paths requests made for unexpected resources. - -### SDK Bugs -* aws/session: Fix formatting bug in doc. ([#2294](https://github.com/aws/aws-sdk-go/pull/2294)) - * Fixes a minor issue in aws/session/doc.go where mistakenly used format specifiers in logger.Println. -* Fix SDK model cleanup to remove old model folder ([#2324](https://github.com/aws/aws-sdk-go/pull/2324)) - * Fixes the SDK's model cleanup to remove the entire old model folder not just the api-2.json file. -* Fix SDK's vet usage to use go vet with build tags ([#2300](https://github.com/aws/aws-sdk-go/pull/2300)) - * Updates the SDK's usage of vet to use go vet instead of go tool vet. This allows the SDK to pass build tags and packages instead of just folder paths to the tool. -Release v1.15.90 (2018-12-04) -=== - -### Service Client Updates -* `service/health`: Updates service API and documentation - * AWS Health API DescribeAffectedEntities operation now includes a field that returns the URL of the affected entity. -* `service/s3`: Updates service API - * S3 Inventory reports can now be generated in Parquet format by setting the Destination Format to be 'Parquet'. - -Release v1.15.89 (2018-12-03) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Customers can now schedule runs without a need to create a Device Pool. They also get realtime information on public device availability. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediaconvert`: Updates service documentation - * Documentation updates for mediaconvert -* `service/servicecatalog`: Updates service documentation - * Documentation updates for servicecatalog -* `service/storagegateway`: Updates service API and documentation - * API list-local-disks returns a list of the gateway's local disks. This release adds a field DiskAttributeList to these disks. - -Release v1.15.88 (2018-11-29) -=== - -### Service Client Updates -* `service/s3`: Updates service documentation - * Fixed issue with Content-MD5 for S3 PutObjectLegalHold, PutObjectRetention and PutObjectLockConfiguration. - -Release v1.15.87 (2018-11-29) -=== - -### Service Client Updates -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/events`: Updates service API and documentation - * Support for Managed Rules (rules that are created and maintained by the AWS services in your account) is added. -* `service/kafka`: Adds new service -* `service/lambda`: Updates service API and documentation - * AWS Lambda now supports Lambda Layers and Ruby as a runtime. Lambda Layers are a new type of artifact that contains arbitrary code and data, and may be referenced by zero, one, or more functions at the same time. You can also now develop your AWS Lambda function code using the Ruby programming language. -* `service/s3`: Updates service API and examples - * Fixed issue with ObjectLockRetainUntilDate in S3 PutObject -* `service/serverlessrepo`: Updates service API, documentation, and paginators -* `service/states`: Updates service API and documentation - * AWS Step Functions is now integrated with eight additional AWS services: Amazon ECS, AWS Fargate, Amazon DynamoDB, Amazon SNS, Amazon SQS, AWS Batch, AWS Glue, and Amazon SageMaker. To learn more, please see https://docs.aws.amazon.com/step-functions/index.html -* `service/xray`: Updates service API and documentation - * GetTraceSummaries - Now provides additional information regarding your application traces such as Availability Zone, Instance ID, Resource ARN details, Revision, Entry Point, Root Cause Exceptions and Root Causes for Fault, Error and Response Time. - -Release v1.15.86 (2018-11-29) -=== - -### Service Client Updates -* `service/appmesh`: Adds new service -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. You can now hibernate and resume Amazon-EBS backed instances using the StopInstances and StartInstances APIs. For more information about using this feature and supported instance types and operating systems, visit the user guide. 2. Amazon Elastic Inference accelerators are resources that you can attach to current generation EC2 instances to accelerate your deep learning inference workloads. With Amazon Elastic Inference, you can configure the right amount of inference acceleration to your deep learning application without being constrained by fixed hardware configurations and limited GPU selection. 3. AWS License Manager makes it easier to manage licenses in AWS and on premises when customers run applications using existing licenses from a variety of software vendors including Microsoft, SAP, Oracle, and IBM. -* `service/license-manager`: Adds new service -* `service/lightsail`: Updates service API and documentation - * This update adds the following features: 1. Copy instance and disk snapshots within the same AWS Region or from one region to another in Amazon Lightsail. 2. Export Lightsail instance and disk snapshots to Amazon Elastic Compute Cloud (Amazon EC2). 3. Create an Amazon EC2 instance from an exported Lightsail instance snapshot using AWS CloudFormation stacks. 4. Apply tags to filter your Lightsail resources, or organize your costs, or control access. -* `service/sagemaker`: Updates service API, documentation, and paginators - * Amazon SageMaker now has Algorithm and Model Package entities that can be used to create Training Jobs, Hyperparameter Tuning Jobs and hosted Models. Subscribed Marketplace products can be used on SageMaker to create Training Jobs, Hyperparameter Tuning Jobs and Models. Notebook Instances and Endpoints can leverage Elastic Inference accelerator types for on-demand GPU computing. Model optimizations can be performed with Compilation Jobs. Labeling Jobs can be created and supported by a Workforce. Models can now contain up to 5 containers allowing for inference pipelines within Endpoints. Code Repositories (such as Git) can be linked with SageMaker and loaded into Notebook Instances. Network isolation is now possible on Models, Training Jobs, and Hyperparameter Tuning Jobs, which restricts inbound/outbound network calls for the container. However, containers can talk to their peers in distributed training mode within the same security group. A Public Beta Search API was added that currently supports Training Jobs. -* `service/servicediscovery`: Updates service API and documentation - * AWS Cloud Map lets you define friendly names for your cloud resources so that your applications can quickly and dynamically discover them. When a resource becomes available (for example, an Amazon EC2 instance running a web server), you can register a Cloud Map service instance. Then your application can discover service instances by submitting DNS queries or API calls. - -Release v1.15.85 (2018-11-28) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service API and documentation - * Amazon DynamoDB now supports the following features: DynamoDB on-demand and transactions. DynamoDB on-demand is a flexible new billing option for DynamoDB capable of serving thousands of requests per second without capacity planning. DynamoDB on-demand offers simple pay-per-request pricing for read and write requests so that you only pay for what you use, making it easy to balance costs and performance. Transactions simplify the developer experience of making coordinated, all-or-nothing changes to multiple items both within and across tables. The new transactional APIs provide atomicity, consistency, isolation, and durability (ACID) in DynamoDB, helping developers support sophisticated workflows and business logic that requires adding, updating, or deleting multiple items using native, server-side transactions. For more information, see the Amazon DynamoDB Developer Guide. -* `service/fsx`: Adds new service -* `service/rds`: Updates service API, documentation, and paginators - * Amazon Aurora Global Database. This release introduces support for Global Database, a feature that allows a single Amazon Aurora database to span multiple AWS regions. Customers can use the feature to replicate data with no impact on database performance, enable fast local reads with low latency in each region, and improve disaster recovery from region-wide outages. You can create, modify and describe an Aurora Global Database, as well as add or remove regions from your Global Database. -* `service/securityhub`: Adds new service - -Release v1.15.84 (2018-11-28) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * Support for Amazon ECS service deployment - AWS CodeDeploy now supports the deployment of Amazon ECS services. An Amazon ECS deployment uses an Elastic Load Balancer, two Amazon ECS target groups, and a listener to reroute production traffic from your Amazon ECS service's original task set to a new replacement task set. The original task set is terminated when the deployment is complete. Success of a deployment can be validated using Lambda functions that are referenced by the deployment. This provides the opportunity to rollback if necessary. You can use the new ECSService, ECSTarget, and ECSTaskSet data types in the updated SDK to create or retrieve an Amazon ECS deployment. -* `service/comprehendmedical`: Adds new service -* `service/ec2`: Updates service API and documentation - * With VPC sharing, you can now allow multiple accounts in the same AWS Organization to launch their application resources, like EC2 instances, RDS databases, and Redshift clusters into shared, centrally managed VPCs. -* `service/ecs`: Updates service API and documentation - * This release of Amazon Elastic Container Service (Amazon ECS) introduces support for blue/green deployment feature. Customers can now update their ECS services in a blue/green deployment pattern via using AWS CodeDeploy. -* `service/kinesisanalytics`: Updates service API and documentation - * Improvements to error messages, validations, and more to the Kinesis Data Analytics APIs. -* `service/kinesisanalyticsv2`: Adds new service -* `service/logs`: Updates service API and documentation - * Six new APIs added to support CloudWatch Logs Insights. The APIs are StartQuery, StopQuery, GetQueryResults, GetLogRecord, GetLogGroupFields, and DescribeQueries. -* `service/mediaconnect`: Adds new service -* `service/meteringmarketplace`: Updates service API, documentation, and paginators - * RegisterUsage operation added to AWS Marketplace Metering Service, allowing sellers to meter and entitle Docker container software use with AWS Marketplace. For details on integrating Docker containers with RegisterUsage see: https://docs.aws.amazon.com/marketplace/latest/userguide/entitlement-and-metering-for-paid-products.html -* `service/translate`: Updates service API and documentation - -Release v1.15.83 (2018-11-27) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. Transit Gateway helps easily scale connectivity across thousands of Amazon VPCs, AWS accounts, and on-premises networks. 2. Amazon EC2 A1 instance is a new Arm architecture based general purpose instance. 3. You can now launch the new Amazon EC2 compute optimized C5n instances that can utilize up to 100 Gbps of network bandwidth. -* `service/globalaccelerator`: Adds new service -* `service/greengrass`: Updates service API and documentation - * Support Greengrass Connectors and allow Lambda functions to run without Greengrass containers. -* `service/iot`: Updates service API and documentation - * As part of this release, we are extending capability of AWS IoT Rules Engine to support IoT Events rule action. The IoT Events rule action lets you send messages from IoT sensors and applications to IoT Events for pattern recognition and event detection. -* `service/iotanalytics`: Updates service API and documentation -* `service/kms`: Updates service API and documentation - * AWS Key Management Service (KMS) now enables customers to create and manage dedicated, single-tenant key stores in addition to the default KMS key store. These are known as custom key stores and are deployed using AWS CloudHSM clusters. Keys that are created in a KMS custom key store can be used like any other customer master key in KMS. -* `service/s3`: Updates service API and documentation - * Four new Amazon S3 Glacier features help you reduce your storage costs by making it even easier to build archival applications using the Amazon S3 Glacier storage class. S3 Object Lock enables customers to apply Write Once Read Many (WORM) protection to objects in S3 in order to prevent object deletion for a customer-defined retention period. S3 Inventory now supports fields for reporting on S3 Object Lock. "ObjectLockRetainUntilDate", "ObjectLockMode", and "ObjectLockLegalHoldStatus" are now available as valid optional fields. -* `service/sms`: Updates service API, documentation, and paginators - * In this release, AWS Server Migration Service (SMS) has added multi-server migration support to simplify the application migration process. Customers can migrate all their application-specific servers together as a single unit as opposed to moving individual server one at a time. The new functionality includes - 1. Ability to group on-premises servers into applications and application tiers. 2. Auto-generated CloudFormation Template and Stacks for launching migrated servers into EC2. 3. Ability to run post-launch configuration scripts to configure servers and applications in EC2. In order for SMS to launch servers into your AWS account using CloudFormation Templates, we have also updated the ServerMigrationServiceRole IAM policy to include appropriate permissions. Refer to Server Migration Service documentation for more details. - -### SDK Enhancements -* `service/s3/s3manager`: Generate Upload Manager's UploadInput structure ([#2296](https://github.com/aws/aws-sdk-go/pull/2296)) - * Updates the SDK's code generation to also generate the S3 Upload Manager's UploadInput structure type based on the modeled S3 PutObjectInput. This ensures parity between the two types, and the S3 manager does not fall behind the capabilities of PutObject. - -### SDK Bugs -* `private/model/api`: Fix model loading to not require docs model. ([#2303](https://github.com/aws/aws-sdk-go/pull/2303)) - * Fixes the SDK's model loading to not require that the docs model be present. This model isn't explicitly required. -* Fixup endpoint discovery unit test to be stable ([#2305](https://github.com/aws/aws-sdk-go/pull/2305)) - * Fixes the SDK's endpoint discovery async unit test to be stable, and produce consistent unit test results. -Release v1.15.82 (2018-11-26) -=== - -### Service Client Updates -* `service/amplify`: Adds new service -* `service/datasync`: Adds new service -* `service/robomaker`: Adds new service -* `service/s3`: Updates service API, documentation, and examples - * The INTELLIGENT_TIERING storage class is designed to optimize storage costs by automatically moving data to the most cost effective storage access tier, without performance impact or operational overhead. This SDK release provides API support for this new storage class. -* `service/snowball`: Updates service API and documentation - * AWS announces the availability of AWS Snowball Edge Compute Optimized to run compute-intensive applications is disconnected and physically harsh environments. It comes with 52 vCPUs, 208GB memory, 8TB NVMe SSD, and 42TB S3-compatible storage to accelerate local processing and is well suited for use cases such as full motion video processing, deep IoT analytics, and continuous machine learning in bandwidth-constrained locations. It features new instances types called SBE-C instances that are available in eight sizes and multiple instances can be run on the device at the same time. Optionally, developers can choose the compute optimized device to include a GPU and use SBE-G instances for accelerating their application performance. -* `service/transfer`: Adds new service - * AWS Transfer for SFTP is a fully managed service that enables transfer of secure data over the internet into and out of Amazon S3. SFTP is deeply embedded in data exchange workflows across different industries such as financial services, healthcare, advertising, and retail, among others. - -Release v1.15.81 (2018-11-21) -=== - -### Service Client Updates -* `service/rekognition`: Updates service API and documentation - * This release updates the DetectFaces and IndexFaces operation. When the Attributes input parameter is set to ALL, the face location landmarks includes 5 new landmarks: upperJawlineLeft, midJawlineLeft, chinBottom, midJawlineRight, upperJawlineRight. - -Release v1.15.80 (2018-11-20) -=== - -### Service Client Updates -* `service/appsync`: Updates service API and documentation -* `service/autoscaling-plans`: Updates service API and documentation -* `service/cloudfront`: Adds new service - * With Origin Failover capability in CloudFront, you can setup two origins for your distributions - primary and secondary, such that your content is served from your secondary origin if CloudFront detects that your primary origin is unavailable. These origins can be any combination of AWS origins or non-AWS custom HTTP origins. For example, you can have two Amazon S3 buckets that serve as your origin that you independently upload your content to. If an object that CloudFront requests from your primary bucket is not present or if connection to your primary bucket times-out, CloudFront will request the object from your secondary bucket. So, you can configure CloudFront to trigger a failover in response to either HTTP 4xx or 5xx status codes. -* `service/devicefarm`: Updates service API and documentation - * Disabling device filters -* `service/medialive`: Updates service API and documentation - * You can now include the media playlist(s) from both pipelines in the HLS master manifest for seamless failover. -* `service/monitoring`: Updates service API and documentation - * Amazon CloudWatch now supports alarms on metric math expressions. -* `service/quicksight`: Adds new service - * Amazon QuickSight is a fully managed, serverless, cloud business intelligence system that allows you to extend data and insights to every user in your organization. The first release of APIs for Amazon QuickSight introduces embedding and user/group management capabilities. The get-dashboard-embed-url API allows you to obtain an authenticated dashboard URL that can be embedded in application domains whitelisted for QuickSight dashboard embedding. User APIs allow you to programmatically expand and manage your QuickSight deployments while group APIs allow easier permissions management for resources within QuickSight. -* `service/rds-data`: Adds new service -* `service/redshift`: Updates service documentation - * Documentation updates for redshift -* `service/ssm`: Updates service API and documentation - * AWS Systems Manager Distributor helps you securely distribute and install software packages. -* `service/xray`: Updates service API and documentation - * Groups build upon X-Ray filter expressions to allow for fine tuning trace summaries and service graph results. You can configure groups by using the AWS X-Ray console or by using the CreateGroup API. The addition of groups has extended the available request fields to the GetServiceGraph API. You can now specify a group name or group ARN to retrieve its service graph. - -Release v1.15.79 (2018-11-20) -=== - -### Service Client Updates -* `service/batch`: Updates service API and documentation - * Adding multinode parallel jobs, placement group support for compute environments. -* `service/cloudformation`: Updates service API and documentation - * Use the CAPABILITY_AUTO_EXPAND capability to create or update a stack directly from a stack template that contains macros, without first reviewing the resulting changes in a change set first. -* `service/cloudtrail`: Updates service API and documentation - * This release supports creating a trail in CloudTrail that logs events for all AWS accounts in an organization in AWS Organizations. This helps enable you to define a uniform event logging strategy for your organization. An organization trail is applied automatically to each account in the organization and cannot be modified by member accounts. To learn more, please see the AWS CloudTrail User Guide https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html -* `service/config`: Updates service API and documentation -* `service/devicefarm`: Updates service API and documentation - * Customers can now schedule runs without a need to create a Device Pool. They also get realtime information on public device availability. -* `service/ec2`: Updates service API and documentation - * Adding AvailabilityZoneId to DescribeAvailabilityZones -* `service/iot`: Updates service API and documentation - * IoT now supports resource tagging and tag based access control for Billing Groups, Thing Groups, Thing Types, Jobs, and Security Profiles. IoT Billing Groups help you group devices to categorize and track your costs. AWS IoT Device Management also introduces three new features: 1. Dynamic thing groups. 2. Jobs dynamic rollouts. 3. Device connectivity indexing. Dynamic thing groups lets you to create a group of devices using a Fleet Indexing query. The devices in your group will be automatically added or removed when they match your specified query criteria. Jobs dynamic rollout allows you to configure an exponentially increasing rate of deployment for device updates and define failure criteria to cancel your job. Device connectivity indexing allows you to index your devices' lifecycle events to discover whether devices are connected or disconnected to AWS IoT. -* `service/lambda`: Updates service API and documentation - * AWS Lambda now supports python3.7 and the Kinesis Data Streams (KDS) enhanced fan-out and HTTP/2 data retrieval features for Kinesis event sources. -* `service/lightsail`: Updates service API - * Add Managed Database operations to OperationType enum. -* `service/mediaconvert`: Updates service API and documentation - * AWS Elemental MediaConvert SDK has added several features including support for: SPEKE full document encryption, up to 150 elements for input stitching, input and motion image insertion, AWS CLI path arguments in S3 links including special characters, AFD signaling, additional caption types, and client-side encrypted input files. -* `service/rds`: Updates service API and documentation - * This release adds a new parameter to specify VPC security groups for restore from DB snapshot, restore to point int time and create read replica operations. For more information, see Amazon RDS Documentation. -* `service/workdocs`: Updates service API and documentation - * With this release, clients can now use the GetResources API to fetch files and folders from the user's SharedWithMe collection. And also through this release, the existing DescribeActivities API has been enhanced to support additional filters such as the ActivityType and the ResourceId. -* `service/workspaces`: Updates service API and documentation - * Added new APIs to Modify and Describe WorkSpaces client properties for users in a directory. With the new APIs, you can enable/disable remember me option in WorkSpaces client for users in a directory. - -### SDK Bugs -* `internal/ini`: trimSpaces not trimming rhs properly (#2282) - * Fixes trimSpaces to behave properly by removing the necessary rhs spaces of a literal. -Release v1.15.78 (2018-11-16) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/comprehend`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * This release of Amazon Elastic Container Service (Amazon ECS) introduces support for additional Docker flags as Task Definition parameters. Customers can now configure their ECS Tasks to use pidMode (pid) and ipcMode (ipc) Docker flags. -* `service/ssm`: Updates service API and documentation - * AWS Systems Manager Automation now allows you to execute and manage Automation workflows across multiple accounts and regions. -* `service/workspaces`: Updates service API and documentation - * Added new Bring Your Own License (BYOL) automation APIs. With the new APIs, you can list available management CIDR ranges for dedicated tenancy, enable your account for BYOL, describe BYOL status of your account, and import BYOL images. Added new APIs to also describe and delete WorkSpaces images. - -Release v1.15.77 (2018-11-16) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Adding queue phase and configurable queue timeout to CodeBuild. -* `service/comprehend`: Updates service API and documentation -* `service/directconnect`: Updates service API and documentation - * This release enables DirectConnect customers to have logical redundancy on virtual interfaces within supported DirectConnect locations. -* `service/dms`: Updates service API, documentation, and waiters - * Settings structures have been added to our DMS endpoint APIs to support Kinesis and Elasticsearch as targets. We are introducing the ability to configure custom DNS name servers on a replication instance as a beta feature. -* `service/ecs`: Updates service API, documentation, and examples - * In this release, Amazon ECS introduces multiple features. First, ECS now supports integration with Systems Manager Parameter Store for injecting runtime secrets. Second, ECS introduces support for resources tagging. Finally, ECS introduces a new ARN and ID Format for its resources, and provides new APIs for opt-in to the new formats. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iam`: Updates service API, documentation, and examples - * We are making it easier for you to manage your AWS Identity and Access Management (IAM) resources by enabling you to add tags to your IAM principals (users and roles). Adding tags on IAM principals will enable you to write fewer policies for permissions management and make policies easier to comprehend. Additionally, tags will also make it easier for you to grant access to AWS resources. -* `service/pinpoint`: Updates service API and documentation - * 1. With Amazon Pinpoint Voice, you can use text-to-speech technology to deliver personalized voice messages to your customers. Amazon Pinpoint Voice is a great way to deliver transactional messages -- such as one-time passwords and identity confirmations -- to customers. 2. Adding support for Campaign Event Triggers. With Campaign Event Triggers you can now schedule campaigns to execute based on incoming event data and target just the source of the event. -* `service/ram`: Adds new service -* `service/rds`: Updates service API, documentation, and paginators - * Introduces DB Instance Automated Backups for the MySQL, MariaDB, PostgreSQL, Oracle and Microsoft SQL Server database engines. You can now retain Amazon RDS automated backups (system snapshots and transaction logs) when you delete a database instance. This allows you to restore a deleted database instance to a specified point in time within the backup retention period even after it has been deleted, protecting you against accidental deletion of data. For more information, see Amazon RDS Documentation. -* `service/redshift`: Updates service API and documentation - * With this release, Redshift is providing API's for better snapshot management by supporting user defined automated snapshot schedules, retention periods for manual snapshots, and aggregate snapshot actions including batch deleting user snapshots, viewing account level snapshot storage metrics, and better filtering and sorting on the describe-cluster-snapshots API. Automated snapshots can be scheduled to be taken at a custom interval and the schedule created can be reused across clusters. Manual snapshot retention periods can be set at the cluster, snapshot, and cross-region-copy level. The retention period set on a manual snapshot indicates how many days the snapshot will be retained before being automatically deleted. -* `service/route53resolver`: Adds new service -* `service/s3`: Updates service API, documentation, and examples - * Add support for new S3 Block Public Access bucket-level APIs. The new Block Public Access settings allow bucket owners to prevent public access to S3 data via bucket/object ACLs or bucket policies. -* `service/s3control`: Adds new service - * Add support for new S3 Block Public Access account-level APIs. The Block Public Access settings allow account owners to prevent public access to S3 data via bucket/object ACLs or bucket policies. -* `service/sms-voice`: Adds new service -* `service/transcribe`: Updates service API and documentation - -Release v1.15.76 (2018-11-14) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * EC2 Auto Scaling now allows users to provision and automatically scale instances across purchase options (Spot, On-Demand, and RIs) and instance types in a single Auto Scaling group (ASG). -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Fleet now supports a new request type "Instant" that you can use to provision capacity synchronously across instance types & purchase models and CreateFleet will return the instances launched in the API response. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediatailor`: Updates service API and documentation -* `service/resource-groups`: Updates service API and documentation -* `service/sagemaker`: Updates service API and documentation - * SageMaker now makes the final set of metrics published from training jobs available in the DescribeTrainingJob results. Automatic Model Tuning now supports warm start of hyperparameter tuning jobs. Notebook instances now support a larger number of instance types to include instances from the ml.t3, ml.m5, ml.c4, ml.c5 families. -* `service/servicecatalog`: Updates service API and documentation - * Adds support for Cloudformation StackSets in Service Catalog -* `service/sns`: Updates service API and documentation - * Added an optional request parameter, named Attributes, to the Amazon SNS CreateTopic API action. For more information, see the Amazon SNS API Reference (https://docs.aws.amazon.com/sns/latest/api/API_CreateTopic.html). - -Release v1.15.75 (2018-11-13) -=== - -### Service Client Updates -* `service/budgets`: Updates service documentation - * Doc Update: 1. Available monthly-budgets maximal history data points from 12 to 13. 2. Added 'Amazon Elasticsearch' costfilters support. -* `service/chime`: Updates service API and documentation - * This release adds support in ListUsers API to filter the list by an email address. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/redshift`: Updates service API and documentation - * Amazon Redshift provides the option to defer non-mandatory maintenance updates to a later date. - -Release v1.15.74 (2018-11-12) -=== - -### Service Client Updates -* `service/batch`: Updates service API and documentation - * Adding EC2 Launch Template support in AWS Batch Compute Environments. -* `service/budgets`: Updates service API and documentation - * 1. Added budget performance history, enabling you to see how well your budgets matched your actual costs and usage. 2. Added budget performance history, notification state, and last updated time, enabling you to see how well your budgets matched your actual costs and usage, how often your budget alerts triggered, and when your budget was last updated. -* `service/cloudformation`: Updates service API, documentation, and paginators - * The Drift Detection feature enables customers to detect whether a stack's actual configuration differs, or has drifted, from its expected configuration as defined within AWS CloudFormation. -* `service/codepipeline`: Updates service API and documentation - * Add support for cross-region pipeline with accompanying definitions as needed in the AWS CodePipeline API Guide. -* `service/firehose`: Updates service API and documentation - * With this release, Amazon Kinesis Data Firehose allows you to enable/disable server-side encryption(SSE) for your delivery streams ensuring encryption of data at rest. For technical documentation, look at https://docs.aws.amazon.com/firehose/latest/dev/encryption.html -* `service/polly`: Updates service API - * Amazon Polly adds new female voices: Italian - Bianca, Castilian Spanish - Lucia and new language: Mexican Spanish with new female voice - Mia. -* `service/rds`: Updates service API and documentation - * API Update for RDS: this update enables Custom Endpoints, a new feature compatible with Aurora Mysql, Aurora PostgreSQL and Neptune that allows users to configure a customizable endpoint that will provide access to their instances in a cluster. - -### SDK Bugs -* `internal/ini`: allowing LHS of equal expression to contain spaces (#2265) - * Fixes a backward compatibility issue where LHS of equal expr could contain spaces - -Release v1.15.73 (2018-11-09) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediapackage`: Updates service API and documentation - * As a part of SPEKE DRM encryption, MediaPackage now supports encrypted content keys. You can enable this enhanced content protection in an OriginEndpoint's encryption settings. When this is enabled, MediaPackage indicates to the key server that it requires an encrypted response. To use this, your DRM key provider must support content key encryption. For details on this feature, see the AWS MediaPackage User Guide at https://docs.aws.amazon.com/mediapackage/latest/ug/what-is.html. - -Release v1.15.72 (2018-11-08) -=== - -### Service Client Updates -* `service/dlm`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service documentation - * Documentation updates for events -* `service/medialive`: Updates service API and documentation - * You can now switch a live channel between preconfigured inputs. This means assigned inputs for a running channel can be changed according to a defined schedule. You can also use MP4 files as inputs. - -Release v1.15.71 (2018-11-07) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/dms`: Updates service waiters - * Update the DMS TestConnectionSucceeds waiter. -* `service/ec2`: Updates service API and documentation - * VM Import/Export now supports generating encrypted EBS snapshots, as well as AMIs backed by encrypted EBS snapshots during the import process. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.15.70 (2018-11-06) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * AWS WAF integration with APIGW. Changes for adding webAclArn as a part of Stage output. When the user calls a get-stage or get-stages, webAclArn will also be returned as a part of the output. -* `service/codebuild`: Updates service documentation - * Documentation updates for codebuild -* `service/ec2`: Updates service API and paginators - * You can now launch the new Amazon EC2 memory optimized R5a and general purpose M5a instances families that feature AMD EPYC processors. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/pinpoint`: Updates service API and documentation - * This update adds the ability to send transactional email by using the SendMessage API. Transactional emails are emails that you send directly to specific email addresses. Unlike campaign-based email that you send from Amazon Pinpoint, you don't have to create segments and campaigns in order to send transactional email. -* `service/pinpoint-email`: Adds new service -* `service/waf-regional`: Updates service API and documentation - -Release v1.15.69 (2018-11-05) -=== - -### Service Client Updates -* `service/eks`: Updates service waiters -* `service/serverlessrepo`: Updates service API and documentation - -Release v1.15.68 (2018-11-02) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * ListObjectParents API now supports a bool parameter IncludeAllLinksToEachParent, which if set to true, will return a ParentLinks list instead of a Parents map; BatchRead API now supports ListObjectParents operation. -* `service/rekognition`: Updates service API and documentation - * This release updates the DetectLabels operation. Bounding boxes are now returned for certain objects, a hierarchical taxonomy is now available for labels, and you can now get the version of the detection model used for detection. - -### SDK Bugs -* `internal/ini`: profile names did not allow for ':' character (#2247) - * Fixes an issue where profile names would return an error if the name contained a ':' -Release v1.15.67 (2018-11-01) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Service Catalog integration with AWS Organizations, enables customers to more easily create and manage a portfolio of IT services across an organization. Administrators can now take advantage of the AWS account structure and account groupings configured in AWS Organizations to share Service Catalog Portfolios increasing agility and reducing risk. With this integration the admin user will leverage the trust relationship that exists within the accounts of the Organization to share portfolios to the entire Organization, a specific Organizational Unit or a specific Account. - -### SDK Bugs -* `internal/ini`: removing // comments (#2240) - * removes // comments since that was never supported previously. -Release v1.15.66 (2018-10-31) -=== - -### Service Client Updates -* `service/config`: Updates service API -* `service/greengrass`: Updates service API and documentation - * Greengrass APIs now support bulk deployment operations, and APIs that list definition versions now support pagination. -* `service/mediastore-data`: Updates service API and documentation -* `service/secretsmanager`: Updates service documentation - * Documentation updates for AWS Secrets Manager. - -Release v1.15.65 (2018-10-30) -=== - -### Service Client Updates -* `service/chime`: Adds new service - * This is the initial release for the Amazon Chime AWS SDK. In this release, Amazon Chime adds support for administrative actions on users and accounts. API Documentation is also updated on https://docs.aws.amazon.com/chime/index.html -* `service/dms`: Updates service waiters - * Add waiters for TestConnectionSucceeds, EndpointDeleted, ReplicationInstanceAvailable, ReplicationInstanceDeleted, ReplicationTaskReady, ReplicationTaskStopped, ReplicationTaskRunning and ReplicationTaskDeleted. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * This release adds the listener connection endpoint for SQL Server Always On to the list of fields returned when performing a describe-db-instances operation. - -Release v1.15.64 (2018-10-26) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service documentation -* `service/sagemaker`: Updates service API and documentation - * SageMaker notebook instances can now have a volume size configured. -* `service/ssm`: Updates service API and documentation - * Compliance Severity feature release for State Manager. Users now have the ability to select compliance severity to their association in state manager console or CLI. - -Release v1.15.63 (2018-10-25) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * As part of this release we are introducing EC2 On-Demand Capacity Reservations. With On-Demand Capacity Reservations, customers can reserve the exact EC2 capacity they need, and can keep it only for as long as they need it. - -Release v1.15.62 (2018-10-24) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API, documentation, and paginators -* `service/codestar`: Updates service API and documentation - * This release lets you create projects from source code and a toolchain definition that you provide. - -Release v1.15.61 (2018-10-23) -=== - -### Service Client Updates -* `service/ec2`: Updates service API, documentation, and examples - * Provides customers the ability to Bring Your Own IP (BYOIP) prefix. You can bring part or all of your public IPv4 address range from your on-premises network to your AWS account. You continue to own the address range, but AWS advertises it on the internet. - -Release v1.15.60 (2018-10-22) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/inspector`: Updates service API and documentation - * Finding will be decorated with ec2 related metadata -* `service/shield`: Updates service API and documentation - * AWS Shield Advanced API introduced a new service-specific AccessDeniedException which will be thrown when accessing individual attack information without sufficient permission. - -Release v1.15.59 (2018-10-19) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * Rate Control feature release for State Manager. Users now have the ability to apply rate control parameters similar to run command to their association in state manager console or CLI. -* `service/workspaces`: Updates service API - * Added support for PowerPro and GraphicsPro WorkSpaces bundles. - -### SDK Enhancements -* `aws/request`: Add private ini package (#2210) - * Get rids of go-ini dependency in favor of `internal/ini` package. - -Release v1.15.58 (2018-10-18) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update adds support for creating, managing, and deleting users in the AppStream 2.0 user pool. -* `service/medialive`: Updates service API and documentation - * This release allows you to now turn on Quality-Defined Variable Bitrate (QVBR) encoding for your AWS Elemental MediaLive channels. You can now deliver a consistently high-quality video viewing experience while reducing overall distribution bitrates by using Quality-Defined Variable Bitrate (QVBR) encoding with AWS Elemental MediaLive. QVBR is a video compression technique that automatically adjusts output bitrates to the complexity of source content and only use the bits required to maintain a defined level of quality. This means using QVBR encoding, you can save on distribution cost, while maintaining, or increasing video quality for your viewers. -* `service/route53`: Updates service API and documentation - * This change allows customers to disable health checks. - -Release v1.15.57 (2018-10-17) -=== - -### Service Client Updates -* `service/apigateway`: Updates service documentation - * Documentation updates for API Gateway -* `service/events`: Updates service API and documentation - * AWS Events - AWS Organizations Support in Event-Bus Policies. This release introduces a new parameter in the PutPermission API named Condition. Using the Condition parameter, customers can allow one or more AWS Organizations to access their CloudWatch Events Event-Bus resource. - -Release v1.15.56 (2018-10-16) -=== - -### Service Client Updates -* `service/glue`: Updates service API and documentation - * New Glue APIs for creating, updating, reading and deleting Data Catalog resource-based policies. -* `service/lightsail`: Updates service API and documentation - * Adds support for Lightsail managed databases. -* `service/resource-groups`: Updates service API and documentation - -Release v1.15.55 (2018-10-15) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * Documentation updates for lambda -* `service/rds`: Updates service API and documentation - * This release adds a new parameter to specify the DB instance or cluster parameter group for restore from DB snapshot and restore to point int time operations. For more information, see Amazon RDS Documentation. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * AWS Service Catalog enables you to reduce administrative maintenance and end-user training while adhering to compliance and security measures. With service actions, you as the administrator can enable end users to perform operational tasks, troubleshoot issues, run approved commands, or request permissions within Service Catalog. Service actions are defined using AWS Systems Manager documents, where you have access to pre-defined actions that implement AWS best practices, such asEC2 stop and reboot, as well as the ability to define custom actions. - -Release v1.15.54 (2018-10-12) -=== - -### Service Client Updates -* `service/cloudtrail`: Updates service API and documentation - * The LookupEvents API now supports two new attribute keys: ReadOnly and AccessKeyId - -### SDK Enhancements -* `aws/session`: Add support for credential source(#2201) - * Allows for shared config file to contain `credential_source` with any of the given values `EcsContainer`, `Environment` or `Ec2InstanceMetadata` - -Release v1.15.53 (2018-10-11) -=== - -### Service Client Updates -* `service/athena`: Updates service API and documentation - * 1. GetQueryExecution API changes to return statementType of a submitted Athena query. 2. GetQueryResults API changes to return the number of rows added to a table when a CTAS query is executed. -* `service/directconnect`: Updates service API and documentation - * This release adds support for Jumbo Frames over AWS Direct Connect. You can now set MTU value when creating new virtual interfaces. This release also includes a new API to modify MTU value of existing virtual interfaces. -* `service/ec2`: Updates service API - * You can now launch the smaller-sized G3 instance called g3s.xlarge. G3s.xlarge provides 4 vCPU, 30.5 GB RAM and a NVIDIA Tesla M60 GPU. It is ideal for remote workstations, engineering and architectural applications, and 3D visualizations and rendering for visual effects. -* `service/mediaconvert`: Updates service paginators - * Added Paginators for all the MediaConvert list operations -* `service/transcribe`: Updates service API and documentation - -Release v1.15.52 (2018-10-10) -=== - -### Service Client Updates -* `service/comprehend`: Updates service API -* `service/es`: Updates service API and documentation - * Amazon Elasticsearch Service now supports customer-scheduled service software updates. When new service software becomes available, you can request an update to your domain and benefit from new features more quickly. If you take no action, we update the service software automatically after a certain time frame. -* `service/transcribe`: Updates service API and documentation - -Release v1.15.51 (2018-10-09) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * Adds StartDate, EndDate, and ScheduleTimezone to CreateMaintenanceWindow and UpdateMaintenanceWindow; Adds NextExecutionTime to GetMaintenanceWindow and DescribeMaintenanceWindows; Adds CancelMaintenanceWindowExecution, DescribeMaintenanceWindowSchedule and DescribeMaintenanceWindowsForTarget APIs. - -Release v1.15.50 (2018-10-08) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * We are releasing job execution timeout functionalities to customers. Customer now can set job execution timeout on the job level when creating a job. -* `service/iot-jobs-data`: Updates service API and documentation - -Release v1.15.49 (2018-10-05) -=== - -### Service Client Updates -* `service/ds`: Updates service API and documentation - * SDK changes to create a new type of trust for active directory - -Release v1.15.48 (2018-10-04) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adding support for multi-value parameters in TestInvokeMethod and TestInvokeAuthorizer. -* `service/codebuild`: Updates service API and documentation - * Add resolved source version field in build output -* `service/ssm`: Updates service API and documentation - * Adds RejectedPatchesAction to baseline to enable stricted validation of the rejected Patches List ; Add InstalledRejected and InstallOverrideList to compliance reporting -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway now enables you to specify folders and subfolders when you update your file gateway's view of your S3 objects using the Refresh Cache API. - -Release v1.15.47 (2018-10-02) -=== - -### Service Client Updates -* `service/sagemaker`: Updates service waiters - * Waiter for SageMaker Batch Transform Jobs. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -### SDK Enhancements -* `aws/config`: fix typo in Config struct documentation (#2169) - * fix typo in Config struct documentation in aws-sdk-go/aws/config.go -* `internal/csm`: Add region to api call metrics (#2175) -* `private/model/api`: Use modeled service signing version in code generation (#2162) - * Updates the SDK's code generate to make use of the model's service signature version when generating the client for the service. This allows the SDK to generate a client using the correct signature version, e.g v4 vs s3v4 without the need for additional customizations. - -### SDK Bugs -* `service/cloudfront/sign`: Do not Escape HTML when encode the cloudfront sign policy (#2164) - * Fixes the signer escaping HTML elements `<`, `>`, and `&` in the signature policy incorrectly. Allows use of multiple query parameters in the URL to be signed. - * Fixes #2163 - -Release v1.15.46 (2018-10-01) -=== - -### Service Client Updates -* `service/guardduty`: Updates service API and documentation - * Support optional FindingPublishingFrequency parameter in CreateDetector and UpdateDetector operations, and ClientToken on Create* operations -* `service/rekognition`: Updates service documentation - * Documentation updates for Amazon Rekognition - -Release v1.15.45 (2018-09-28) -=== - -### Service Client Updates -* `service/codestar`: Updates service API and documentation - * This release enables tagging CodeStar Projects at creation. The CreateProject API now includes optional tags parameter. -* `service/ec2`: Updates service API - * You can now use EC2 High Memory instances with 6 TiB memory (u-6tb1.metal), 9 TiB memory (u-9tb1.metal), and 12 TiB memory (u-12tb1.metal), which are ideal for running large in-memory databases, including production deployments of SAP HANA. These instances offer 448 logical processors, where each logical processor is a hyperthread on 224 cores. These instance deliver high networking throughput and lower latency with up to 25 Gbps of aggregate network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking. These instances are EBS-Optimized by default, and support encrypted and unencrypted EBS volumes. This instance is only available in host-tenancy. You will need an EC2 Dedicated Host for this instance type to launch an instance. - -Release v1.15.44 (2018-09-27) -=== - -### Service Client Updates -* `service/apigateway`: Updates service documentation - * Adding support for OpenAPI 3.0 import and export. -* `service/codecommit`: Updates service API and documentation - * This release adds API support for getting the contents of a file, getting the contents of a folder, and for deleting a file in an AWS CodeCommit repository. -* `service/mq`: Updates service API and documentation - * Amazon MQ supports ActiveMQ 5.15.6, in addition to 5.15.0. Automatic minor version upgrades can be toggled. Updated the documentation. - -Release v1.15.43 (2018-09-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * AWS Glue now supports data encryption at rest for ETL jobs and development endpoints. With encryption enabled, when you run ETL jobs, or development endpoints, Glue will use AWS KMS keys to write encrypted data at rest. You can also encrypt the metadata stored in the Glue Data Catalog using keys that you manage with AWS KMS. Additionally, you can use AWS KMS keys to encrypt the logs generated by crawlers and ETL jobs as well as encrypt ETL job bookmarks. Encryption settings for Glue crawlers, ETL jobs, and development endpoints can be configured using the security configurations in Glue. Glue Data Catalog encryption can be enabled via the settings for the Glue Data Catalog. -* `service/opsworkscm`: Updates service API and documentation - * This release introduces a new API called ExportServerEngineAttribute to Opsworks-CM. You can use this API call to export engine specific attributes like the UserData script used for unattended bootstrapping of new nodes that connect to the server. -* `service/rds`: Updates service API and documentation - * This release includes Deletion Protection for RDS databases. -* `service/sqs`: Updates service API and documentation - * Documentation updates for Amazon SQS. - -### SDK Enhancements -* `private/protocol/restjson/restjson`: Use json.Decoder to decrease memory allocation (#2141) - * Update RESTJSON protocol unmarshaler to use json.Decoder instead of ioutil.ReadAll to reduce allocations. -* `private/protocol/jsonrpc/jsonrpc`: Use json.Decoder to decrease memory allocation (#2142) - * Update JSONPRC protocol unmarshaler to use json.Decoder instead of ioutil.ReadAll to reduce allocations. - -Release v1.15.42 (2018-09-25) -=== - -### Service Client Updates -* `service/cloudfront`: Updates service documentation - * Documentation updates for cloudfront -* `service/ds`: Updates service API and documentation - * API changes related to launch of cross account for Directory Service. -* `service/ec2`: Updates service API and documentation - * Add pagination support for ec2.describe-route-tables API. - -Release v1.15.41 (2018-09-24) -=== - -### Service Client Updates -* `service/connect`: Updates service API, documentation, and paginators -* `service/rds`: Updates service API and documentation - * Adds DB engine version requirements for option group option settings, and specifies if an option setting requires a value. - -Release v1.15.40 (2018-09-21) -=== - -### Service Client Updates -* `service/mediaconvert`: Updates service API and documentation - * To offer lower prices for predictable, non-urgent workloads, we propose the concept of Reserved Transcode pricing. Reserved Transcode pricing Reserved Transcoding pricing would offer the customer access to a fixed parallel processing capacity for a fixed monthly rate. This capacity would be stated in terms of number of Reserved Transcode Slots (RTSs). One RTS would be able to process one job at a time for a fixed monthly fee. - -Release v1.15.39 (2018-09-20) -=== - -### Service Client Updates -* `service/ds`: Updates service API and documentation - * Added CreateLogSubscription, DeleteLogSubscription, and ListLogSubscriptions APIs for Microsoft AD. Customers can now opt in to have Windows security event logs from the domain controllers forwarded to a log group in their account. -* `service/ec2`: Updates service API - * You can now launch f1.4xlarge, a new instance size within the existing f1 family which provides two Xilinx Virtex Field Programmable Arrays (FPGAs) for acceleration. FPGA acceleration provide additional performance and time sensitivity for specialized accelerated workloads such as clinical genomics and real-time video processing. F1.4xlarge instances are available in the US East (N. Virginia), US West (Oregon), GovCloud (US), and EU West (Dublin) AWS Regions. -* `service/rds`: Updates service API and documentation - * This launch enables RDS start-db-cluster and stop-db-cluster. Stopping and starting Amazon Aurora clusters helps you manage costs for development and test environments. You can temporarily stop all the DB instances in your cluster, instead of setting up and tearing down all the DB instances each time that you use the cluster. - -Release v1.15.38 (2018-09-19) -=== - -### Service Client Updates -* `service/monitoring`: Updates service API and documentation - * Amazon CloudWatch adds the ability to request png image snapshots of metric widgets using the GetMetricWidgetImage API. -* `service/organizations`: Updates service API and documentation - * Introducing a new exception - AccountOwnerNotVerifiedException which will be returned for InviteAccountToOrganization call for unverified accounts. -* `service/s3`: Updates service API and documentation - * S3 Cross Region Replication now allows customers to use S3 object tags to filter the scope of replication. By using S3 object tags, customers can identify individual objects for replication across AWS Regions for compliance and data protection. Cross Region Replication for S3 enables automatic and asynchronous replication of objects to another AWS Region, and with this release customers can replicate at a bucket level, prefix level or by using object tags. - -Release v1.15.37 (2018-09-18) -=== - -### Service Client Updates -* `service/es`: Updates service API and documentation - * Amazon Elasticsearch Service adds support for node-to-node encryption for new domains running Elasticsearch version 6.0 and above -* `service/rekognition`: Updates service API and documentation - * This release updates the Amazon Rekognition IndexFaces API operation. It introduces a QualityFilter parameter that allows you to automatically filter out detected faces that are deemed to be of low quality by Amazon Rekognition. The quality bar is based on a variety of common use cases. You can filter low-quality detected faces by setting QualityFilter to AUTO, which is also the default setting. To index all detected faces regardless of quality, you can specify NONE. This release also provides a MaxFaces parameter that is useful when you want to only index the most prominent and largest faces in an image and don't want to index other faces detected in the image, such as smaller faces belonging to people standing in the background. - -Release v1.15.36 (2018-09-17) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Support build logs configuration. -* `service/ec2`: Updates service API and documentation - * Added support for customers to tag EC2 Dedicated Hosts on creation. -* `service/ecs`: Updates service API and documentation - * This release of Amazon Elastic Container Service (Amazon ECS) introduces support for additional Docker flags as Task Definition parameters. Customers can now configure their ECS Tasks to use systemControls (sysctl), pseudoTerminal (tty), and interactive (i) Docker flags. -* `service/elasticache`: Updates service API and documentation - * ElastiCache for Redis added support for adding and removing read-replicas from any cluster with no cluster downtime, Shard naming: ElastiCache for Redis customers have the option of allowing ElastiCache to create names for their node groups (shards) or generating their own node group names. For more information, see https:// docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_NodeGroupConfiguration.html, ShardsToRetain: When reducing the number of node groups (shards) in an ElastiCache for Redis (cluster mode enabled) you have the option of specifying which node groups to retain or which node groups to remove. For more information, see https:// docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ModifyReplicationGroupShardConfiguration.html, ReservationARN: ReservedNode includes an ARN, ReservationARN, member which identifies the reserved node. For more information, see https:// docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ReservedCacheNode.html -* `service/elastictranscoder`: Updates service API, documentation, and paginators - * Added support for MP2 container -* `service/monitoring`: Updates service API and documentation - * Amazon CloudWatch adds the ability to publish values and counts using PutMetricData -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.15.35 (2018-09-13) -=== - -### Service Client Updates -* `service/polly`: Updates service API and documentation - * Amazon Polly adds Mandarin Chinese language support with new female voice - "Zhiyu" - -Release v1.15.34 (2018-09-12) -=== - -### Service Client Updates -* `service/connect`: Updates service API and documentation -* `service/ec2`: Updates service API, documentation, and paginators - * Pagination Support for DescribeNetworkInterfaces API -* `service/email`: Updates service documentation - * Documentation updates for Amazon Simple Email Service -* `service/fms`: Updates service API and documentation - -Release v1.15.33 (2018-09-11) -=== - -### Service Client Updates -* `service/opsworkscm`: Updates service documentation - * Documentation updates for opsworkscm -* `service/ssm`: Updates service API and documentation - * Session Manager is a fully managed AWS Systems Manager capability that provides interactive one-click access to Amazon EC2 Linux and Windows instances. - -Release v1.15.32 (2018-09-10) -=== - -### Service Client Updates -* `service/cloudhsmv2`: Updates service API and documentation - * With this release, we are adding 2 new APIs. DeleteBackup deletes a specified AWS CloudHSM backup. A backup can be restored up to 7 days after the DeleteBackup request. During this 7-day period, the backup will be in state PENDING_DELETION. Backups can be restored using the RestoreBackup API, which will move the backup from state PENDING_DELETION back to ACTIVE. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/redshift`: Updates service API and documentation - * Adding support to Redshift to change the encryption type after cluster creation completes. - -Release v1.15.31 (2018-09-07) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/logs`: Updates service API and documentation - * * Adding a log prefix parameter for filter log events API and minor updates to the documentation - -### SDK Enhancements -* `private/protocol/json/jsonutil`: Use json.Decoder to decrease memory allocation ([#2115](https://github.com/aws/aws-sdk-go/pull/2115)) - * Updates the SDK's JSON protocol marshaler to use `json.Decoder` instead of `ioutil.ReadAll`. This reduces the memory unmarshaling JSON payloads by about 50%. - * Fix [#2114](https://github.com/aws/aws-sdk-go/pull/2114) - -Release v1.15.29 (2018-09-06) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for Active X-Ray with API Gateway -* `service/codecommit`: Updates service API and documentation - * This release adds additional optional fields to the pull request APIs. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediaconvert`: Updates service API and documentation - * This release adds support for Cost Allocation through tagging and also enables adding, editing, and removal of tags from the MediaConvert console. - -### SDK Enhancements -* `private/protocol`: Serialization errors will now be wrapped in `awserr.RequestFailure` types ([#2135](https://github.com/aws/aws-sdk-go/pull/2135)) - * Updates the SDK protocol unmarshaling to handle the `SerializationError` as a request failure allowing for inspection of `requestID`s and status codes. - -Release v1.15.28 (2018-09-05) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Added support for enabling persistent application settings for a stack. When these settings are enabled, changes that users make to applications and Windows settings are automatically saved after each session and applied to the next session. -* `service/dynamodb`: Updates service API and documentation - * New feature for Amazon DynamoDB. -* `service/elasticloadbalancing`: Updates service API and documentation -* `service/rds`: Updates service documentation - * Fix broken links in the RDS CLI Reference to the Aurora User Guide -* `service/s3`: Updates service API, documentation, and examples - * Parquet input format support added for the SelectObjectContent API - -### SDK Enhancements -* `private/model/api`: Add "Deprecated" to deprecated API operation and type doc strings ([#2129](https://github.com/aws/aws-sdk-go/pull/2129)) - * Updates the SDK's code generation to include `Deprecated` in the documentation string for API operations and types that are depercated by a service. - * Related to [golang/go#10909](https://github.com/golang/go/issues/10909) - * https://blog.golang.org/godoc-documenting-go-code - -### SDK Bugs -* `service/s3/s3manager`: Fix Download Manager with iterator docs ([#2131](https://github.com/aws/aws-sdk-go/pull/2131)) - * Fixes the S3 Download manager's DownloadWithIterator documentation example. - * Fixes [#1824](https://github.com/aws/aws-sdk-go/issues/1824) -Release v1.15.27 (2018-09-04) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Updating cross references for the new Aurora User Guide. -* `service/rekognition`: Updates service API and documentation - * This release introduces a new API called DescribeCollection to Amazon Rekognition. You can use DescribeCollection to get information about an existing face collection. Given the ID for a face collection, DescribeCollection returns the following information: the number of faces indexed into the collection, the version of the face detection model used by the collection, the Amazon Resource Name (ARN) of the collection and the creation date/time of the collection. - -Release v1.15.26 (2018-08-31) -=== - -### Service Client Updates -* `service/eks`: Updates service API and documentation -* `service/waf`: Updates service API and documentation - * This change includes support for the WAF FullLogging feature through which Customers will have access to all the logs of requests that are inspected by a WAF WebACL. The new APIs allow Customers to manage association of a WebACL with one or more supported "LogDestination" and redact any request fields from the logs. -* `service/waf-regional`: Updates service API and documentation - -Release v1.15.25 (2018-08-30) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Support multiple sources and artifacts for CodeBuild projects. -* `service/sagemaker`: Updates service API and documentation - * VolumeKmsKeyId now available in Batch Transform Job - -Release v1.15.24 (2018-08-29) -=== - -### Service Client Updates -* `service/glue`: Updates service API and documentation - * AWS Glue now supports data encryption at rest for ETL jobs and development endpoints. With encryption enabled, when you run ETL jobs, or development endpoints, Glue will use AWS KMS keys to write encrypted data at rest. You can also encrypt the metadata stored in the Glue Data Catalog using keys that you manage with AWS KMS. Additionally, you can use AWS KMS keys to encrypt the logs generated by crawlers and ETL jobs as well as encrypt ETL job bookmarks. Encryption settings for Glue crawlers, ETL jobs, and development endpoints can be configured using the security configurations in Glue. Glue Data Catalog encryption can be enabled via the settings for the Glue Data Catalog. -* `service/mediapackage`: Updates service API and documentation - * MediaPackage now provides input redundancy. Channels have two ingest endpoints that can receive input from encoders. OriginEndpoints pick one of the inputs receiving content for playback and automatically switch to the other input if the active input stops receiving content. Refer to the User Guide (https://docs.aws.amazon.com/mediapackage/latest/ug/what-is.html) for more details on this feature. -* `service/runtime.sagemaker`: Updates service API and documentation - -Release v1.15.23 (2018-08-28) -=== - -### Service Client Updates -* `service/glue`: Updates service API and documentation - * New Glue APIs for creating, updating, reading and deleting Data Catalog resource-based policies. -* `service/xray`: Updates service API and documentation - * Support for new APIs that enable management of sampling rules. - -Release v1.15.22 (2018-08-27) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API and documentation - * This release adds support to create a Stream and Code signing for Amazon FreeRTOS job along with Over-the-air updates. -* `service/iotanalytics`: Updates service API, documentation, and paginators -* `service/redshift`: Updates service documentation - * Documentation updates for redshift -* `service/signer`: Adds new service - * AWS Signer is a new feature that allows Amazon FreeRTOS (AFR) Over The Air (OTA) customers to cryptographically sign code using code-signing certificates managed by AWS Certificate Manager. - -Release v1.15.21 (2018-08-25) -=== - -### Service Client Updates -* `service/glue`: Updates service API and documentation - * AWS Glue now supports data encryption at rest for ETL jobs and development endpoints. With encryption enabled, when you run ETL jobs, or development endpoints, Glue will use AWS KMS keys to write encrypted data at rest. You can also encrypt the metadata stored in the Glue Data Catalog using keys that you manage with AWS KMS. Additionally, you can use AWS KMS keys to encrypt the logs generated by crawlers and ETL jobs as well as encrypt ETL job bookmarks. Encryption settings for Glue crawlers, ETL jobs, and development endpoints can be configured using the security configurations in Glue. Glue Data Catalog encryption can be enabled via the settings for the Glue Data Catalog. - -Release v1.15.20 (2018-08-24) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/events`: Updates service API and documentation - * Added Fargate and NetworkConfiguration support to EcsParameters. - -Release v1.15.19 (2018-08-23) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * This release adds support for IoT Thing Group Indexing and Searching functionality. -* `service/iotanalytics`: Updates service API and documentation -* `service/lex-models`: Updates service API -* `service/medialive`: Updates service API, documentation, and paginators - * Adds two APIs for working with Channel Schedules: BatchUpdateSchedule and DescribeSchedule. These APIs allow scheduling actions for SCTE-35 message insertion and for static image overlays. -* `service/rekognition`: Updates service API, documentation, and examples - * This release introduces a new API called DescribeCollection to Amazon Rekognition. You can use DescribeCollection to get information about an existing face collection. Given the ID for a face collection, DescribeCollection returns the following information: the number of faces indexed into the collection, the version of the face detection model used by the collection, the Amazon Resource Name (ARN) of the collection and the creation date/time of the collection. - -Release v1.15.18 (2018-08-22) -=== - -### Service Client Updates -* `service/snowball`: Updates service API - * Snowball job states allow customers to track the status of the Snowball job. We are launching a new Snowball job state "WithSortingFacility"! When customer returns the Snowball to AWS, the device first goes to a sorting facility before it reaches an AWS data center. Many customers have requested us to add a new state to reflect the presence of the device at the sorting facility for better tracking. Today when a customer returns the Snowball, the state first changes from "InTransitToAWS" to "WithAWS". With the addition of new state, the device will move from "InTransitToAWS" to "WithAWSSortingFacility", and then to "WithAWS". There are no other changes to the API at this time besides adding this new state. - -Release v1.15.17 (2018-08-21) -=== - -### Service Client Updates -* `service/dlm`: Updates service documentation -* `service/ec2`: Updates service API - * Added support for T3 Instance type in EC2. To learn more about T3 instances, please see https://aws.amazon.com/ec2/instance-types/t3/ -* `service/elasticbeanstalk`: Updates service API, documentation, and examples - * Elastic Beanstalk adds the "Privileged" field to the "CPUUtilization" type, to support enhanced health reporting in Windows environments. -* `service/rds`: Updates service paginators - * Adds a paginator for the DescribeDBClusters operation. - -Release v1.15.16 (2018-08-20) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service API and documentation - * Added SSESpecification block to update-table command which allows users to modify table Server-Side Encryption. Added two new fields (SSEType and KMSMasterKeyId) to SSESpecification block used by create-table and update-table commands. Added new SSEDescription Status value UPDATING. -* `service/mediaconvert`: Updates service API - * This release fixes backward-incompatible changes from a previous release. That previous release changed non-required job settings to required, which prevented jobs and job templates from merging correctly. The current change removes validation of required settings from the SDK and instead centralizes the validation in the service API. For information on required settings, see the Resources chapter of the AWS Elemental MediaConvert API Reference https://docs.aws.amazon.com/mediaconvert/latest/apireference/resources.html - -Release v1.15.15 (2018-08-17) -=== - -### Service Client Updates -* `service/dax`: Updates service API - * DAX CreateClusterRequest is updated to include IamRoleArn as a required request parameter. -* `service/sagemaker`: Updates service API and documentation - * Added an optional boolean parameter, 'DisassociateLifecycleConfig', to the UpdateNotebookInstance operation. When set to true, the lifecycle configuration associated with the notebook instance will be removed, allowing a new one to be set via a new 'LifecycleConfigName' parameter. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for Secrets Manager - -Release v1.15.14 (2018-08-16) -=== - -### Service Client Updates -* `service/discovery`: Updates service API, documentation, and paginators - * The Application Discovery Service's Continuous Export APIs allow you to analyze your on-premises server inventory data, including system performance and network dependencies, in Amazon Athena. -* `service/ec2`: Updates service API - * The 'Attribute' parameter DescribeVolumeAttribute request has been marked as required - the API has always required this parameter, but up until now this wasn't reflected appropriately in the SDK. -* `service/mediaconvert`: Updates service API and documentation - * Added WriteSegmentTimelineInRepresentation option for Dash Outputs -* `service/redshift`: Updates service API and documentation - * You can now resize your Amazon Redshift cluster quickly. With the new ResizeCluster action, your cluster is available for read and write operations within minutes -* `service/ssm`: Updates service API and documentation - * AWS Systems Manager Inventory now supports groups to quickly see a count of which managed instances are and arent configured to collect one or more Inventory types - -Release v1.15.13 (2018-08-15) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Support for running tests in a custom environment with live logs/video streaming, full test features parity and reduction in overall test execution time. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.15.12 (2018-08-14) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Add batch operations for creating/updating and deleting scheduled scaling actions. -* `service/cloudfront`: Adds new service - * Lambda@Edge Now Provides You Access to the Request Body for HTTP POST/PUT Processing. With this feature, you can now offload more origin logic to the edge and improve end-user latency. Developers typically use Web/HTML forms or Web Beacons/Bugs as a mechanism to collect data from the end users and then process that data at their origins servers. For example, if you are collecting end user behavior data through a web beacon on your website, you can use this feature to access the user behavior data and directly log it to an Amazon Kinesis Firehose endpoint from the Lambda function, thereby simplifying your origin infrastructure. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/es`: Updates service API, documentation, and paginators - * Amazon Elasticsearch Service adds support for no downtime, in-place upgrade for Elasticsearch version 5.1 and above. - -Release v1.15.11 (2018-08-13) -=== - -### Service Client Updates -* `service/sagemaker`: Updates service API and documentation - * SageMaker updated the default endpoint URL to support Private Link via the CLI/SDK. - -Release v1.15.10 (2018-08-10) -=== - -### Service Client Updates -* `service/mediaconvert`: Updates service API and documentation - * This release adds support for a new rate control mode, Quality-Defined Variable Bitrate (QVBR) encoding, includes updates to optimize transcoding performance, and resolves previously reported bugs. -* `service/rds`: Updates service documentation - * Documentation updates for rds - -Release v1.15.9 (2018-08-09) -=== - -### Service Client Updates -* `service/dax`: Updates service API and documentation - * Add the SSESpecification field to CreateCluster to allow creation of clusters with server-side encryption, and add the SSEDescription field to DescribeClusters to display the status of server-side encryption for a cluster. -* `service/ecs`: Updates service API and documentation - * This release of Amazon Elastic Container Service (Amazon ECS) introduces support for Docker volumes and Docker volume drivers. Customers can now configure their ECS Tasks to use Docker volumes, enabling stateful and storage-intensive applications to be deployed on ECS. -* `service/rds`: Updates service API, documentation, and examples - * Launch RDS Aurora Serverless - -Release v1.15.8 (2018-08-08) -=== - -### Service Client Updates -* `service/secretsmanager`: Updates service API and documentation - * This release introduces a ForceDeleteWithoutRecovery parameter to the DeleteSecret API enabling customers to force the deletion of a secret without any recovery window -* `service/ssm`: Updates service API and documentation - * AWS Systems Manager Automation is launching two new features for Automation Execution Rate Control based on tags and customized parameter maps. With the first feature, customer can target their resources by specifying a Tag with Key/Value. With the second feature, Parameter maps rate control, customers can benefit from customization of input parameters. - -Release v1.15.7 (2018-08-07) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Release semantic versioning feature for CodeBuild -* `service/ec2`: Updates service API and documentation - * Amazon VPC Flow Logs adds support for delivering flow logs directly to S3 -* `service/logs`: Updates service API and documentation - * Documentation Update -* `service/pinpoint`: Updates service API and documentation - * This release includes a new batch API call for Amazon Pinpoint which can be used to update endpoints and submit events. This call will accept events from clients such as mobile devices and AWS SDKs. This call will accept requests which has multiple endpoints and multiple events attached to those endpoints in a single call. This call will update the endpoints attached and will ingest events for those endpoints. The response from this call will be a multipart response per endpoint/per event submitted. -* `service/ssm`: Updates service API and documentation - * Two new filters ExecutionStage and DocumentName will be added to ListCommands so that customers will have more approaches to query their commands. - -Release v1.15.6 (2018-08-06) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service API and documentation - * Amazon DynamoDB Point-in-time recovery (PITR) provides continuous backups of your table data. DynamoDB now supports the ability to self-restore a deleted PITR enabled table. Now, when a table with PITR enabled is deleted, a system backup is automatically created and retained for 35 days (at no additional cost). System backups allow you to restore the deleted PITR enabled table to the state it was just before the point of deletion. For more information, see the Amazon DynamoDB Developer Guide. -* `service/health`: Updates service API, documentation, and paginators - * Updates the ARN structure vended by AWS Health API. All ARNs will now include the service and type code of the associated event, as vended by DescribeEventTypes. - -Release v1.15.5 (2018-08-03) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API and documentation - -Release v1.15.4 (2018-08-02) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API, documentation, and paginators - * This update introduces SubscribeToShard and RegisterStreamConsumer APIs which allows for retrieving records on a data stream over HTTP2 with enhanced fan-out capabilities. With this new feature the Java SDK now supports event streaming natively which will allow you to define payload and exception structures on the client over a persistent connection. For more information, see Developing Consumers with Enhanced Fan-Out in the Kinesis Developer Guide. -* `service/polly`: Updates service API and documentation - * Amazon Polly enables female voice Aditi to speak Hindi language -* `service/resource-groups`: Updates service API and documentation -* `service/ssm`: Updates service API and documentation - * This release updates AWS Systems Manager APIs to let customers create and use service-linked roles to register and edit Maintenance Window tasks. - -Release v1.15.3 (2018-08-01) -=== - -### Service Client Updates -* `service/storagegateway`: Updates service API, documentation, and examples - * AWS Storage Gateway now enables you to create stored volumes with AWS KMS support. -* `service/transcribe`: Updates service API and documentation - -Release v1.15.2 (2018-07-31) -=== - -### Service Client Updates -* `service/connect`: Updates service API and documentation -* `service/es`: Updates service API and documentation - * Amazon Elasticsearch Service adds support for enabling Elasticsearch error logs, providing you valuable information for troubleshooting your Elasticsearch domains quickly and easily. These logs are published to the Amazon CloudWatch Logs service and can be turned on or off at will. -* `service/iot`: Updates service API and documentation - * As part of this release we are introducing a new IoT security service, AWS IoT Device Defender, and extending capability of AWS IoT to support Step Functions rule action. The AWS IoT Device Defender is a fully managed service that helps you secure your fleet of IoT devices. For more details on this new service, go to https://aws.amazon.com/iot-device-defender. The Step Functions rule action lets you start an execution of AWS Step Functions state machine from a rule. -* `service/kms`: Updates service API and documentation - * Added a KeyID parameter to the ListAliases operation. This parameter allows users to list only the aliases that refer to a particular AWS KMS customer master key. All other functionality remains intact. -* `service/mediaconvert`: Updates service API and documentation - * Fixes an issue with modeled timestamps being labeled with the incorrect format. - -### SDK Enhancements -* `service/dynamodb/dynamodbattribute`: Add support for custom struct tag keys([#2054](https://github.com/aws/aws-sdk-go/pull/2054)) - * Adds support for (un)marshaling Go types using custom struct tag keys. The new `MarshalOptions.TagKey` allows the user to specify the tag key to use when (un)marshaling struct fields. Adds support for struct tags such as `yaml`, `toml`, etc. Support for these keys are in name only, and require the tag value format and values to be supported by the package's Marshalers. - -### SDK Bugs -* `aws/endpoints`: Add workaround for AWS China Application Autoscaling ([#2080](https://github.com/aws/aws-sdk-go/pull/2080)) - * Adds workaround to correct the endpoint for Application Autoscaling running in AWS China. This will allow your application to make API calls to Application Autoscaling service in AWS China. - * Fixes [#2079](https://github.com/aws/aws-sdk-go/issues/2079) - * Fixes [#1957](https://github.com/aws/aws-sdk-go/issues/1957) -* `private/protocol/xml/xmlutil`: Fix SDK marshaling of empty types ([#2081](https://github.com/aws/aws-sdk-go/pull/2081)) - * Fixes the SDK's marshaling of types without members. This corrects the issue where the SDK would not marshal an XML tag for a type, if that type did not have any exported members. - * Fixes [#2015](https://github.com/aws/aws-sdk-go/issues/2015) -Release v1.15.1 (2018-07-30) -=== - -### Service Client Updates -* `service/cloudhsmv2`: Updates service API and documentation - * This update to the AWS CloudHSM API adds copy-backup-to-region, which allows you to copy a backup of a cluster from one region to another. The copied backup can be used in the destination region to create a new AWS CloudHSM cluster as a clone of the original cluster. -* `service/directconnect`: Updates service API and documentation - * 1. awsDeviceV2 field is introduced for Connection/Lag/Interconnect/VirtualInterface/Bgp Objects, while deprecating the awsDevice field for Connection/Lag/Interconnect Objects. 2. region field is introduced for VirtualInterface/Location objects -* `service/glacier`: Updates service API and documentation - * Documentation updates for glacier -* `service/glue`: Updates service API and documentation - * Glue Development Endpoints now support association of multiple SSH public keys with a development endpoint. -* `service/iot`: Updates service API and documentation - * get rid of documentParameters field from CreateJob API -* `service/mq`: Updates service API, documentation, and paginators - * Modified the CreateBroker, UpdateBroker, and DescribeBroker operations to support integration with Amazon CloudWatch Logs. Added a field to indicate the IP address(es) that correspond to wire-level endpoints of broker instances. While a single-instance broker has one IP address, an active/standby broker for high availability has 2 IP addresses. Added fields to indicate the time when resources were created. Updated documentation for Amazon MQ. -* `service/sagemaker`: Updates service API and documentation - * Added SecondaryStatusTransitions to DescribeTrainingJob to provide more visibility into SageMaker training job progress and lifecycle. - -Release v1.15.0 (2018-07-26) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Add artifacts encryptionDisabled and build encryptionKey. -* `service/ec2`: Updates service API and documentation - * This change provides the EC2/Spot customers with two new allocation strategies -- LowestN for Spot instances, and OD priority for on-demand instances. -* `service/greengrass`: Updates service documentation - * Documentation updates for Greengrass Local Resource Access feature -* `service/inspector`: Updates service API and documentation - * inspector will return ServiceTemporarilyUnavailableException when service is under stress -* `service/redshift`: Updates service API and documentation - * When we make a new version of Amazon Redshift available, we update your cluster during its maintenance window. By selecting a maintenance track, you control whether we update your cluster with the most recent approved release, or with the previous release. The two values for maintenance track are current and trailing. If you choose the current track, your cluster is updated with the latest approved release. If you choose the trailing track, your cluster is updated with the release that was approved previously.The new API operation for managing maintenance tracks for a cluster is DescribeClusterTracks. In addition, the following API operations have new MaintenanceTrackName parameters: Cluster, PendingModifiedValues, ModifyCluster, RestoreFromClusterSnapshot, CreateCluster, Snapshot -* `service/ssm`: Updates service API and documentation - * This release updates AWS Systems Manager APIs to allow customers to attach labels to history parameter records and reference history parameter records via labels. It also adds Parameter Store integration with AWS Secrets Manager to allow referencing and retrieving AWS Secrets Manager's secrets from Parameter Store. - -### SDK Features -* `private/model/api`: SDK APIs input/output are not consistently generated ([#2073](https://github.com/aws/aws-sdk-go/pull/2073)) - * Updates the SDK's API code generation to generate the API input and output types consistently. This ensures that the SDK will no longer rename input/output types unexpectedly as in [#2070](https://github.com/aws/aws-sdk-go/issues/2070). SDK API input and output parameter types will always be the API name with a suffix of Input and Output. - * Existing service APIs which were incorrectly modeled have been preserved to ensure they do not break. - * Fixes [#2070](https://github.com/aws/aws-sdk-go/issues/2070) - -### SDK Enhancements -* `service/s3/s3manager`: Document default behavior for Upload's MaxNumParts ([#2077](https://github.com/aws/aws-sdk-go/issues/2077)) - * Updates the S3 Upload Manager's default behavior for MaxNumParts, and ensures that the Uploader.MaxNumPart's member value is initialized properly if the type was created via struct initialization instead of using the NewUploader function. - * Fixes [#2015](https://github.com/aws/aws-sdk-go/issues/2015) - -### SDK Bugs -* `private/model/api`: SDK APIs input/output are not consistently generated ([#2073](https://github.com/aws/aws-sdk-go/pull/2073)) - * Fixes EFS service breaking change in v1.14.26 where `FileSystemDescription` was incorrectly renamed to `UpdateFileSystemOutput. - * Fixes [#2070](https://github.com/aws/aws-sdk-go/issues/2070) -Release v1.14.33 (2018-07-25) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * R5 is the successor to R4 in EC2's memory-optimized instance family. R5d is a variant of R5 that has local NVMe SSD. Z1d instances deliver both high compute and high memory. Z1d instances use custom Intel Xeon Scalable Processors running at up to 4.0 GHz, powered by sustained all-core Turbo Boost. They are available in 6 sizes, with up to 48 vCPUs, 384 GiB of memory, and 1.8 TB of local NVMe storage. -* `service/ecs`: Updates service API and documentation - * This release of Amazon Elastic Container Service (Amazon ECS) introduces support for private registry authentication using AWS Secrets Manager. With private registry authentication, private Docker images can be used in a task definition. -* `service/elasticloadbalancingv2`: Updates service API and documentation - -Release v1.14.32 (2018-07-24) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service API and documentation - * With this SDK update, APIs UpdateGlobalTableSettings and DescribeGlobalTableSettings now allow consistently configuring AutoScaling settings for a DynamoDB global table. Previously, they would only allow consistently setting IOPS. Now new APIs are being released, existing APIs are being extended. - -Release v1.14.31 (2018-07-20) -=== - -### Service Client Updates -* `service/config`: Updates service API -* `service/dlm`: Updates service documentation - -### SDK Enhancements -* `service/s3/s3manager`: Add documentation for sequential download [#2065](https://github.com/aws/aws-sdk-go/pull/2065) - * Adds documentation for downloading object sequentially with the S3 download manager. - -Release v1.14.30 (2018-07-19) -=== - -### Service Client Updates -* `service/mediapackage`: Updates service API and documentation - * Adds support for DASH OriginEnpoints with multiple media presentation description periods triggered by presence of SCTE-35 ad markers in Channel input streams. - -### SDK Enhancements -* `aws/default`: Add helper to get default provider chain list of credential providers ([#2059](https://github.com/aws/aws-sdk-go/issues/2051)) - * Exports the default provider chain list of providers so it can be used to compose custom chains of credential providers. - * Fixes [#2051](https://github.com/aws/aws-sdk-go/issues/2051) - -Release v1.14.29 (2018-07-18) -=== - -### Service Client Updates -* `service/iotanalytics`: Updates service API and documentation - -Release v1.14.28 (2018-07-17) -=== - -### Service Client Updates -* `service/comprehend`: Updates service API and documentation -* `service/polly`: Updates service API, documentation, and paginators - * Amazon Polly adds new API for asynchronous synthesis to S3 -* `service/sagemaker`: Updates service API, documentation, and paginators - * Amazon SageMaker has added the capability for customers to run fully-managed, high-throughput batch transform machine learning models with a simple API call. Batch Transform is ideal for high-throughput workloads and predictions in non-real-time scenarios where data is accumulated over a period of time for offline processing. -* `service/snowball`: Updates service API and documentation - * AWS Snowball Edge announces the availability of Amazon EC2 compute instances that run on the device. AWS Snowball Edge is a 100-TB ruggedized device built to transfer data into and out of AWS with optional support for local Lambda-based compute functions. With this feature, developers and administrators can run their EC2-based applications on the device providing them with an end to end vertically integrated AWS experience. Designed for data pre-processing, compression, machine learning, and data collection applications, these new instances, called SBE1 instances, feature 1.8 GHz Intel Xeon D processors up to 16 vCPUs, and 32 GB of memory. The SBE1 instance type is available in four sizes and multiple instances can be run on the device at the same time. Customers can now run compute instances using the same Amazon Machine Images (AMIs) that are used in Amazon EC2. - -Release v1.14.27 (2018-07-13) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and paginators - * This API update adds support for sharing AppStream images across AWS accounts within the same region. -* `service/kinesis-video-archived-media`: Updates service API and documentation -* `service/kinesisvideo`: Updates service API and documentation - * Adds support for HLS video playback of Kinesis Video streams using the KinesisVideo client by including "GET_HLS_STREAMING_SESSION_URL" as an additional APIName parameter in the GetDataEndpoint input. - -Release v1.14.26 (2018-07-12) -=== - -### Service Client Updates -* `service/appsync`: Updates service API and documentation -* `service/codebuild`: Updates service API - * Update CodeBuild CreateProject API - serviceRole is a required input -* `service/dlm`: Adds new service -* `service/elasticfilesystem`: Updates service API and documentation - * Amazon EFS now allows you to instantly provision the throughput required for your applications independent of the amount of data stored in your file system, allowing you to optimize throughput for your applications performance needs. Starting today, you can provision the throughput your applications require quickly with a few simple steps using AWS Console, AWS CLI or AWS API to achieve consistent performance. -* `service/elasticmapreduce`: Updates service API and documentation - * Documentation updates for EMR. -* `service/iam`: Updates service API and documentation - * SDK release to support IAM delegated administrator feature. The feature lets customers attach permissions boundary to IAM principals. The IAM principals cannot operate exceeding the permission specified in permissions boundary. - -### SDK Enhancements -* `aws/credentials/ec2rolecreds`: Avoid unnecessary redirect [#2037](https://github.com/aws/aws-sdk-go/pull/2037) - * This removes the unnecessary redirect for /latest/meta-data/iam/security-credentials/ - -Release v1.14.25 (2018-07-11) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Support for fine grain throttling for API gateway. -* `service/ce`: Updates service API and documentation -* `service/s3`: Updates service API and documentation - * S3 Select support for BZIP2 compressed input files -* `service/ssm`: Updates service API and documentation - * Support Conditional Branching OnFailure for SSM Automation - -Release v1.14.24 (2018-07-10) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, paginators, and examples - * This API update adds pagination to the DescribeImages API to support future features and enhancements. -* `service/codebuild`: Updates service API and documentation - * API changes to CodeBuild service, support report build status for Github sources -* `service/ec2`: Updates service API and documentation - * Support CpuOptions field in Launch Template data and allow Launch Template name to contain hyphen. -* `service/glue`: Updates service API and documentation - * AWS Glue adds the ability to crawl DynamoDB tables. -* `service/opsworks`: Updates service documentation - * Documentation updates for AWS OpsWorks Stacks. - -Release v1.14.23 (2018-07-10) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service documentation - -Release v1.14.22 (2018-07-09) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API -* `service/ce`: Updates service API and documentation -* `service/dms`: Updates service API and documentation - * Added support for DmsTransfer endpoint type and support for re-validate option in table reload API. -* `service/lambda`: Updates service API - * Add support for .NET Core 2.1 to Lambda. -* `service/transcribe`: Updates service API and documentation - -Release v1.14.21 (2018-07-06) -=== - -### Service Client Updates -* `service/mediaconvert`: Updates service API and documentation - * This release adds support for the following 1) users can specify tags to be attached to queues, presets, and templates during creation of those resources on MediaConvert. 2) users can now view the count of jobs in submitted state and in progressing state on a per queue basis. -* `service/serverlessrepo`: Updates service API and documentation - -Release v1.14.20 (2018-07-05) -=== - -### Service Client Updates -* `service/pinpoint`: Updates service API and documentation - * This release of the Amazon Pinpoint SDK adds the ability to create complex segments and validate phone numbers for SMS messages. It also adds the ability to get or delete endpoints based on user IDs, remove attributes from endpoints, and list the defined channels for an app. -* `service/sagemaker`: Updates service API and documentation - * Amazon SageMaker NotebookInstances supports 'Updating' as a NotebookInstanceStatus. In addition, DescribeEndpointOutput now includes Docker repository digest of deployed Model images. - -Release v1.14.19 (2018-07-03) -=== - -### Service Client Updates -* `service/acm`: Updates service waiters - * Adds a "CertificateValidated" waiter to AWS Certificate Manager clients, which polls on a new certificate's validation state. -* `service/ec2`: Updates service API, documentation, and examples - * Added support for customers to tag EC2 Dedicated Hosts -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/redshift`: Updates service API and documentation - * Feature 1 - On-demand cluster release version - When Amazon Redshift releases a new cluster version, you can choose to upgrade to that version immediately instead of waiting until your next maintenance window. You can also choose to roll back to a previous version. The two new APIs added for managing cluster release version are - ModifyClusterDbRevision, DescribeClusterDbRevisions. Feature 2 - Upgradeable reserved instance - You can now exchange one Reserved Instance for a new Reserved Instance with no changes to the terms of your existing Reserved Instance (term, payment type, or number of nodes). The two new APIs added for managing these upgrades are - AcceptReservedNodeExchange, GetReservedNodeExchangeOfferings. - -### SDK Enhancements -* `private/model/api`: Add EventStream support over RPC protocl ([#1998](https://github.com/aws/aws-sdk-go/pull/1998)) - * Adds support for EventStream over JSON PRC protocol. This adds support for the EventStream's initial-response event, EventStream headers, and EventStream modeled exceptions. Also replaces the hand written tests with generated tests for EventStream usage. - -Release v1.14.18 (2018-07-02) -=== - -### Service Client Updates -* `service/ssm`: Updates service API, documentation, and examples - * Execution History and StartAssociationOnce release for State Manager. Users now have the ability to view association execution history with DescribeAssociationExecutions and DescribeAssociationExecutionTargets. Users can also execute an association by calling StartAssociationOnce. - -Release v1.14.17 (2018-06-29) -=== - -### Service Client Updates -* `service/secretsmanager`: Updates service examples - * New SDK code snippet examples for the new APIs released for the Resource-based Policy support in Secrets Manager - -Release v1.14.16 (2018-06-28) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API, documentation, and examples - * Elastic Beanstalk adds "Suspended" health status to the EnvironmentHealthStatus enum type and updates document. -* `service/lambda`: Updates service API and documentation - * Support for SQS as an event source. -* `service/storagegateway`: Updates service API, documentation, and examples - * AWS Storage Gateway now enables you to use Server Message Block (SMB) protocol to store and access objects in Amazon Simple Storage Service (S3). - -Release v1.14.15 (2018-06-27) -=== - -### Service Client Updates -* `service/cloudfront`: Updates service API and documentation - * Unpublish delete-service-linked-role API. -* `service/codepipeline`: Updates service API - * UpdatePipeline may now throw a LimitExceededException when adding or updating Source Actions that use periodic checks for change detection -* `service/comprehend`: Updates service API, documentation, and paginators -* `service/secretsmanager`: Updates service documentation, paginators, and examples - * Documentation updates for secretsmanager - -### SDK Bugs -* `aws/csm`: Final API Call Attempt events were not being called [#2008](https://github.com/aws/aws-sdk-go/pull/2008) -Release v1.14.14 (2018-06-26) -=== - -### Service Client Updates -* `service/inspector`: Updates service API, documentation, and paginators - * Introduce four new APIs to view and preview Exclusions. Exclusions show which intended security checks are excluded from an assessment, along with reasons and recommendations to fix. The APIs are CreateExclusionsPreview, GetExclusionsPreview, ListExclusions, and DescribeExclusions. -* `service/s3`: Updates service API and documentation - * Add AllowQuotedRecordDelimiter to Amazon S3 Select API. Please refer to https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectSELECTContent.html for usage details. -* `service/secretsmanager`: Updates service API, documentation, paginators, and examples - * This release adds support for resource-based policies that attach directly to your secrets. These policies provide an additional way to control who can access your secrets and what they can do with them. For more information, see https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_resource-based-policies.html in the Secrets Manager User Guide. - -Release v1.14.13 (2018-06-22) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API and documentation -* `service/appstream`: Updates service API, documentation, paginators, and examples - * This API update enables customers to find their VPC private IP address and ENI ID associated with AppStream streaming sessions. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.14.12 (2018-06-21) -=== - -### Service Client Updates -* `service/clouddirectory`: Adds new service - * SDK release to support Flexible Schema initiative being carried out by Amazon Cloud Directory. This feature lets customers using new capabilities like: variant typed attributes, dynamic facets and AWS managed Cloud Directory schemas. - -Release v1.14.11 (2018-06-21) -=== - -### Service Client Updates -* `service/macie`: Adds new service - * Amazon Macie is a security service that uses machine learning to automatically discover, classify, and protect sensitive data in AWS. With this release, we are launching the following Macie HTTPS API operations: AssociateMemberAccount, AssociateS3Resources, DisassociateMemberAccount, DisassociateS3Resources, ListMemberAccounts, ListS3Resources, and UpdateS3Resources. With these API operations you can issue HTTPS requests directly to the service. -* `service/neptune`: Updates service API, documentation, and examples - * Deprecates the PubliclyAccessible parameter that is not supported by Amazon Neptune. -* `service/ssm`: Updates service API, documentation, and examples - * Adds Amazon Linux 2 support to Patch Manager - -Release v1.14.10 (2018-06-20) -=== - -### Service Client Updates -* `service/acm-pca`: Updates service API, documentation, paginators, and examples -* `service/medialive`: Updates service API, documentation, and paginators - * AWS Elemental MediaLive now makes Reserved Outputs and Inputs available through the AWS Management Console and API. You can reserve outputs and inputs with a 12 month commitment in exchange for discounted hourly rates. Pricing is available at https://aws.amazon.com/medialive/pricing/ -* `service/rds`: Updates service API, documentation, and examples - * This release adds a new parameter to specify the retention period for Performance Insights data for RDS instances. You can either choose 7 days (default) or 731 days. For more information, see Amazon RDS Documentation. - -### SDK Enhancements -* `service/s3`: Update SelectObjectContent doc example to be on the API not nested type. ([#1991](https://github.com/aws/aws-sdk-go/pull/1991)) - -### SDK Bugs -* `aws/client`: Fix HTTP debug log EventStream payloads ([#2000](https://github.com/aws/aws-sdk-go/pull/2000)) - * Fixes the SDK's HTTP client debug logging to not log the HTTP response body for EventStreams. This prevents the SDK from buffering a very large amount of data to be logged at once. The aws.LogDebugWithEventStreamBody should be used to log the event stream events. - * Fixes a bug in the SDK's response logger which will buffer the response body's content if LogDebug is enabled but LogDebugWithHTTPBody is not. -Release v1.14.9 (2018-06-19) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rekognition`: Updates service documentation and examples - * Documentation updates for rekognition - -### SDK Bugs -* `private/model/api`: Update client ServiceName to be based on name of service for new services. ([#1997](https://github.com/aws/aws-sdk-go/pull/1997)) - * Fixes the SDK's `ServiceName` AWS service client package value to be unique based on the service name for new AWS services. Does not change exiting client packages. -Release v1.14.8 (2018-06-15) -=== - -### Service Client Updates -* `service/mediaconvert`: Updates service API and documentation - * This release adds language code support according to the ISO-639-3 standard. Custom 3-character language codes are now supported on input and output for both audio and captions. - -Release v1.14.7 (2018-06-14) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Support for PRIVATE endpoint configuration type -* `service/dynamodb`: Updates service API and documentation - * Added two new fields SSEType and KMSMasterKeyArn to SSEDescription block in describe-table output. -* `service/iotanalytics`: Updates service API and documentation - -Release v1.14.6 (2018-06-13) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API - * Introduced new length limitations for few of the product fields. -* `service/ssm`: Updates service API and documentation - * Added support for new parameter, CloudWatchOutputConfig, for SendCommand API. Users can now have RunCommand output sent to CloudWatchLogs. - -Release v1.14.5 (2018-06-12) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Adding VPCEndpoint support for Remote access. Allows customers to be able to access their private endpoints/services running in their VPC during remote access. -* `service/ecs`: Updates service API and documentation - * Introduces daemon scheduling capability to deploy one task per instance on selected instances in a cluster. Adds a "force" flag to the DeleteService API to delete a service without requiring to scale down the number of tasks to zero. - -### SDK Enhancements -* `service/rds/rdsutils`: Clean up the rdsutils package and adds a new builder to construct connection strings ([#1985](https://github.com/aws/aws-sdk-go/pull/1985)) - * Rewords documentation to be more useful and provides links to prior setup needed to support authentication tokens. Introduces a builder that allows for building connection strings - -### SDK Bugs -* `aws/signer/v4`: Fix X-Amz-Content-Sha256 being in to query for presign ([#1976](https://github.com/aws/aws-sdk-go/pull/1976)) - * Fixes the bug which would allow the X-Amz-Content-Sha256 header to be promoted to the query string when presigning a S3 request. This bug also was preventing users from setting their own sha256 value for a presigned URL. Presigned requests generated with the custom sha256 would of always failed with invalid signature. - * Fixes [#1974](https://github.com/aws/aws-sdk-go/pull/1974) -Release v1.14.4 (2018-06-11) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Amazon Cloud Directory now supports optional attributes on Typed Links, giving users the ability to associate and manage data on Typed Links. -* `service/rds`: Updates service documentation - * Changed lists of valid EngineVersion values to links to the RDS User Guide. -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway now enables you to create cached volumes and tapes with AWS KMS support. - -Release v1.14.3 (2018-06-08) -=== - -### Service Client Updates -* `service/mediatailor`: Updates service API - -Release v1.14.2 (2018-06-07) -=== - -### Service Client Updates -* `service/medialive`: Updates service API, documentation, and paginators - * AWS Elemental MediaLive now makes channel log information available through Amazon CloudWatch Logs. You can set up each MediaLive channel with a logging level; when the channel is run, logs will automatically be published to your account on Amazon CloudWatch Logs - -Release v1.14.1 (2018-06-05) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/polly`: Updates service API and documentation - * Amazon Polly adds new French voice - "Lea" -* `service/rds`: Updates service API and documentation - * This release adds customizable processor features for RDS instances. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager -* `service/shield`: Updates service API and documentation - * DDoS Response Team access management for AWS Shield - -Release v1.14.0 (2018-06-04) -=== - -### Service Client Updates -* `service/AWSMigrationHub`: Updates service documentation -* `service/appstream`: Updates service API and documentation - * Amazon AppStream 2.0 adds support for Google Drive for G Suite. With this feature, customers will be able to connect their G Suite accounts with AppStream 2.0 and enable Google Drive access for an AppStream 2.0 stack. Users of the stack can then link their Google Drive using their G Suite login credentials and use their existing files stored in Drive with their AppStream 2.0 applications. File changes will be synced automatically to Google cloud. -* `service/ec2`: Updates service API and documentation - * You are now able to use instance storage (up to 3600 GB of NVMe based SSD) on M5 instances, the next generation of EC2's General Purpose instances in us-east-1, us-west-2, us-east-2, eu-west-1 and ca-central-1. M5 instances offer up to 96 vCPUs, 384 GiB of DDR4 instance memory, 25 Gbps in Network bandwidth and improved EBS and Networking bandwidth on smaller instance sizes and provide a balance of compute, memory and network resources for many applications. -* `service/eks`: Adds new service -* `service/mediaconvert`: Updates service API and documentation - * This release adds the support for Common Media Application Format (CMAF) fragmented outputs, RF64 WAV audio output format, and HEV1 or HEVC1 MP4 packaging types when using HEVC in DASH or CMAF outputs. -* `service/sagemaker`: Updates service API, documentation, and paginators - * Amazon SageMaker has added the ability to run hyperparameter tuning jobs. A hyperparameter tuning job will create and evaluate multiple training jobs while tuning algorithm hyperparameters, to optimize a customer specified objective metric. - -### SDK Features -* Add support for EventStream based APIs (S3 SelectObjectContent) ([#1941](https://github.com/aws/aws-sdk-go/pull/1941)) - * Adds support for EventStream asynchronous APIs such as S3 SelectObjectContents API. This API allows your application to receiving multiple events asynchronously from the API response. Your application recieves these events from a channel on the API response. - * See PR [#1941](https://github.com/aws/aws-sdk-go/pull/1941) for example. - * Fixes [#1895](https://github.com/aws/aws-sdk-go/issues/1895) - -Release v1.13.60 (2018-06-01) -=== - -### Service Client Updates -* `service/ds`: Updates service API and documentation - * Added ResetUserPassword API. Customers can now reset their users' passwords without providing the old passwords in Simple AD and Microsoft AD. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API and documentation - * We are releasing force CancelJob and CancelJobExecution functionalities to customers. -* `service/mediatailor`: Adds new service -* `service/redshift`: Updates service documentation - * Documentation updates for redshift -* `service/sns`: Updates service API, documentation, and paginators - * The SNS Subscribe API has been updated with two new optional parameters: Attributes and ReturnSubscriptionArn. Attributes is a map of subscription attributes which can be one or more of: FilterPolicy, DeliveryPolicy, and RawMessageDelivery. ReturnSubscriptionArn is a boolean parameter that overrides the default behavior of returning "pending confirmation" for subscriptions that require confirmation instead of returning the subscription ARN. - -### SDK Bugs -* `private/mode/api`: Fix error code constants being generated incorrectly.([#1958](https://github.com/aws/aws-sdk-go/issues/1958)) - * Fixes the SDK's code generation to not modify the error code text value when generating error code constants. This prevents generating error code values which are invalid and will never be sent by the service. This change does not change the error code constant variable name generated by the SDK, only the value of the error code. - * Fixes [#1856](https://github.com/aws/aws-sdk-go/issues/1856) -Release v1.13.59 (2018-05-31) -=== - -* `aws/endpoints`: Updated Regions and Endpoints metadata. -Release v1.13.58 (2018-05-30) -=== - -### Service Client Updates -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/neptune`: Adds new service - * Amazon Neptune is a fast, reliable graph database service that makes it easy to build and run applications that work with highly connected datasets. Neptune supports popular graph models Property Graph and W3C's Resource Description Frame (RDF), and their respective query languages Apache TinkerPop Gremlin 3.3.2 and SPARQL 1.1. - -Release v1.13.57 (2018-05-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/pi`: Adds new service - -Release v1.13.56 (2018-05-25) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update enables customers to control whether users can transfer data between their local devices and their streaming applications through file uploads and downloads, clipboard operations, or printing to local devices -* `service/config`: Updates service API and documentation -* `service/glue`: Updates service API and documentation - * AWS Glue now sends a delay notification to Amazon CloudWatch Events when an ETL job runs longer than the specified delay notification threshold. -* `service/iot`: Updates service API - * We are exposing DELETION_IN_PROGRESS as a new job status in regards to the release of DeleteJob API. - -Release v1.13.55 (2018-05-24) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API - * AWS CodeBuild Adds Support for Windows Builds. -* `service/elasticloadbalancingv2`: Updates service documentation -* `service/rds`: Updates service API and documentation - * This release adds CloudWatch Logs integration capabilities to RDS Aurora MySQL clusters -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -### SDK Bugs -* `service/cloudwatchlogs`: Fix pagination with cloudwatchlogs ([#1945](https://github.com/aws/aws-sdk-go/pull/1945)) - * Fixes the SDK's behavior with CloudWatchLogs APIs which return duplicate `NextToken` values to signal end of pagination. - * Fixes [#1908](https://github.com/aws/aws-sdk-go/pull/1908) - -Release v1.13.54 (2018-05-22) -=== - -### Service Client Updates -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (ECS) adds service discovery for services that use host or bridged network mode. ECS can now also register instance IPs for active tasks using bridged and host networking with Route 53, making them available via DNS. -* `service/inspector`: Updates service API - * We are launching the ability to target all EC2 instances. With this launch, resourceGroupArn is now optional for CreateAssessmentTarget and UpdateAssessmentTarget. If resourceGroupArn is not specified, all EC2 instances in the account in the AWS region are included in the assessment target. - -Release v1.13.53 (2018-05-21) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * 1) Filtered Update for StackSet based on Accounts and Regions: This feature will allow flexibility for the customers to roll out updates on a StackSet based on specific Accounts and Regions. 2) Support for customized ExecutionRoleName: This feature will allow customers to attach ExecutionRoleName to the StackSet thus ensuring more security and controlling the behavior of any AWS resources in the target accounts. - -Release v1.13.52 (2018-05-18) -=== - -### Service Client Updates -* `service/email`: Updates service documentation - * Fixed a broken link in the documentation for S3Action. -* `service/iot`: Updates service API and documentation - * We are releasing DeleteJob and DeleteJobExecution APIs to allow customer to delete resources created using AWS IoT Jobs. - -Release v1.13.51 (2018-05-17) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service documentation - * Documentation updates for codedeploy -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * You are now able to use instance storage (up to 1800 GB of NVMe based SSD) on C5 instances, the next generation of EC2's compute optimized instances in us-east-1, us-west-2, us-east-2, eu-west-1 and ca-central-1. C5 instances offer up to 72 vCPUs, 144 GiB of DDR4 instance memory, 25 Gbps in Network bandwidth and improved EBS and Networking bandwidth on smaller instance sizes to deliver improved performance for compute-intensive workloads.You can now run bare metal workloads on EC2 with i3.metal instances. As a new instance size belonging to the I3 instance family, i3.metal instances have the same characteristics as other instances in the family, including NVMe SSD-backed instance storage optimized for low latency, very high random I/O performance, and high sequential read throughput. I3.metal instances are powered by 2.3 GHz Intel Xeon processors, offering 36 hyper-threaded cores (72 logical processors), 512 GiB of memory, and 15.2 TB of NVMe SSD-backed instance storage. These instances deliver high networking throughput and lower latency with up to 25 Gbps of aggregate network bandwidth using Elastic Network Adapter (ENA)-based Enhanced Networking. - -Release v1.13.50 (2018-05-16) -=== - -### Service Client Updates -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager -* `service/servicecatalog`: Updates service API and documentation - * Users can now pass a new option to ListAcceptedPortfolioShares called portfolio-share-type with a value of AWS_SERVICECATALOG in order to access Getting Started Portfolios that contain selected products representing common customer use cases. - -Release v1.13.49 (2018-05-15) -=== - -### Service Client Updates -* `service/config`: Updates service API - -Release v1.13.48 (2018-05-14) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Adding support for more override fields for StartBuild API, add support for idempotency token field for StartBuild API in AWS CodeBuild. -* `service/iot1click-devices`: Adds new service -* `service/iot1click-projects`: Adds new service -* `service/organizations`: Updates service documentation - * Documentation updates for organizations - -Release v1.13.47 (2018-05-10) -=== - -### Service Client Updates -* `service/firehose`: Updates service API and documentation - * With this release, Amazon Kinesis Data Firehose can convert the format of your input data from JSON to Apache Parquet or Apache ORC before storing the data in Amazon S3. Parquet and ORC are columnar data formats that save space and enable faster queries compared to row-oriented formats like JSON. - -Release v1.13.46 (2018-05-10) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/gamelift`: Updates service API and documentation - * AutoScaling Target Tracking scaling simplification along with StartFleetActions and StopFleetActions APIs to suspend and resume automatic scaling at will. - -Release v1.13.45 (2018-05-10) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Updating the regex for the NumericValue fields. -* `service/ec2`: Updates service API and documentation - * Enable support for latest flag with Get Console Output -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Changes to support the Aurora MySQL Backtrack feature. - -Release v1.13.44 (2018-05-08) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Enable support for specifying CPU options during instance launch. -* `service/rds`: Updates service documentation - * Correction to the documentation about copying unencrypted snapshots. - -Release v1.13.43 (2018-05-07) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API -* `service/budgets`: Updates service API and documentation - * "With this release, customers can use AWS Budgets to monitor how much of their Amazon EC2, Amazon RDS, Amazon Redshift, and Amazon ElastiCache instance usage is covered by reservations, and receive alerts when their coverage falls below the threshold they define." -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/es`: Updates service API, documentation, and paginators - * This change brings support for Reserved Instances to AWS Elasticsearch. -* `service/s3`: Updates service API and documentation - * Added BytesReturned details for Progress and Stats Events for Amazon S3 Select . - -Release v1.13.42 (2018-05-04) -=== - -### Service Client Updates -* `service/guardduty`: Updates service API, documentation, and paginators - * Amazon GuardDuty is adding five new API operations for creating and managing filters. For each filter, you can specify a criteria and an action. The action you specify is applied to findings that match the specified criteria. - -Release v1.13.41 (2018-05-03) -=== - -### Service Client Updates -* `service/appsync`: Updates service API and documentation -* `service/config`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.40 (2018-05-02) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation updates for acm -* `service/codepipeline`: Updates service API and documentation - * Added support for webhooks with accompanying definitions as needed in the AWS CodePipeline API Guide. -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Fleet is a new feature that simplifies the provisioning of Amazon EC2 capacity across different EC2 instance types, Availability Zones, and the On-Demand, Reserved Instance, and Spot Instance purchase models. With a single API call, you can now provision capacity to achieve desired scale, performance, and cost. -* `service/ssm`: Updates service API and documentation - * Added support for new parameter, DocumentVersion, for SendCommand API. Users can now specify version of SSM document to be executed on the target(s). - -Release v1.13.39 (2018-04-30) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API, documentation, and paginators -* `service/dynamodb`: Updates service API and documentation - * Adds two new APIs UpdateGlobalTableSettings and DescribeGlobalTableSettings. This update introduces new constraints in the CreateGlobalTable and UpdateGlobalTable APIs . Tables must have the same write capacity units. If Global Secondary Indexes exist then they must have the same write capacity units and key schema. -* `service/guardduty`: Updates service API and documentation - * You can disable the email notification when inviting GuardDuty members using the disableEmailNotification parameter in the InviteMembers operation. -* `service/route53domains`: Updates service API and documentation - * This release adds a SubmittedSince attribute to the ListOperations API, so you can list operations that were submitted after a specified date and time. -* `service/sagemaker`: Updates service API and documentation - * SageMaker has added support for VPC configuration for both Endpoints and Training Jobs. This allows you to connect from the instances running the Endpoint or Training Job to your VPC and any resources reachable in the VPC rather than being restricted to resources that were internet accessible. -* `service/workspaces`: Updates service API and documentation - * Added new IP Access Control APIs, an API to change the state of a Workspace, and the ADMIN_MAINTENANCE WorkSpace state. With the new IP Access Control APIs, you can now create/delete IP Access Control Groups, add/delete/update rules for IP Access Control Groups, Associate/Disassociate IP Access Control Groups to/from a WorkSpaces Directory, and Describe IP Based Access Control Groups. - -Release v1.13.38 (2018-04-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service documentation - * Documentation updates for Glacier to fix a broken link -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.37 (2018-04-25) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy has a new exception that indicates when a GitHub token is not valid. -* `service/rekognition`: Updates service documentation - * Documentation updates for Amazon Rekognition. -* `service/xray`: Updates service API and documentation - * Added PutEncryptionConfig and GetEncryptionConfig APIs for managing data encryption settings. Use PutEncryptionConfig to configure X-Ray to use an AWS Key Management Service customer master key to encrypt trace data at rest. - -Release v1.13.36 (2018-04-24) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * Support tracking Elastic Beanstalk resources in AWS Config. -* `service/secretsmanager`: Updates service documentation - * Documentation updates for secretsmanager - -Release v1.13.35 (2018-04-23) -=== - -### Service Client Updates -* `service/autoscaling-plans`: Updates service API and documentation -* `service/iot`: Updates service API and documentation - * Add IotAnalyticsAction which sends message data to an AWS IoT Analytics channel -* `service/iotanalytics`: Adds new service - -### SDK Enhancements -* `aws/endpoints`: Add Get Region description to endpoints package ([#1909](https://github.com/aws/aws-sdk-go/pull/1909)) - * Adds exposing the description field of the endpoints Region struct. - * Fixes [#1194](https://github.com/aws/aws-sdk-go/issues/1194) - -### SDK Bugs -* Fix XML unmarshaler not correctly unmarshaling list of timestamp values ([#1894](https://github.com/aws/aws-sdk-go/pull/1894)) - * Fixes a bug in the XML unmarshaler that would incorrectly try to unmarshal "time.Time" parameters that did not have the struct tag type on them. This would occur for nested lists like CloudWatch's GetMetricDataResponse MetricDataResults timestamp parameters. - * Fixes [#1892](https://github.com/aws/aws-sdk-go/issues/1892) -Release v1.13.34 (2018-04-20) -=== - -### Service Client Updates -* `service/firehose`: Updates service API and documentation - * With this release, Amazon Kinesis Data Firehose allows you to tag your delivery streams. Tags are metadata that you can create and use to manage your delivery streams. For more information about tagging, see AWS Tagging Strategies. For technical documentation, look for the tagging operations in the Amazon Kinesis Firehose API reference. -* `service/medialive`: Updates service API and documentation - * With AWS Elemental MediaLive you can now output live channels as RTMP (Real-Time Messaging Protocol) and RTMPS as the encrypted version of the protocol (Secure, over SSL/TLS). RTMP is the preferred protocol for sending live streams to popular social platforms which means you can send live channel content to social and sharing platforms in a secure and reliable way while continuing to stream to your own website, app or network. - -Release v1.13.33 (2018-04-19) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/codepipeline`: Updates service API and documentation - * Added new SourceRevision structure to Execution Summary with accompanying definitions as needed in the AWS CodePipeline API Guide. -* `service/devicefarm`: Updates service API and documentation - * Adding support for VPCEndpoint feature. Allows customers to be able to access their private endpoints/services running in their VPC during test automation. -* `service/ec2`: Updates service API and documentation - * Added support for customers to see the time at which a Dedicated Host was allocated or released. -* `service/rds`: Updates service API and documentation - * The ModifyDBCluster operation now includes an EngineVersion parameter. You can use this to upgrade the engine for a clustered database. -* `service/secretsmanager`: Updates service documentation and examples - * Documentation updates -* `service/ssm`: Updates service API and documentation - * Added new APIs DeleteInventory and DescribeInventoryDeletions, for customers to delete their custom inventory data. - -Release v1.13.32 (2018-04-10) -=== - -### Service Client Updates -* `service/dms`: Updates service API and documentation - * Native Change Data Capture start point and task recovery support in Database Migration Service. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * "AWS Glue now supports timeout values for ETL jobs. With this release, all new ETL jobs have a default timeout value of 48 hours. AWS Glue also now supports the ability to start a schedule or job events trigger when it is created." -* `service/mediapackage`: Updates service API and documentation - * Adds a new OriginEndpoint package type CmafPackage in MediaPackage. Origin endpoints can now be configured to use the Common Media Application Format (CMAF) media streaming format. This version of CmafPackage only supports HTTP Live Streaming (HLS) manifests with fragmented MP4. -* `service/ssm`: Updates service API and documentation - * Added TooManyUpdates exception for AddTagsToResource and RemoveTagsFromResource API -* `service/workmail`: Updates service API, documentation, and paginators - * Amazon WorkMail adds the ability to grant users and groups with "Full Access", "Send As" and "Send on Behalf" permissions on a given mailbox. - -Release v1.13.31 (2018-04-09) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Cloud Directory customers can fetch attributes within a facet on an object with the new GetObjectAttributes API and can fetch attributes from multiple facets or objects with the BatchGetObjectAttributes operation. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.30 (2018-04-06) -=== - -### Service Client Updates -* `service/batch`: Updates service API and documentation - * Support for Timeout in SubmitJob and RegisterJobDefinition - -Release v1.13.29 (2018-04-05) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/ssm`: Updates service documentation - -Release v1.13.28 (2018-04-04) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * AWS Certificate Manager has added support for AWS Certificate Manager Private Certificate Authority (CA). Customers can now request private certificates with the RequestCertificate API, and also export private certificates with the ExportCertificate API. -* `service/acm-pca`: Adds new service -* `service/config`: Updates service API and documentation -* `service/fms`: Adds new service -* `service/monitoring`: Updates service API and documentation - * The new GetMetricData API enables you to collect batch amounts of metric data and optionally perform math expressions on the data. With one GetMetricData call you can retrieve as many as 100 different metrics and a total of 100,800 data points. -* `service/s3`: Updates service API and documentation - * ONEZONE_IA storage class stores object data in only one Availability Zone at a lower price than STANDARD_IA. This SDK release provides API support for this new storage class. -* `service/sagemaker`: Updates service API and documentation - * SageMaker is now supporting many additional instance types in previously supported families for Notebooks, Training Jobs, and Endpoints. Training Jobs and Endpoints now support instances in the m5 family in addition to the previously supported instance families. For specific instance types supported please see the documentation for the SageMaker API. -* `service/secretsmanager`: Adds new service - * AWS Secrets Manager enables you to easily create and manage the secrets that you use in your customer-facing apps. Instead of embedding credentials into your source code, you can dynamically query Secrets Manager from your app whenever you need credentials. You can automatically and frequently rotate your secrets without having to deploy updates to your apps. All secret values are encrypted when they're at rest with AWS KMS, and while they're in transit with HTTPS and TLS. -* `service/transcribe`: Updates service API, documentation, and paginators - -Release v1.13.27 (2018-04-03) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Added Private Device Management feature. Customers can now manage their private devices efficiently - view their status, set labels and apply profiles on them. Customers can also schedule automated tests and remote access sessions on individual instances in their private device fleet. -* `service/lambda`: Updates service API and documentation - * added nodejs8.10 as a valid runtime -* `service/translate`: Updates service API and documentation - -Release v1.13.26 (2018-04-02) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Amazon API Gateway now supports resource policies for APIs making it easier to set access controls for invoking APIs. -* `service/cloudfront`: Adds new service - * You can now use a new Amazon CloudFront capability called Field-Level Encryption to further enhance the security of sensitive data, such as credit card numbers or personally identifiable information (PII) like social security numbers. CloudFront's field-level encryption further encrypts sensitive data in an HTTPS form using field-specific encryption keys (which you supply) before a POST request is forwarded to your origin. This ensures that sensitive data can only be decrypted and viewed by certain components or services in your application stack. Field-level encryption is easy to setup. Simply configure the fields that have to be further encrypted by CloudFront using the public keys you specify and you can reduce attack surface for your sensitive data. -* `service/es`: Updates service API and documentation - * This adds Amazon Cognito authentication support to Kibana. - -Release v1.13.25 (2018-03-30) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * Documentation updates for acm -* `service/connect`: Adds new service -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.24 (2018-03-29) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API, documentation, and paginators -* `service/cloudformation`: Updates service API and documentation - * Enabling resource level permission control for StackSets APIs. Adding support for customers to use customized AdministrationRole to create security boundaries between different users. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/greengrass`: Updates service API and documentation - * Greengrass APIs now support creating Machine Learning resource types and configuring binary data as the input payload for Greengrass Lambda functions. -* `service/ssm`: Updates service API - * This Patch Manager release supports creating patch baselines for CentOS. - -Release v1.13.23 (2018-03-28) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iam`: Updates service API and documentation - * Add support for Longer Role Sessions. Four APIs manage max session duration: GetRole, ListRoles, CreateRole, and the new API UpdateRole. The max session duration integer attribute is measured in seconds. -* `service/mturk-requester`: Updates service API and documentation -* `service/sts`: Updates service API and documentation - * Change utilizes the Max Session Duration attribute introduced for IAM Roles and allows STS customers to request session duration up to the Max Session Duration of 12 hours from AssumeRole based APIs. - -Release v1.13.22 (2018-03-27) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * AWS Certificate Manager has added support for customers to disable Certificate Transparency logging on a per-certificate basis. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.21 (2018-03-26) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service API and documentation - * Point-in-time recovery (PITR) provides continuous backups of your DynamoDB table data. With PITR, you do not have to worry about creating, maintaining, or scheduling backups. You enable PITR on your table and your backup is available for restore at any point in time from the moment you enable it, up to a maximum of the 35 preceding days. PITR provides continuous backups until you explicitly disable it. For more information, see the Amazon DynamoDB Developer Guide. - -Release v1.13.20 (2018-03-23) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for RDS - -Release v1.13.19 (2018-03-22) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Feedback URL allows admins to provide a feedback link or a survey link for collecting user feedback while streaming sessions. When a feedback link is provided, streaming users will see a "Send Feedback" choice in their streaming session toolbar. On selecting this choice, user will be redirected to the link provided in a new browser tab. If a feedback link is not provided, users will not see the "Send Feedback" option. -* `service/codebuild`: Updates service API and documentation - * Adding support for branch filtering when using webhooks with AWS CodeBuild. -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (ECS) now includes integrated Service Discovery using Route 53 Auto Naming. Customers can now specify a Route 53 Auto Naming service as part of an ECS service. ECS will register task IPs with Route 53, making them available via DNS in your VPC. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -### SDK Bugs -* `aws/endpoints`: Use service metadata for fallback signing name ([#1854](https://github.com/aws/aws-sdk-go/pull/1854)) - * Updates the SDK's endpoint resolution to fallback deriving the service's signing name from the service's modeled metadata in addition the endpoints modeled data. - * Fixes [#1850](https://github.com/aws/aws-sdk-go/issues/1850) -Release v1.13.18 (2018-03-21) -=== - -### Service Client Updates -* `service/serverlessrepo`: Updates service documentation - -Release v1.13.17 (2018-03-20) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/config`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now mount a temporary volume in memory in containers and specify the shared memory that a container can use through the use of docker's 'tmpfs' and 'shm-size' features respectively. These fields can be specified under linuxParameters in ContainerDefinition in the Task Definition Template. -* `service/elasticbeanstalk`: Updates service documentation - * Documentation updates for the new Elastic Beanstalk API DescribeAccountAttributes. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service API and documentation - * Added SQS FIFO queue target support -* `service/glue`: Updates service API and documentation - * API Updates for DevEndpoint: PublicKey is now optional for CreateDevEndpoint. The new DevEndpoint field PrivateAddress will be populated for DevEndpoints associated with a VPC. -* `service/medialive`: Updates service API and documentation - * AWS Elemental MediaLive has added support for updating Inputs and Input Security Groups. You can update Input Security Groups at any time and it will update all channels using that Input Security Group. Inputs can be updated as long as they are not attached to a currently running channel. - -Release v1.13.16 (2018-03-16) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * AWS Elastic Beanstalk is launching a new public API named DescribeAccountAttributes which allows customers to access account level attributes. In this release, the API will support quotas for resources such as applications, application versions, and environments. - -Release v1.13.15 (2018-03-15) -=== - -### Service Client Updates -* `service/organizations`: Updates service API and documentation - * This release adds additional reason codes to improve clarity to exceptions that can occur. -* `service/pinpoint`: Updates service API and documentation - * With this release, you can delete endpoints from your Amazon Pinpoint projects. Customers can now specify one of their leased dedicated long or short codes to send text messages. -* `service/sagemaker`: Updates service API, documentation, and paginators - * This release provides support for ml.p3.xlarge instance types for notebook instances. Lifecycle configuration is now available to customize your notebook instances on start; the configuration can be reused between multiple notebooks. If a notebook instance is attached to a VPC you can now opt out of internet access that by default is provided by SageMaker. - -Release v1.13.14 (2018-03-14) -=== - -### Service Client Updates -* `service/lightsail`: Updates service API and documentation - * Updates to existing Lightsail documentation - -Release v1.13.13 (2018-03-13) -=== - -### Service Client Updates -* `service/servicediscovery`: Updates service API and documentation - * This release adds support for custom health checks, which let you check the health of resources that aren't accessible over the internet. For example, you can use a custom health check when the instance is in an Amazon VPC. - -Release v1.13.12 (2018-03-12) -=== - -### Service Client Updates -* `service/cloudhsmv2`: Updates service API - * CreateCluster can now take both 8 and 17 character Subnet IDs. DeleteHsm can now take both 8 and 17 character ENI IDs. -* `service/discovery`: Updates service API and documentation - * Documentation updates for discovery -* `service/iot`: Updates service API and documentation - * We added new fields to the response of the following APIs. (1) describe-certificate: added new generationId, customerVersion fields (2) describe-ca-certificate: added new generationId, customerVersion and lastModifiedDate fields (3) get-policy: added generationId, creationDate and lastModifiedDate fields -* `service/redshift`: Updates service API and documentation - * DescribeClusterSnapshotsMessage with ClusterExists flag returns snapshots of existing clusters. Else both existing and deleted cluster snapshots are returned - -Release v1.13.11 (2018-03-08) -=== - -### Service Client Updates -* `service/AWSMigrationHub`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (ECS) now supports container health checks. Customers can now specify a docker container health check command and parameters in their task definition. ECS will monitor, report and take scheduling action based on the health status. -* `service/pinpoint`: Updates service API and documentation - * With this release, you can export endpoints from your Amazon Pinpoint projects. You can export a) all of the endpoints assigned to a project or b) the subset of endpoints assigned to a segment. -* `service/rds`: Updates service documentation - * Documentation updates for RDS - -Release v1.13.10 (2018-03-07) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/medialive`: Updates service API and documentation - * Updates API to model required traits and minimum/maximum constraints. - -Release v1.13.9 (2018-03-06) -=== - -### Service Client Updates -* `service/ecs`: Updates service documentation - * Documentation updates for Amazon ECS -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.8 (2018-03-01) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Added support for modifying Placement Group association of instances via ModifyInstancePlacement API. -* `service/events`: Updates service API and documentation - * Added BatchParameters to the PutTargets API -* `service/servicecatalog`: Updates service API and documentation - * This release of ServiceCatalog adds the DeleteTagOption API. -* `service/ssm`: Updates service API and documentation - * This Inventory release supports the status message details reported by the last sync for the resource data sync API. -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway (File) support for two new file share attributes are added. 1. Users can specify the S3 Canned ACL to use for new objects created in the file share. 2. Users can create file shares for requester-pays buckets. - -Release v1.13.7 (2018-02-28) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.6 (2018-02-27) -=== - -### Service Client Updates -* `service/ecr`: Updates service documentation - * Documentation updates for Amazon ECR. - -Release v1.13.5 (2018-02-26) -=== - -### Service Client Updates -* `service/route53`: Updates service API - * Added support for creating LBR rules using ap-northeast-3 region. -* `service/sts`: Updates service API and documentation - * Increased SAMLAssertion parameter size from 50000 to 100000 for AWS Security Token Service AssumeRoleWithSAML API to allow customers to pass bigger SAML assertions - -Release v1.13.4 (2018-02-23) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update is to enable customers to copy their Amazon AppStream 2.0 images within and between AWS Regions -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.3 (2018-02-22) -=== - -### Service Client Updates -* `service/ce`: Updates service API and documentation -* `service/elasticloadbalancingv2`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.13.2 (2018-02-21) -=== - -### Service Client Updates -* `service/codecommit`: Updates service API and documentation - * This release adds an API for adding a file directly to an AWS CodeCommit repository without requiring a Git client. -* `service/ec2`: Updates service API and documentation - * Adds support for tagging an EBS snapshot as part of the API call that creates the EBS snapshot -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/serverlessrepo`: Updates service API, documentation, and paginators - -Release v1.13.1 (2018-02-20) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Amazon EC2 Auto Scaling support for service-linked roles -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/waf`: Updates service API and documentation - * The new PermissionPolicy APIs in AWS WAF Regional allow customers to attach resource-based policies to their entities. -* `service/waf-regional`: Updates service API and documentation - -Release v1.13.0 (2018-02-19) -=== - -### Service Client Updates -* `service/config`: Updates service API - * With this release, AWS Config updated the ConfigurationItemStatus enum values. The values prior to this update did not represent appropriate values returned by GetResourceConfigHistory. You must update your code to enumerate the new enum values so this is a breaking change. To map old properties to new properties, use the following descriptions: New discovered resource - Old property: Discovered, New property: ResourceDiscovered. Updated resource - Old property: Ok, New property: OK. Deleted resource - Old property: Deleted, New property: ResourceDeleted or ResourceDeletedNotRecorded. Not-recorded resource - Old property: N/A, New property: ResourceNotRecorded or ResourceDeletedNotRecorded. - -Release v1.12.79 (2018-02-16) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * Updates RDS API to indicate whether a DBEngine supports read replicas. - -Release v1.12.78 (2018-02-15) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/gamelift`: Updates service API and documentation - * Updates to allow Fleets to run on On-Demand or Spot instances. -* `service/mediaconvert`: Updates service API and documentation - * Nielsen ID3 tags can now be inserted into transport stream (TS) and HLS outputs. For more information on Nielsen configuration you can go to https://docs.aws.amazon.com/mediaconvert/latest/apireference/jobs.html#jobs-nielsenconfiguration - -Release v1.12.77 (2018-02-14) -=== - -### Service Client Updates -* `service/appsync`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation - -### Bug Fixes -* `aws/request`: Fix support for streamed payloads for unsigned body request ([#1778](https://github.com/aws/aws-sdk-go/pull/1778)) - * Fixes the SDK's handling of the SDK's `ReaderSeekerCloser` helper type to not allow erroneous request retries, and request signature generation. This Fix allows you to use the `aws.ReaderSeekerCloser` to wrap an arbitrary `io.Reader` for request `io.ReadSeeker` input parameters. APIs such as lex-runtime's PostContent can now make use of the -ReaderSeekerCloser type without causing unexpected failures. - * Fixes [#1776](https://github.com/aws/aws-sdk-go/issues/1776) - -Release v1.12.76 (2018-02-13) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service documentation - * Documentation updates for glacier -* `service/route53`: Updates service API - * Added support for creating Private Hosted Zones and metric-based healthchecks in the ap-northeast-3 region for whitelisted customers. - -Release v1.12.75 (2018-02-12) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Network interfaces now supply the following additional status of "associated" to better distinguish the current status. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/guardduty`: Updates service API and documentation - * Added PortProbeAction information to the Action section of the port probe-type finding. -* `service/kms`: Updates service API - * This release of AWS Key Management Service includes support for InvalidArnException in the RetireGrant API. -* `service/rds`: Updates service documentation - * Aurora MySQL now supports MySQL 5.7. - -Release v1.12.74 (2018-02-09) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Users can now better understand the longer ID opt-in status of their account using the two new APIs DescribeAggregateIdFormat and DescribePrincipalIdFormat -* `service/lex-models`: Updates service API and documentation -* `service/runtime.lex`: Updates service API and documentation - -Release v1.12.73 (2018-02-08) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Adds support for allowing customers to provide a redirect URL for a stack. Users will be redirected to the link provided by the admin at the end of their streaming session. -* `service/budgets`: Updates service API and documentation - * Making budgetLimit and timePeriod optional, and updating budgets docs. -* `service/dms`: Updates service API, documentation, and paginators - * This release includes the addition of two new APIs: describe replication instance task logs and reboot instance. The first allows user to see how much storage each log for a task on a given instance is occupying. The second gives users the option to reboot the application software on the instance and force a fail over for MAZ instances to test robustness of their integration with our service. -* `service/ds`: Updates service API - * Updated the regex of some input parameters to support longer EC2 identifiers. -* `service/dynamodb`: Updates service API and documentation - * Amazon DynamoDB now supports server-side encryption using a default service key (alias/aws/dynamodb) from the AWS Key Management Service (KMS). AWS KMS is a service that combines secure, highly available hardware and software to provide a key management system scaled for the cloud. AWS KMS is used via the AWS Management Console or APIs to centrally create encryption keys, define the policies that control how keys can be used, and audit key usage to prove they are being used correctly. For more information, see the Amazon DynamoDB Developer Guide. -* `service/gamelift`: Updates service API and documentation - * Amazon GameLift FlexMatch added the StartMatchBackfill API. This API allows developers to add new players to an existing game session using the same matchmaking rules and player data that were used to initially create the session. -* `service/medialive`: Updates service API and documentation - * AWS Elemental MediaLive has added support for updating channel settings for idle channels. You can now update channel name, channel outputs and output destinations, encoder settings, user role ARN, and input specifications. Channel settings can be updated in the console or with API calls. Please note that running channels need to be stopped before they can be updated. We've also deprecated the 'Reserved' field. -* `service/mediastore`: Updates service API and documentation - * AWS Elemental MediaStore now supports per-container CORS configuration. - -Release v1.12.72 (2018-02-07) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * This new feature will now allow customers to add a customized json classifier. They can specify a json path to indicate the object, array or field of the json documents they'd like crawlers to inspect when they crawl json files. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * This release of Service Catalog adds SearchProvisionedProducts API and ProvisionedProductPlan APIs. -* `service/servicediscovery`: Updates service API and documentation - * This release adds support for registering CNAME record types and creating Route 53 alias records that route traffic to Amazon Elastic Load Balancers using Amazon Route 53 Auto Naming APIs. -* `service/ssm`: Updates service API and documentation - * This Patch Manager release supports configuring Linux repos as part of patch baselines, controlling updates of non-OS security packages and also creating patch baselines for SUSE12 - -### SDK Enhancements -* `private/model/api`: Add validation to ensure there is no duplication of services in models/apis ([#1758](https://github.com/aws/aws-sdk-go/pull/1758)) - * Prevents the SDK from mistakenly generating code a single service multiple times with different model versions. -* `example/service/ec2/instancesbyRegion`: Fix typos in example ([#1762](https://github.com/aws/aws-sdk-go/pull/1762)) -* `private/model/api`: removing SDK API reference crosslinks from input/output shapes. (#1765) - -### SDK Bugs -* `aws/session`: Fix bug in session.New not supporting AWS_SDK_LOAD_CONFIG ([#1770](https://github.com/aws/aws-sdk-go/pull/1770)) - * Fixes a bug in the session.New function that was not correctly sourcing the shared configuration files' path. - * Fixes [#1771](https://github.com/aws/aws-sdk-go/pull/1771) -Release v1.12.71 (2018-02-05) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation updates for acm -* `service/cloud9`: Updates service documentation and examples - * API usage examples for AWS Cloud9. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API and documentation - * Using ListShards a Kinesis Data Streams customer or client can get information about shards in a data stream (including meta-data for each shard) without obtaining data stream level information. -* `service/opsworks`: Updates service API, documentation, and waiters - * AWS OpsWorks Stacks supports EBS encryption and HDD volume types. Also, a new DescribeOperatingSystems API is available, which lists all operating systems supported by OpsWorks Stacks. - -Release v1.12.70 (2018-01-26) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * Add InteractionMode in CreateRemoteAccessSession for DirectDeviceAccess feature. -* `service/medialive`: Updates service API and documentation - * Add InputSpecification to CreateChannel (specification of input attributes is used for channel sizing and affects pricing); add NotFoundException to DeleteInputSecurityGroups. -* `service/mturk-requester`: Updates service documentation - -Release v1.12.69 (2018-01-26) -=== - -### SDK Bugs -* `models/api`: Fix colliding names [#1754](https://github.com/aws/aws-sdk-go/pull/1754) [#1756](https://github.com/aws/aws-sdk-go/pull/1756) - * SDK had duplicate folders that were causing errors in some builds. - * Fixes [#1753](https://github.com/aws/aws-sdk-go/issues/1753) -Release v1.12.68 (2018-01-25) -=== - -### Service Client Updates -* `service/alexaforbusiness`: Updates service API and documentation -* `service/codebuild`: Updates service API and documentation - * Adding support for Shallow Clone and GitHub Enterprise in AWS CodeBuild. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/guardduty`: Adds new service - * Added the missing AccessKeyDetails object to the resource shape. -* `service/lambda`: Updates service API and documentation - * AWS Lambda now supports Revision ID on your function versions and aliases, to track and apply conditional updates when you are updating your function version or alias resources. - -### SDK Bugs -* `service/s3/s3manager`: Fix check for nil OrigErr in Error() [#1749](https://github.com/aws/aws-sdk-go/issues/1749) - * S3 Manager's `Error` type did not check for nil of `OrigErr` when calling `Error()` - * Fixes [#1748](https://github.com/aws/aws-sdk-go/issues/1748) -Release v1.12.67 (2018-01-22) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add additional costTypes: IncludeDiscount, UseAmortized, to support finer control for different charges included in a cost budget. - -Release v1.12.66 (2018-01-19) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glue`: Updates service API and documentation - * New AWS Glue DataCatalog APIs to manage table versions and a new feature to skip archiving of the old table version when updating table. -* `service/transcribe`: Adds new service - -Release v1.12.65 (2018-01-18) -=== - -### Service Client Updates -* `service/sagemaker`: Updates service API and documentation - * CreateTrainingJob and CreateEndpointConfig now supports KMS Key for volume encryption. - -Release v1.12.64 (2018-01-17) -=== - -### Service Client Updates -* `service/autoscaling-plans`: Updates service documentation -* `service/ec2`: Updates service documentation - * Documentation updates for EC2 - -Release v1.12.63 (2018-01-17) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/autoscaling-plans`: Adds new service -* `service/rds`: Updates service API and documentation - * With this release you can now integrate RDS DB instances with CloudWatch Logs. We have added parameters to the operations for creating and modifying DB instances (for example CreateDBInstance) to allow you to take advantage of this capability through the CLI and API. Once you enable this feature, a stream of log events will publish to CloudWatch Logs for each log type you enable. - -Release v1.12.62 (2018-01-15) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lambda`: Updates service API and documentation - * Support for creating Lambda Functions using 'dotnetcore2.0' and 'go1.x'. - -Release v1.12.61 (2018-01-12) -=== - -### Service Client Updates -* `service/glue`: Updates service API and documentation - * Support is added to generate ETL scripts in Scala which can now be run by AWS Glue ETL jobs. In addition, the trigger API now supports firing when any conditions are met (in addition to all conditions). Also, jobs can be triggered based on a "failed" or "stopped" job run (in addition to a "succeeded" job run). - -Release v1.12.60 (2018-01-11) -=== - -### Service Client Updates -* `service/elasticloadbalancing`: Updates service API and documentation -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/rds`: Updates service API and documentation - * Read Replicas for Amazon RDS for MySQL, MariaDB, and PostgreSQL now support Multi-AZ deployments.Amazon RDS Read Replicas enable you to create one or more read-only copies of your database instance within the same AWS Region or in a different AWS Region. Updates made to the source database are asynchronously copied to the Read Replicas. In addition to providing scalability for read-heavy workloads, you can choose to promote a Read Replica to become standalone a DB instance when needed.Amazon RDS Multi-AZ Deployments provide enhanced availability for database instances within a single AWS Region. With Multi-AZ, your data is synchronously replicated to a standby in a different Availability Zone (AZ). In case of an infrastructure failure, Amazon RDS performs an automatic failover to the standby, minimizing disruption to your applications.You can now combine Read Replicas with Multi-AZ as part of a disaster recovery strategy for your production databases. A well-designed and tested plan is critical for maintaining business continuity after a disaster. Since Read Replicas can also be created in different regions than the source database, your Read Replica can be promoted to become the new production database in case of a regional disruption.You can also combine Read Replicas with Multi-AZ for your database engine upgrade process. You can create a Read Replica of your production database instance and upgrade it to a new database engine version. When the upgrade is complete, you can stop applications, promote the Read Replica to a standalone database instance and switch over your applications. Since the database instance is already a Multi-AZ deployment, no additional steps are needed.For more information, see the Amazon RDS User Guide. -* `service/ssm`: Updates service documentation - * Updates documentation for the HierarchyLevelLimitExceededException error. - -Release v1.12.59 (2018-01-09) -=== - -### Service Client Updates -* `service/kms`: Updates service documentation - * Documentation updates for AWS KMS - -Release v1.12.58 (2018-01-09) -=== - -### Service Client Updates -* `service/ds`: Updates service API and documentation - * On October 24 we introduced AWS Directory Service for Microsoft Active Directory (Standard Edition), also known as AWS Microsoft AD (Standard Edition), which is a managed Microsoft Active Directory (AD) that is optimized for small and midsize businesses (SMBs). With this SDK release, you can now create an AWS Microsoft AD directory using API. This enables you to run typical SMB workloads using a cost-effective, highly available, and managed Microsoft AD in the AWS Cloud. - -Release v1.12.57 (2018-01-08) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * The AWS CodeDeploy API was updated to support DeleteGitHubAccountToken, a new method that deletes a GitHub account connection. -* `service/discovery`: Updates service API and documentation - * Documentation updates for AWS Application Discovery Service. -* `service/route53`: Updates service API and documentation - * This release adds an exception to the CreateTrafficPolicyVersion API operation. - -Release v1.12.56 (2018-01-05) -=== - -### Service Client Updates -* `service/inspector`: Updates service API, documentation, and examples - * Added 2 new attributes to the DescribeAssessmentTemplate response, indicating the total number of assessment runs and last assessment run ARN (if present.) -* `service/snowball`: Updates service documentation - * Documentation updates for snowball -* `service/ssm`: Updates service documentation - * Documentation updates for ssm - -Release v1.12.55 (2018-01-02) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for rds - -Release v1.12.54 (2017-12-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/workspaces`: Updates service API and documentation - * Modify WorkSpaces have been updated with flexible storage and switching of hardware bundles feature. The following configurations have been added to ModifyWorkSpacesProperties: storage and compute. This update provides the capability to configure the storage of a WorkSpace. It also adds the capability of switching hardware bundle of a WorkSpace by specifying an eligible compute (Value, Standard, Performance, Power). - -Release v1.12.53 (2017-12-22) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * This release fixes an issue with tags not showing in DescribeAddresses responses. -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now set a health check initialization wait period of their ECS services, the services that are associated with an Elastic Load Balancer (ELB) will wait for a period of time before the ELB become healthy. You can now configure this in Create and Update Service. -* `service/inspector`: Updates service API and documentation - * PreviewAgents API now returns additional fields within the AgentPreview data type. The API now shows the agent health and availability status for all instances included in the assessment target. This allows users to check the health status of Inspector Agents before running an assessment. In addition, it shows the instance ID, hostname, and IP address of the targeted instances. -* `service/sagemaker`: Updates service API and documentation - * SageMaker Models no longer support SupplementalContainers. API's that have been affected are CreateModel and DescribeModel. - -Release v1.12.52 (2017-12-21) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Adding support allowing AWS CodeBuild customers to select specific curated image versions. -* `service/ec2`: Updates service API and documentation - * Elastic IP tagging enables you to add key and value metadata to your Elastic IPs so that you can search, filter, and organize them according to your organization's needs. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesisanalytics`: Updates service API and documentation - * Kinesis Analytics now supports AWS Lambda functions as output. - -Release v1.12.51 (2017-12-21) -=== - -### Service Client Updates -* `service/config`: Updates service API -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API and documentation - * This release adds support for code signed Over-the-air update functionality for Amazon FreeRTOS. Users can now create and schedule Over-the-air updates to their Amazon FreeRTOS devices using these new APIs. - -Release v1.12.50 (2017-12-19) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * API Gateway now adds support for calling API with compressed payloads using one of the supported content codings, tagging an API stage for cost allocation, and returning API keys from a custom authorizer for use with a usage plan. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mediastore-data`: Updates service documentation -* `service/route53`: Updates service API and documentation - * Route 53 added support for a new China (Ningxia) region, cn-northwest-1. You can now specify cn-northwest-1 as the region for latency-based or geoproximity routing. Route 53 also added support for a new EU (Paris) region, eu-west-3. You can now associate VPCs in eu-west-3 with private hosted zones and create alias records that route traffic to resources in eu-west-3. - -Release v1.12.49 (2017-12-19) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/monitoring`: Updates service documentation - * Documentation updates for monitoring - -Release v1.12.48 (2017-12-15) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update is to enable customers to add tags to their Amazon AppStream 2.0 resources - -Release v1.12.47 (2017-12-14) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adds support for Cognito Authorizer scopes at the API method level. -* `service/email`: Updates service documentation - * Added information about the maximum number of transactions per second for the SendCustomVerificationEmail operation. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.46 (2017-12-12) -=== - -### Service Client Updates -* `service/workmail`: Adds new service - * Today, Amazon WorkMail released an administrative SDK and enabled AWS CloudTrail integration. With the administrative SDK, you can natively integrate WorkMail with your existing services. The SDK enables programmatic user, resource, and group management through API calls. This means your existing IT tools and workflows can now automate WorkMail management, and third party applications can streamline WorkMail migrations and account actions. - -Release v1.12.45 (2017-12-11) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation -* `service/sagemaker`: Updates service API - * CreateModel API Update: The request parameter 'ExecutionRoleArn' has changed from optional to required. - -Release v1.12.44 (2017-12-08) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * This API update is to support the feature that allows customers to automatically consume the latest Amazon AppStream 2.0 agent as and when published by AWS. -* `service/ecs`: Updates service documentation - * Documentation updates for Windows containers. -* `service/monitoring`: Updates service API and documentation - * With this launch, you can now create a CloudWatch alarm that alerts you when M out of N datapoints of a metric are breaching your predefined threshold, such as three out of five times in any given five minutes interval or two out of six times in a thirty minutes interval. When M out of N datapoints are not breaching your threshold in an interval, the alarm will be in OK state. Please note that the M datapoints out of N datapoints in an interval can be of any order and does not need to be consecutive. Consequently, you can now get alerted even when the spikes in your metrics are intermittent over an interval. - -Release v1.12.43 (2017-12-07) -=== - -### Service Client Updates -* `service/email`: Updates service API, documentation, and paginators - * Customers can customize the emails that Amazon SES sends when verifying new identities. This feature is helpful for developers whose applications send email through Amazon SES on behalf of their customers. -* `service/es`: Updates service API and documentation - * Added support for encryption of data at rest on Amazon Elasticsearch Service using AWS KMS - -### SDK Bugs -* `models/apis` Fixes removes colliding sagemaker models folders ([#1686](https://github.com/aws/aws-sdk-go/pull/1686)) - * Fixes Release v1.12.42's SageMaker vs sagemaker model folders. -Release v1.12.42 (2017-12-06) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Amazon Cloud Directory makes it easier for you to apply schema changes across your directories with in-place schema upgrades. Your directories now remain available while backward-compatible schema changes are being applied, such as the addition of new fields. You also can view the history of your schema changes in Cloud Directory by using both major and minor version identifiers, which can help you track and audit schema versions across directories. -* `service/elasticbeanstalk`: Updates service documentation - * Documentation updates for AWS Elastic Beanstalk. -* `service/sagemaker`: Adds new service - * Initial waiters for common SageMaker workflows. - -Release v1.12.41 (2017-12-05) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * Add error action API for RulesEngine. -* `service/servicecatalog`: Updates service API and documentation - * ServiceCatalog has two distinct personas for its use, an "admin" persona (who creates sets of products with different versions and prescribes who has access to them) and an "end-user" persona (who can launch cloud resources based on the configuration data their admins have given them access to). This API update will allow admin users to deactivate/activate product versions, end-user will only be able to access and launch active product versions. -* `service/servicediscovery`: Adds new service - * Amazon Route 53 Auto Naming lets you configure public or private namespaces that your microservice applications run in. When instances of the service become available, you can call the Auto Naming API to register the instance, and Amazon Route 53 automatically creates up to five DNS records and an optional health check. Clients that submit DNS queries for the service receive an answer that contains up to eight healthy records. - -Release v1.12.40 (2017-12-04) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add additional costTypes to support finer control for different charges included in a cost budget. -* `service/ecs`: Updates service documentation - * Documentation updates for ecs - -Release v1.12.39 (2017-12-01) -=== - -### Service Client Updates -* `service/SageMaker`: Updates service waiters - -Release v1.12.38 (2017-11-30) -=== - -### Service Client Updates -* `service/AWSMoneypenny`: Adds new service -* `service/Cloud9`: Adds new service -* `service/Serverless Registry`: Adds new service -* `service/apigateway`: Updates service API, documentation, and paginators - * Added support Private Integration and VPC Link features in API Gateway. This allows to create an API with the API Gateway private integration, thus providing clients access to HTTP/HTTPS resources in an Amazon VPC from outside of the VPC through a VpcLink resource. -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. Spread Placement ensures that instances are placed on distinct hardware in order to reduce correlated failures. 2. Inter-region VPC Peering allows customers to peer VPCs across different AWS regions without requiring additional gateways, VPN connections or physical hardware -* `service/lambda`: Updates service API and documentation - * AWS Lambda now supports the ability to set the concurrency limits for individual functions, and increasing memory to 3008 MB. - -Release v1.12.37 (2017-11-30) -=== - -### Service Client Updates -* `service/Ardi`: Adds new service -* `service/autoscaling`: Updates service API and documentation - * You can now use Auto Scaling with EC2 Launch Templates via the CreateAutoScalingGroup and UpdateAutoScalingGroup APIs. -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. T2 Unlimited enables high CPU performance for any period of time whenever required 2. You are now able to create and launch EC2 m5 and h1 instances -* `service/lightsail`: Updates service API and documentation - * This release adds support for load balancer and TLS/SSL certificate management. This set of APIs allows customers to create, manage, and scale secure load balanced applications on Lightsail infrastructure. To provide support for customers who manage their DNS on Lightsail, we've added the ability create an Alias A type record which can point to a load balancer DNS name via the CreateDomainEntry API http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_CreateDomainEntry.html. -* `service/ssm`: Updates service API and documentation - * This release updates AWS Systems Manager APIs to enable executing automations at controlled rate, target resources in a resource groups and execute entire automation at once or single step at a time. It is now also possible to use YAML, in addition to JSON, when creating Systems Manager documents. -* `service/waf`: Updates service API and documentation - * This release adds support for rule group and managed rule group. Rule group is a container of rules that customers can create, put rules in it and associate the rule group to a WebACL. All rules in a rule group will function identically as they would if each rule was individually associated to the WebACL. Managed rule group is a pre-configured rule group composed by our security partners and made available via the AWS Marketplace. Customers can subscribe to these managed rule groups, associate the managed rule group to their WebACL and start using them immediately to protect their resources. -* `service/waf-regional`: Updates service API and documentation - -Release v1.12.36 (2017-11-29) -=== - -### Service Client Updates -* `service/DeepInsight`: Adds new service -* `service/IronmanRuntime`: Adds new service -* `service/Orchestra - Laser`: Adds new service -* `service/SageMaker`: Adds new service -* `service/Shine`: Adds new service -* `service/archived.kinesisvideo`: Adds new service -* `service/data.kinesisvideo`: Adds new service -* `service/dynamodb`: Updates service API and documentation - * Amazon DynamoDB now supports the following features: Global Table and On-Demand Backup. Global Table is a fully-managed, multi-region, multi-master database. DynamoDB customers can now write anywhere and read anywhere with single-digit millisecond latency by performing database operations closest to where end users reside. Global Table also enables customers to disaster-proof their applications, keeping them running and data accessible even in the face of natural disasters or region disruptions. Customers can set up Global Table with just a few clicks in the AWS Management Console-no application rewrites required. On-Demand Backup capability is to protect data from loss due to application errors, and meet customers' archival needs for compliance and regulatory reasons. Customers can backup and restore their DynamoDB table data anytime, with a single-click in the AWS management console or a single API call. Backup and restore actions execute with zero impact on table performance or availability. For more information, see the Amazon DynamoDB Developer Guide. -* `service/ecs`: Updates service API and documentation - * Amazon Elastic Container Service (Amazon ECS) released a new launch type for running containers on a serverless infrastructure. The Fargate launch type allows you to run your containerized applications without the need to provision and manage the backend infrastructure. Just register your task definition and Fargate launches the container for you. -* `service/glacier`: Updates service API and documentation - * This release includes support for Glacier Select, a new feature that allows you to filter and analyze your Glacier archives and store the results in a user-specified S3 location. -* `service/greengrass`: Updates service API and documentation - * Greengrass OTA feature allows updating Greengrass Core and Greengrass OTA Agent. Local Resource Access feature allows Greengrass Lambdas to access local resources such as peripheral devices and volumes. -* `service/iot`: Updates service API and documentation - * This release adds support for a number of new IoT features, including AWS IoT Device Management (Jobs, Fleet Index and Thing Registration), Thing Groups, Policies on Thing Groups, Registry & Job Events, JSON Logs, Fine-Grained Logging Controls, Custom Authorization and AWS Service Authentication Using X.509 Certificates. -* `service/kinesisvideo`: Adds new service - * Announcing Amazon Kinesis Video Streams, a fully managed video ingestion and storage service. Kinesis Video Streams makes it easy to securely stream video from connected devices to AWS for machine learning, analytics, and processing. You can also stream other time-encoded data like RADAR and LIDAR signals using Kinesis Video Streams. -* `service/rekognition`: Updates service API, documentation, and paginators - * This release introduces Amazon Rekognition support for video analysis. -* `service/s3`: Updates service API and documentation - * This release includes support for Glacier Select, a new feature that allows you to filter and analyze your Glacier storage class objects and store the results in a user-specified S3 location. - -Release v1.12.35 (2017-11-29) -=== - -### Service Client Updates -* `service/AmazonMQ`: Adds new service -* `service/GuardDuty`: Adds new service -* `service/apigateway`: Updates service API and documentation - * Changes related to CanaryReleaseDeployment feature. Enables API developer to create a deployment as canary deployment and test API changes with percentage of customers before promoting changes to all customers. -* `service/batch`: Updates service API and documentation - * Add support for Array Jobs which allow users to easily submit many copies of a job with a single API call. This change also enhances the job dependency model to support N_TO_N and sequential dependency chains. The ListJobs and DescribeJobs APIs now have the ability to list or describe the status of entire Array Jobs or individual elements within the array. -* `service/cognito-idp`: Updates service API and documentation -* `service/deepdish`: Adds new service - * AWS AppSync is an enterprise-level, fully managed GraphQL service with real-time data synchronization and offline programming features. -* `service/ec2`: Updates service API and documentation - * Adds the following updates: 1. You are now able to host a service powered by AWS PrivateLink to provide private connectivity to other VPCs. You are now also able to create endpoints to other services powered by PrivateLink including AWS services, Marketplace Seller services or custom services created by yourself or other AWS VPC customers. 2. You are now able to save launch parameters in a single template that can be used with Auto Scaling, Spot Fleet, Spot, and On Demand instances. 3. You are now able to launch Spot instances via the RunInstances API, using a single additional parameter. RunInstances will response synchronously with an instance ID should capacity be available for your Spot request. 4. A simplified Spot pricing model which delivers low, predictable prices that adjust gradually, based on long-term trends in supply and demand. 5. Amazon EC2 Spot can now hibernate Amazon EBS-backed instances in the event of an interruption, so your workloads pick up from where they left off. Spot can fulfill your request by resuming instances from a hibernated state when capacity is available. -* `service/lambda`: Updates service API and documentation - * Lambda aliases can now shift traffic between two function versions, based on preassigned weights. - -Release v1.12.34 (2017-11-27) -=== - -### Service Client Updates -* `service/data.mediastore`: Adds new service -* `service/mediaconvert`: Adds new service - * AWS Elemental MediaConvert is a file-based video conversion service that transforms media into formats required for traditional broadcast and for internet streaming to multi-screen devices. -* `service/medialive`: Adds new service - * AWS Elemental MediaLive is a video service that lets you easily create live outputs for broadcast and streaming delivery. -* `service/mediapackage`: Adds new service - * AWS Elemental MediaPackage is a just-in-time video packaging and origination service that lets you format highly secure and reliable live outputs for a variety of devices. -* `service/mediastore`: Adds new service - * AWS Elemental MediaStore is an AWS storage service optimized for media. It gives you the performance, consistency, and low latency required to deliver live and on-demand video content. AWS Elemental MediaStore acts as the origin store in your video workflow. - -Release v1.12.33 (2017-11-22) -=== - -### Service Client Updates -* `service/acm`: Updates service API and documentation - * AWS Certificate Manager now supports the ability to import domainless certs and additional Key Types as well as an additional validation method for DNS. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.32 (2017-11-22) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for Access logs and customizable integration timeouts -* `service/cloudformation`: Updates service API and documentation - * 1) Instance-level parameter overrides (CloudFormation-StackSet feature): This feature will allow the customers to override the template parameters on specific stackInstances. Customers will also have ability to update their existing instances with/without parameter-overrides using a new API "UpdateStackInstances" 2) Add support for SSM parameters in CloudFormation - This feature will allow the customers to use Systems Manager parameters in CloudFormation templates. They will be able to see values for these parameters in Describe APIs. -* `service/codebuild`: Updates service API and documentation - * Adding support for accessing Amazon VPC resources from AWS CodeBuild, dependency caching and build badges. -* `service/elasticmapreduce`: Updates service API and documentation - * Enable Kerberos on Amazon EMR. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rekognition`: Updates service API and documentation - * This release includes updates to Amazon Rekognition for the following APIs. The new DetectText API allows you to recognize and extract textual content from images. Face Model Versioning has been added to operations that deal with face detection. -* `service/shield`: Updates service API, documentation, and paginators - * The AWS Shield SDK has been updated in order to support Elastic IP address protections, the addition of AttackProperties objects in DescribeAttack responses, and a new GetSubscriptionState operation. -* `service/storagegateway`: Updates service API and documentation - * AWS Storage Gateway now enables you to get notification when all your files written to your NFS file share have been uploaded to Amazon S3. Storage Gateway also enables guessing of the MIME type for uploaded objects based on file extensions. -* `service/xray`: Updates service API, documentation, and paginators - * Added automatic pagination support for AWS X-Ray APIs in the SDKs that support this feature. - -Release v1.12.31 (2017-11-20) -=== - -### Service Client Updates -* `service/apigateway`: Updates service documentation - * Documentation updates for Apigateway -* `service/codecommit`: Updates service API, documentation, and paginators - * AWS CodeCommit now supports pull requests. You can use pull requests to collaboratively review code changes for minor changes or fixes, major feature additions, or new versions of your released software. -* `service/firehose`: Updates service API and documentation - * This release includes a new Kinesis Firehose feature that supports Splunk as Kinesis Firehose delivery destination. You can now use Kinesis Firehose to ingest real-time data to Splunk in a serverless, reliable, and salable manner. This release also includes a new feature that allows you to configure Lambda buffer size in Kinesis Firehose data transformation feature. You can now customize the data buffer size before invoking Lambda function in Kinesis Firehose for data transformation. This feature allows you to flexibly trade-off processing and delivery latency with cost and efficiency based on your specific use cases and requirements. -* `service/iis`: Adds new service - * The AWS Cost Explorer API gives customers programmatic access to AWS cost and usage information, allowing them to perform adhoc queries and build interactive cost management applications that leverage this dataset. -* `service/kinesis`: Updates service API and documentation - * Customers can now obtain the important characteristics of their stream with DescribeStreamSummary. The response will not include the shard list for the stream but will have the number of open shards, and all the other fields included in the DescribeStream response. -* `service/workdocs`: Updates service API and documentation - * DescribeGroups API and miscellaneous enhancements - -### SDK Bugs -* `aws/client`: Retry delays for throttled exception were not limited to 5 minutes [#1654](https://github.com/aws/aws-sdk-go/pull/1654) - * Fixes [#1653](https://github.com/aws/aws-sdk-go/issues/1653) -Release v1.12.30 (2017-11-17) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/dms`: Updates service API, documentation, and paginators - * Support for migration task assessment. Support for data validation after the migration. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Amazon RDS now supports importing MySQL databases by using backup files from Amazon S3. -* `service/s3`: Updates service API - * Added ORC to the supported S3 Inventory formats. - -### SDK Bugs -* `private/protocol/restjson`: Define JSONValue marshaling for body and querystring ([#1640](https://github.com/aws/aws-sdk-go/pull/1640)) - * Adds support for APIs which use JSONValue for body and querystring targets. - * Fixes [#1636](https://github.com/aws/aws-sdk-go/issues/1636) -Release v1.12.29 (2017-11-16) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 x1e smaller instance sizes -* `service/glue`: Updates service API and documentation - * API update for AWS Glue. New crawler configuration attribute enables customers to specify crawler behavior. New XML classifier enables classification of XML data. -* `service/opsworkscm`: Updates service API, documentation, and waiters - * Documentation updates for OpsWorks-cm: a new feature, OpsWorks for Puppet Enterprise, that allows users to create and manage OpsWorks-hosted Puppet Enterprise servers. -* `service/organizations`: Updates service API, documentation, and paginators - * This release adds APIs that you can use to enable and disable integration with AWS services designed to work with AWS Organizations. This integration allows the AWS service to perform operations on your behalf on all of the accounts in your organization. Although you can use these APIs yourself, we recommend that you instead use the commands provided in the other AWS service to enable integration with AWS Organizations. -* `service/route53`: Updates service API and documentation - * You can use Route 53's GetAccountLimit/GetHostedZoneLimit/GetReusableDelegationSetLimit APIs to view your current limits (including custom set limits) on Route 53 resources such as hosted zones and health checks. These APIs also return the number of each resource you're currently using to enable comparison against your current limits. - -Release v1.12.28 (2017-11-15) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * 1. Extended GetDocumentationParts operation to support retrieving documentation parts resources without contents. 2. Added hosted zone ID in the custom domain response. -* `service/email`: Updates service API, documentation, and examples - * SES launches Configuration Set Reputation Metrics and Email Pausing Today, two features that build upon the capabilities of the reputation dashboard. The first is the ability to export reputation metrics for individual configuration sets. The second is the ability to temporarily pause email sending, either at the configuration set level, or across your entire Amazon SES account. -* `service/polly`: Updates service API - * Amazon Polly adds Korean language support with new female voice - "Seoyeon" and new Indian English female voice - "Aditi" -* `service/states`: Updates service API and documentation - * You can now use the UpdateStateMachine API to update your state machine definition and role ARN. Existing executions will continue to use the previous definition and role ARN. You can use the DescribeStateMachineForExecution API to determine which state machine definition and role ARN is associated with an execution - -Release v1.12.27 (2017-11-14) -=== - -### Service Client Updates -* `service/ecs`: Updates service API and documentation - * Added new mode for Task Networking in ECS, called awsvpc mode. Mode configuration parameters to be passed in via awsvpcConfiguration. Updated APIs now use/show this new mode - RegisterTaskDefinition, CreateService, UpdateService, RunTask, StartTask. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lightsail`: Updates service API and documentation - * Lightsail now supports attached block storage, which allows you to scale your applications and protect application data with additional SSD-backed storage disks. This feature allows Lightsail customers to attach secure storage disks to their Lightsail instances and manage their attached disks, including creating and deleting disks, attaching and detaching disks from instances, and backing up disks via snapshot. -* `service/route53`: Updates service API and documentation - * When a Route 53 health check or hosted zone is created by a linked AWS service, the object now includes information about the service that created it. Hosted zones or health checks that are created by a linked service can't be updated or deleted using Route 53. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager GetInventory API adds support for aggregation. - -### SDK Enhancements -* `aws/request`: Remove default port from HTTP host header ([#1618](https://github.com/aws/aws-sdk-go/pull/1618)) - * Updates the SDK to automatically remove default ports based on the URL's scheme when setting the HTTP Host header's value. - * Fixes [#1537](https://github.com/aws/aws-sdk-go/issues/1537) - -Release v1.12.26 (2017-11-09) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Introduces the following features: 1. Create a default subnet in an Availability Zone if no default subnet exists. 2. Spot Fleet integrates with Elastic Load Balancing to enable you to attach one or more load balancers to a Spot Fleet request. When you attach the load balancer, it automatically registers the instance in the Spot Fleet to the load balancers which distributes incoming traffic across the instances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.25 (2017-11-08) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/batch`: Updates service documentation - * Documentation updates for AWS Batch. -* `service/ec2`: Updates service API and documentation - * AWS PrivateLink for Amazon Services - Customers can now privately access Amazon services from their Amazon Virtual Private Cloud (VPC), without using public IPs, and without requiring the traffic to traverse across the Internet. -* `service/elasticache`: Updates service API and documentation - * This release adds online resharding for ElastiCache for Redis offering, providing the ability to add and remove shards from a running cluster. Developers can now dynamically scale-out or scale-in their Redis cluster workloads to adapt to changes in demand. ElastiCache will resize the cluster by adding or removing shards and redistribute hash slots uniformly across the new shard configuration, all while the cluster continues to stay online and serves requests. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.24 (2017-11-07) -=== - -### Service Client Updates -* `service/elasticloadbalancingv2`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * DescribeOrderableDBInstanceOptions now returns the minimum and maximum allowed values for storage size, total provisioned IOPS, and provisioned IOPS per GiB for a DB instance. -* `service/s3`: Updates service API, documentation, and examples - * This releases adds support for 4 features: 1. Default encryption for S3 Bucket, 2. Encryption status in inventory and Encryption support for inventory. 3. Cross region replication of KMS-encrypted objects, and 4. ownership overwrite for CRR. - -Release v1.12.23 (2017-11-07) -=== - -### Service Client Updates -* `service/api.pricing`: Adds new service -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 C5 instances, the next generation of EC2's compute-optimized instances, in us-east-1, us-west-2 and eu-west-1. C5 instances offer up to 72 vCPUs, 144 GiB of DDR4 instance memory, 25 Gbps in Network bandwidth and improved EBS and Networking bandwidth on smaller instance sizes to deliver improved performance for compute-intensive workloads. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kms`: Updates service API, documentation, and examples - * Documentation updates for AWS KMS. -* `service/organizations`: Updates service documentation - * This release updates permission statements for several API operations, and corrects some other minor errors. -* `service/states`: Updates service API, documentation, and paginators - * Documentation update. - -Release v1.12.22 (2017-11-03) -=== - -### Service Client Updates -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now add devices to their containers and enable init process in containers through the use of docker's 'devices' and 'init' features. These fields can be specified under linuxParameters in ContainerDefinition in the Task Definition Template. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.21 (2017-11-02) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * This release supports creating and managing Regional and Edge-Optimized API endpoints. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -### SDK Bugs -* `aws/request`: Fix bug in request presign creating invalid URL ([#1624](https://github.com/aws/aws-sdk-go/pull/1624)) - * Fixes a bug the Request Presign and PresignRequest methods that would allow a invalid expire duration as input. A expire time of 0 would be interpreted by the SDK to generate a normal request signature, not a presigned URL. This caused the returned URL unusable. - * Fixes [#1617](https://github.com/aws/aws-sdk-go/issues/1617) -Release v1.12.20 (2017-11-01) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation updates for ACM -* `service/cloudhsmv2`: Updates service documentation - * Minor documentation update for AWS CloudHSM (cloudhsmv2). -* `service/directconnect`: Updates service API and documentation - * AWS DirectConnect now provides support for Global Access for Virtual Private Cloud (VPC) via a new feature called Direct Connect Gateway. A Direct Connect Gateway will allow you to group multiple Direct Connect Private Virtual Interfaces (DX-VIF) and Private Virtual Gateways (VGW) from different AWS regions (but belonging to the same AWS Account) and pass traffic from any DX-VIF to any VPC in the grouping. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -### SDK Enhancements -* `aws/client`: Adding status code 429 to throttlable status codes in default retryer (#1621) - -Release v1.12.19 (2017-10-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.18 (2017-10-26) -=== - -### Service Client Updates -* `service/cloudfront`: Updates service API and documentation - * You can now specify additional options for MinimumProtocolVersion, which controls the SSL/TLS protocol that CloudFront uses to communicate with viewers. The minimum protocol version that you choose also determines the ciphers that CloudFront uses to encrypt the content that it returns to viewers. -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 P3 instance, next generation GPU instances, optimized for machine learning and high performance computing applications. With up to eight NVIDIA Tesla V100 GPUs, P3 instances provide up to one petaflop of mixed-precision, 125 teraflops of single-precision, and 62 teraflops of double-precision floating point performance, as well as a 300 GB/s second-generation NVLink interconnect that enables high-speed, low-latency GPU-to-GPU communication. P3 instances also feature up to 64 vCPUs based on custom Intel Xeon E5 (Broadwell) processors, 488 GB of DRAM, and 25 Gbps of dedicated aggregate network bandwidth using the Elastic Network Adapter (ENA). -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.17 (2017-10-24) -=== - -### Service Client Updates -* `service/config`: Updates service API -* `service/elasticache`: Updates service API, documentation, and examples - * Amazon ElastiCache for Redis today announced support for data encryption both for data in-transit and data at-rest. The new encryption in-transit functionality enables ElastiCache for Redis customers to encrypt data for all communication between clients and Redis engine, and all intra-cluster Redis communication. The encryption at-rest functionality allows customers to encrypt their S3 based backups. Customers can begin using the new functionality by simply enabling this functionality via AWS console, and a small configuration change in their Redis clients. The ElastiCache for Redis service automatically manages life cycle of the certificates required for encryption, including the issuance, renewal and expiration of certificates. Additionally, as part of this launch, customers will gain the ability to start using the Redis AUTH command that provides an added level of authentication. -* `service/glue`: Adds new service - * AWS Glue: Adding a new API, BatchStopJobRun, to stop one or more job runs for a specified Job. -* `service/pinpoint`: Updates service API and documentation - * Added support for APNs VoIP messages. Added support for collapsible IDs, message priority, and TTL for APNs and FCM/GCM. - -Release v1.12.16 (2017-10-23) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/organizations`: Updates service API and documentation - * This release supports integrating other AWS services with AWS Organizations through the use of an IAM service-linked role called AWSServiceRoleForOrganizations. Certain operations automatically create that role if it does not already exist. - -Release v1.12.15 (2017-10-20) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adding pagination support for DescribeSecurityGroups for EC2 Classic and VPC Security Groups - -Release v1.12.14 (2017-10-19) -=== - -### Service Client Updates -* `service/sqs`: Updates service API and documentation - * Added support for tracking cost allocation by adding, updating, removing, and listing the metadata tags of Amazon SQS queues. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager versioning support for Parameter Store. Also support for referencing parameter versions in SSM Documents. - -Release v1.12.13 (2017-10-18) -=== - -### Service Client Updates -* `service/lightsail`: Updates service API and documentation - * This release adds support for Windows Server-based Lightsail instances. The GetInstanceAccessDetails API now returns the password of your Windows Server-based instance when using the default key pair. GetInstanceAccessDetails also returns a PasswordData object for Windows Server instances containing the ciphertext and keyPairName. The Blueprint data type now includes a list of platform values (LINUX_UNIX or WINDOWS). The Bundle data type now includes a list of SupportedPlatforms values (LINUX_UNIX or WINDOWS). - -Release v1.12.12 (2017-10-17) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/es`: Updates service API and documentation - * This release adds support for VPC access to Amazon Elasticsearch Service. - * This release adds support for VPC access to Amazon Elasticsearch Service. - -Release v1.12.11 (2017-10-16) -=== - -### Service Client Updates -* `service/cloudhsm`: Updates service API and documentation - * Documentation updates for AWS CloudHSM Classic. -* `service/ec2`: Updates service API and documentation - * You can now change the tenancy of your VPC from dedicated to default with a single API operation. For more details refer to the documentation for changing VPC tenancy. -* `service/es`: Updates service API and documentation - * AWS Elasticsearch adds support for enabling slow log publishing. Using slow log publishing options customers can configure and enable index/query slow log publishing of their domain to preferred AWS Cloudwatch log group. -* `service/rds`: Updates service API and waiters - * Adds waiters for DBSnapshotAvailable and DBSnapshotDeleted. -* `service/waf`: Updates service API and documentation - * This release adds support for regular expressions as match conditions in rules, and support for geographical location by country of request IP address as a match condition in rules. -* `service/waf-regional`: Updates service API and documentation - -Release v1.12.10 (2017-10-12) -=== - -### Service Client Updates -* `service/codecommit`: Updates service API and documentation - * This release includes the DeleteBranch API and a change to the contents of a Commit object. -* `service/dms`: Updates service API and documentation - * This change includes addition of new optional parameter to an existing API -* `service/elasticbeanstalk`: Updates service API and documentation - * Added the ability to add, delete or update Tags -* `service/polly`: Updates service API - * Amazon Polly exposes two new voices: "Matthew" (US English) and "Takumi" (Japanese) -* `service/rds`: Updates service API and documentation - * You can now call DescribeValidDBInstanceModifications to learn what modifications you can make to your DB instance. You can use this information when you call ModifyDBInstance. - -Release v1.12.9 (2017-10-11) -=== - -### Service Client Updates -* `service/ecr`: Updates service API, documentation, and paginators - * Adds support for new API set used to manage Amazon ECR repository lifecycle policies. Amazon ECR lifecycle policies enable you to specify the lifecycle management of images in a repository. The configuration is a set of one or more rules, where each rule defines an action for Amazon ECR to apply to an image. This allows the automation of cleaning up unused images, for example expiring images based on age or status. A lifecycle policy preview API is provided as well, which allows you to see the impact of a lifecycle policy on an image repository before you execute it -* `service/email`: Updates service API and documentation - * Added content related to email template management and templated email sending operations. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.12.8 (2017-10-10) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * This release includes updates to AWS Virtual Private Gateway. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `service/opsworkscm`: Updates service API and documentation - * Provide engine specific information for node associations. - -Release v1.12.7 (2017-10-06) -=== - -### Service Client Updates -* `service/sqs`: Updates service documentation - * Documentation updates regarding availability of FIFO queues and miscellaneous corrections. - -Release v1.12.6 (2017-10-05) -=== - -### Service Client Updates -* `service/redshift`: Updates service API and documentation - * DescribeEventSubscriptions API supports tag keys and tag values as request parameters. - -Release v1.12.5 (2017-10-04) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API and documentation - * Kinesis Analytics now supports schema discovery on objects in S3. Additionally, Kinesis Analytics now supports input data preprocessing through Lambda. -* `service/route53domains`: Updates service API and documentation - * Added a new API that checks whether a domain name can be transferred to Amazon Route 53. - -### SDK Bugs -* `service/s3/s3crypto`: Correct PutObjectRequest documentation ([#1568](https://github.com/aws/aws-sdk-go/pull/1568)) - * s3Crypto's PutObjectRequest docstring example was using an incorrect value. Corrected the type used in the example. -Release v1.12.4 (2017-10-03) -=== - -### Service Client Updates -* `service/ec2`: Updates service API, documentation, and waiters - * This release includes service updates to AWS VPN. -* `service/ssm`: Updates service API and documentation - * EC2 Systems Manager support for tagging SSM Documents. Also support for tag-based permissions to restrict access to SSM Documents based on these tags. - -Release v1.12.3 (2017-10-02) -=== - -### Service Client Updates -* `service/cloudhsm`: Updates service documentation and paginators - * Documentation updates for CloudHSM - -Release v1.12.2 (2017-09-29) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Includes APIs for managing and accessing image builders, and deleting images. -* `service/codebuild`: Updates service API and documentation - * Adding support for Building GitHub Pull Requests in AWS CodeBuild -* `service/mturk-requester`: Updates service API and documentation -* `service/organizations`: Updates service API and documentation - * This release flags the HandshakeParty structure's Type and Id fields as 'required'. They effectively were required in the past, as you received an error if you did not include them. This is now reflected at the API definition level. -* `service/route53`: Updates service API and documentation - * This change allows customers to reset elements of health check. - -### SDK Bugs -* `private/protocol/query`: Fix query protocol handling of nested byte slices ([#1557](https://github.com/aws/aws-sdk-go/issues/1557)) - * Fixes the query protocol to correctly marshal nested []byte values of API operations. -* `service/s3`: Fix PutObject and UploadPart API to include ContentMD5 field ([#1559](https://github.com/aws/aws-sdk-go/pull/1559)) - * Fixes the SDK's S3 PutObject and UploadPart API code generation to correctly render the ContentMD5 field into the associated input types for these two API operations. - * Fixes [#1553](https://github.com/aws/aws-sdk-go/pull/1553) -Release v1.12.1 (2017-09-27) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/pinpoint`: Updates service API and documentation - * Added two new push notification channels: Amazon Device Messaging (ADM) and, for push notification support in China, Baidu Cloud Push. Added support for APNs auth via .p8 key file. Added operation for direct message deliveries to user IDs, enabling you to message an individual user on multiple endpoints. - -Release v1.12.0 (2017-09-26) -=== - -### SDK Bugs -* `API Marshaler`: Revert REST JSON and XML protocol marshaler improvements - * Bug [#1550](https://github.com/aws/aws-sdk-go/issues/1550) identified a missed condition in the Amazon Route 53 RESTXML protocol marshaling causing requests to that service to fail. Reverting the marshaler improvements until the bug can be fixed. - -Release v1.11.0 (2017-09-26) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * You can now prevent a stack from being accidentally deleted by enabling termination protection on the stack. If you attempt to delete a stack with termination protection enabled, the deletion fails and the stack, including its status, remains unchanged. You can enable termination protection on a stack when you create it. Termination protection on stacks is disabled by default. After creation, you can set termination protection on a stack whose status is CREATE_COMPLETE, UPDATE_COMPLETE, or UPDATE_ROLLBACK_COMPLETE. - -### SDK Features -* Add dep Go dependency management metadata files (#1544) - * Adds the Go `dep` dependency management metadata files to the SDK. - * Fixes [#1451](https://github.com/aws/aws-sdk-go/issues/1451) - * Fixes [#634](https://github.com/aws/aws-sdk-go/issues/634) -* `service/dynamodb/expression`: Add expression building utility for DynamoDB ([#1527](https://github.com/aws/aws-sdk-go/pull/1527)) - * Adds a new package, expression, to the SDK providing builder utilities to create DynamoDB expressions safely taking advantage of type safety. -* `API Marshaler`: Add generated marshalers for RESTXML protocol ([#1409](https://github.com/aws/aws-sdk-go/pull/1409)) - * Updates the RESTXML protocol marshaler to use generated code instead of reflection for REST XML based services. -* `API Marshaler`: Add generated marshalers for RESTJSON protocol ([#1547](https://github.com/aws/aws-sdk-go/pull/1547)) - * Updates the RESTJSON protocol marshaler to use generated code instead of reflection for REST JSON based services. - -### SDK Enhancements -* `private/protocol`: Update format of REST JSON and XMl benchmarks ([#1546](https://github.com/aws/aws-sdk-go/pull/1546)) - * Updates the format of the REST JSON and XML benchmarks to be readable. RESTJSON benchmarks were updated to more accurately bench building of the protocol. - -Release v1.10.51 (2017-09-22) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - * Amazon ECS users can now add and drop Linux capabilities to their containers through the use of docker's cap-add and cap-drop features. Customers can specify the capabilities they wish to add or drop for each container in their task definition. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service documentation - * Documentation updates for rds - -Release v1.10.50 (2017-09-21) -=== - -### Service Client Updates -* `service/budgets`: Updates service API - * Including "DuplicateRecordException" in UpdateNotification and UpdateSubscriber. -* `service/ec2`: Updates service API and documentation - * Add EC2 APIs to copy Amazon FPGA Images (AFIs) within the same region and across multiple regions, delete AFIs, and modify AFI attributes. AFI attributes include name, description and granting/denying other AWS accounts to load the AFI. -* `service/logs`: Updates service API and documentation - * Adds support for associating LogGroups with KMS Keys. - -### SDK Bugs -* Fix greengrass service model being duplicated with different casing. ([#1541](https://github.com/aws/aws-sdk-go/pull/1541)) - * Fixes [#1540](https://github.com/aws/aws-sdk-go/issues/1540) - * Fixes [#1539](https://github.com/aws/aws-sdk-go/issues/1539) -Release v1.10.49 (2017-09-20) -=== - -### Service Client Updates -* `service/Greengrass`: Adds new service -* `service/appstream`: Updates service API and documentation - * API updates for supporting On-Demand fleets. -* `service/codepipeline`: Updates service API and documentation - * This change includes a PipelineMetadata object that is part of the output from the GetPipeline API that includes the Pipeline ARN, created, and updated timestamp. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Introduces the --option-group-name parameter to the ModifyDBSnapshot CLI command. You can specify this parameter when you upgrade an Oracle DB snapshot. The same option group considerations apply when upgrading a DB snapshot as when upgrading a DB instance. For more information, see http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_UpgradeDBInstance.Oracle.html#USER_UpgradeDBInstance.Oracle.OGPG.OG -* `service/runtime.lex`: Updates service API and documentation - -Release v1.10.48 (2017-09-19) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing ElasticGpuSet from being set. - -### SDK Enhancements -* `aws/credentials`: Add EnvProviderName constant. ([#1531](https://github.com/aws/aws-sdk-go/issues/1531)) - * Adds the "EnvConfigCredentials" string literal as EnvProviderName constant. - * Fixes [#1444](https://github.com/aws/aws-sdk-go/issues/1444) - -Release v1.10.47 (2017-09-18) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Amazon EC2 now lets you opt for Spot instances to be stopped in the event of an interruption instead of being terminated. Your Spot request can be fulfilled again by restarting instances from a previously stopped state, subject to availability of capacity at or below your preferred price. When you submit a persistent Spot request, you can choose from "terminate" or "stop" as the instance interruption behavior. Choosing "stop" will shutdown your Spot instances so you can continue from this stopped state later on. This feature is only available for instances with Amazon EBS volume as their root device. -* `service/email`: Updates service API and documentation - * Amazon Simple Email Service (Amazon SES) now lets you customize the domains used for tracking open and click events. Previously, open and click tracking links referred to destinations hosted on domains operated by Amazon SES. With this feature, you can use your own branded domains for capturing open and click events. -* `service/iam`: Updates service API and documentation - * A new API, DeleteServiceLinkedRole, submits a service-linked role deletion request and returns a DeletionTaskId, which you can use to check the status of the deletion. - -Release v1.10.46 (2017-09-15) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add a new enum "REQUEST" to '--type ' field in the current create-authorizer API, and make "identitySource" optional. - -Release v1.10.45 (2017-09-14) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Supporting Parameter Store in environment variables for AWS CodeBuild -* `service/organizations`: Updates service documentation - * Documentation updates for AWS Organizations -* `service/servicecatalog`: Updates service API, documentation, and paginators - * This release of Service Catalog adds API support to copy products. - -Release v1.10.44 (2017-09-13) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Customers can create Life Cycle Hooks at the time of creating Auto Scaling Groups through the CreateAutoScalingGroup API -* `service/batch`: Updates service documentation and examples - * Documentation updates for batch -* `service/ec2`: Updates service API - * You are now able to create and launch EC2 x1e.32xlarge instance, a new EC2 instance in the X1 family, in us-east-1, us-west-2, eu-west-1, and ap-northeast-1. x1e.32xlarge offers 128 vCPUs, 3,904 GiB of DDR4 instance memory, high memory bandwidth, large L3 caches, and leading reliability capabilities to boost the performance and reliability of in-memory applications. -* `service/events`: Updates service API and documentation - * Exposes ConcurrentModificationException as one of the valid exceptions for PutPermission and RemovePermission operation. - -### SDK Enhancements -* `service/autoscaling`: Fix documentation for PutScalingPolicy.AutoScalingGroupName [#1522](https://github.com/aws/aws-sdk-go/pull/1522) -* `service/s3/s3manager`: Clarify S3 Upload manager Concurrency config [#1521](https://github.com/aws/aws-sdk-go/pull/1521) - * Fixes [#1458](https://github.com/aws/aws-sdk-go/issues/1458) -* `service/dynamodb/dynamodbattribute`: Add support for time alias. [#1520](https://github.com/aws/aws-sdk-go/pull/1520) - * Related to [#1505](https://github.com/aws/aws-sdk-go/pull/1505) - -Release v1.10.43 (2017-09-12) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing HostOfferingSet from being set -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.42 (2017-09-12) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * DeviceFarm has added support for two features - RemoteDebugging and Customer Artifacts. Customers can now do remote Debugging on their Private Devices and can now retrieve custom files generated by their tests on the device and the device host (execution environment) on both public and private devices. - -Release v1.10.41 (2017-09-08) -=== - -### Service Client Updates -* `service/logs`: Updates service API and documentation - * Adds support for the PutResourcePolicy, DescribeResourcePolicy and DeleteResourcePolicy APIs. - -Release v1.10.40 (2017-09-07) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service documentation -* `service/ec2`: Updates service API and documentation - * With Tagging support, you can add Key and Value metadata to search, filter and organize your NAT Gateways according to your organization's needs. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation -* `service/route53`: Updates service API and documentation - * You can configure Amazon Route 53 to log information about the DNS queries that Amazon Route 53 receives for your domains and subdomains. When you configure query logging, Amazon Route 53 starts to send logs to CloudWatch Logs. You can use various tools, including the AWS console, to access the query logs. - -Release v1.10.39 (2017-09-06) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Add an optional "thresholdType" to notifications to support percentage or absolute value thresholds. - -Release v1.10.38 (2017-09-05) -=== - -### Service Client Updates -* `service/codestar`: Updates service API and documentation - * Added support to tag CodeStar projects. Tags can be used to organize and find CodeStar projects on key-value pairs that you can choose. For example, you could add a tag with a key of "Release" and a value of "Beta" to projects your organization is working on for an upcoming beta release. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.37 (2017-09-01) -=== - -### Service Client Updates -* `service/MobileHub`: Adds new service -* `service/gamelift`: Updates service API and documentation - * GameLift VPC resources can be peered with any other AWS VPC. R4 memory-optimized instances now available to deploy. -* `service/ssm`: Updates service API and documentation - * Adding KMS encryption support to SSM Inventory Resource Data Sync. Exposes the ClientToken parameter on SSM StartAutomationExecution to provide idempotent execution requests. - -Release v1.10.36 (2017-08-31) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API, documentation, and examples - * The AWS CodeBuild HTTP API now provides the BatchDeleteBuilds operation, which enables you to delete existing builds. -* `service/ec2`: Updates service API and documentation - * Descriptions for Security Group Rules enables customers to be able to define a description for ingress and egress security group rules . The Descriptions for Security Group Rules feature supports one description field per Security Group rule for both ingress and egress rules . Descriptions for Security Group Rules provides a simple way to describe the purpose or function of a Security Group Rule allowing for easier customer identification of configuration elements . Prior to the release of Descriptions for Security Group Rules , customers had to maintain a separate system outside of AWS if they wanted to track Security Group Rule mapping and their purpose for being implemented. If a security group rule has already been created and you would like to update or change your description for that security group rule you can use the UpdateSecurityGroupRuleDescription API. -* `service/elasticloadbalancingv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lex-models`: Updates service API and documentation - -### SDK Bugs -* `aws/signer/v4`: Revert [#1491](https://github.com/aws/aws-sdk-go/issues/1491) as change conflicts with an undocumented AWS v4 signature test case. - * Related to: [#1495](https://github.com/aws/aws-sdk-go/issues/1495). -Release v1.10.35 (2017-08-30) -=== - -### Service Client Updates -* `service/application-autoscaling`: Updates service API and documentation -* `service/organizations`: Updates service API and documentation - * The exception ConstraintViolationException now contains a new reason subcode MASTERACCOUNT_MISSING_CONTACT_INFO to make it easier to understand why attempting to remove an account from an Organization can fail. We also improved several other of the text descriptions and examples. - -Release v1.10.34 (2017-08-29) -=== - -### Service Client Updates -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Provides capability to add secondary CIDR blocks to a VPC. - -### SDK Bugs -* `aws/signer/v4`: Fix Signing Unordered Multi Value Query Parameters ([#1491](https://github.com/aws/aws-sdk-go/pull/1491)) - * Removes sorting of query string values when calculating v4 signing as this is not part of the spec. The spec only requires the keys, not values, to be sorted which is achieved by Query.Encode(). -Release v1.10.33 (2017-08-25) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API and documentation - * Rollback triggers enable you to have AWS CloudFormation monitor the state of your application during stack creation and updating, and to roll back that operation if the application breaches the threshold of any of the alarms you've specified. -* `service/gamelift`: Updates service API - * Update spelling of MatchmakingTicket status values for internal consistency. -* `service/rds`: Updates service API and documentation - * Option group options now contain additional properties that identify requirements for certain options. Check these properties to determine if your DB instance must be in a VPC or have auto minor upgrade turned on before you can use an option. Check to see if you can downgrade the version of an option after you have installed it. - -### SDK Enhancements -* `example/service/ec2`: Add EC2 list instances example ([#1492](https://github.com/aws/aws-sdk-go/pull/1492)) - -Release v1.10.32 (2017-08-25) -=== - -### Service Client Updates -* `service/rekognition`: Updates service API, documentation, and examples - * Update the enum value of LandmarkType and GenderType to be consistent with service response - -Release v1.10.31 (2017-08-23) -=== - -### Service Client Updates -* `service/appstream`: Updates service documentation - * Documentation updates for appstream -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.30 (2017-08-22) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * Changes to associations in Systems Manager State Manager can now be recorded. Previously, when you edited associations, you could not go back and review older association settings. Now, associations are versioned, and can be named using human-readable strings, allowing you to see a trail of association changes. You can also perform rate-based scheduling, which allows you to schedule associations more granularly. - -Release v1.10.29 (2017-08-21) -=== - -### Service Client Updates -* `service/firehose`: Updates service API, documentation, and paginators - * This change will allow customers to attach a Firehose delivery stream to an existing Kinesis stream directly. You no longer need a forwarder to move data from a Kinesis stream to a Firehose delivery stream. You can now run your streaming applications on your Kinesis stream and easily attach a Firehose delivery stream to it for data delivery to S3, Redshift, or Elasticsearch concurrently. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports CAA resource record type. A CAA record controls which certificate authorities are allowed to issue certificates for the domain or subdomain. - -Release v1.10.28 (2017-08-18) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.27 (2017-08-16) -=== - -### Service Client Updates -* `service/gamelift`: Updates service API and documentation - * The Matchmaking Grouping Service is a new feature that groups player match requests for a given game together into game sessions based on developer configured rules. - -### SDK Enhancements -* `aws/arn`: aws/arn: Package for parsing and producing ARNs ([#1463](https://github.com/aws/aws-sdk-go/pull/1463)) - * Adds the `arn` package for AWS ARN parsing and building. Use this package to build AWS ARNs for services such as outlined in the [documentation](http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). - -### SDK Bugs -* `aws/signer/v4`: Correct V4 presign signature to include content sha25 in URL ([#1469](https://github.com/aws/aws-sdk-go/pull/1469)) - * Updates the V4 signer so that when a Presign is generated the `X-Amz-Content-Sha256` header is added to the query string instead of being required to be in the header. This allows you to generate presigned URLs for GET requests, e.g S3.GetObject that do not require additional headers to be set by the downstream users of the presigned URL. - * Related To: [#1467](https://github.com/aws/aws-sdk-go/issues/1467) - -Release v1.10.26 (2017-08-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API - * Fixed bug in EC2 clients preventing HostReservation from being set -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.10.25 (2017-08-14) -=== - -### Service Client Updates -* `service/AWS Glue`: Adds new service -* `service/batch`: Updates service API and documentation - * This release enhances the DescribeJobs API to include the CloudWatch logStreamName attribute in ContainerDetail and ContainerDetailAttempt -* `service/cloudhsmv2`: Adds new service - * CloudHSM provides hardware security modules for protecting sensitive data and cryptographic keys within an EC2 VPC, and enable the customer to maintain control over key access and use. This is a second-generation of the service that will improve security, lower cost and provide better customer usability. -* `service/elasticfilesystem`: Updates service API, documentation, and paginators - * Customers can create encrypted EFS file systems and specify a KMS master key to encrypt it with. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/mgh`: Adds new service - * AWS Migration Hub provides a single location to track migrations across multiple AWS and partner solutions. Using Migration Hub allows you to choose the AWS and partner migration tools that best fit your needs, while providing visibility into the status of your entire migration portfolio. Migration Hub also provides key metrics and progress for individual applications, regardless of which tools are being used to migrate them. For example, you might use AWS Database Migration Service, AWS Server Migration Service, and partner migration tools to migrate an application comprised of a database, virtualized web servers, and a bare metal server. Using Migration Hub will provide you with a single screen that shows the migration progress of all the resources in the application. This allows you to quickly get progress updates across all of your migrations, easily identify and troubleshoot any issues, and reduce the overall time and effort spent on your migration projects. Migration Hub is available to all AWS customers at no additional charge. You only pay for the cost of the migration tools you use, and any resources being consumed on AWS. -* `service/ssm`: Updates service API and documentation - * Systems Manager Maintenance Windows include the following changes or enhancements: New task options using Systems Manager Automation, AWS Lambda, and AWS Step Functions; enhanced ability to edit the targets of a Maintenance Window, including specifying a target name and description, and ability to edit the owner field; enhanced ability to edits tasks; enhanced support for Run Command parameters; and you can now use a --safe flag when attempting to deregister a target. If this flag is enabled when you attempt to deregister a target, the system returns an error if the target is referenced by any task. Also, Systems Manager now includes Configuration Compliance to scan your fleet of managed instances for patch compliance and configuration inconsistencies. You can collect and aggregate data from multiple AWS accounts and Regions, and then drill down into specific resources that aren't compliant. -* `service/storagegateway`: Updates service API and documentation - * Add optional field ForceDelete to DeleteFileShare api. - -Release v1.10.24 (2017-08-11) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * Adds support for specifying Application Load Balancers in deployment groups, for both in-place and blue/green deployments. -* `service/cognito-idp`: Updates service API and documentation -* `service/ec2`: Updates service API and documentation - * Provides customers an opportunity to recover an EIP that was released - -Release v1.10.23 (2017-08-10) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Enable BatchDetachPolicy -* `service/codebuild`: Updates service API - * Supporting Bitbucket as source type in AWS CodeBuild. - -Release v1.10.22 (2017-08-09) -=== - -### Service Client Updates -* `service/rds`: Updates service documentation - * Documentation updates for RDS. - -Release v1.10.21 (2017-08-09) -=== - -### Service Client Updates -* `service/elasticbeanstalk`: Updates service API and documentation - * Add support for paginating the result of DescribeEnvironments Include the ARN of described environments in DescribeEnvironments output - -### SDK Enhancements -* `aws`: Add pointer conversion utilities to transform int64 to time.Time [#1433](https://github.com/aws/aws-sdk-go/pull/1433) - * Adds `SecondsTimeValue` and `MillisecondsTimeValue` utilities. - -Release v1.10.20 (2017-08-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy now supports the use of multiple tag groups in a single deployment group (an intersection of tags) to identify the instances for a deployment. When you create or update a deployment group, use the new ec2TagSet and onPremisesTagSet structures to specify up to three groups of tags. Only instances that are identified by at least one tag in each of the tag groups are included in the deployment group. -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service waiters - * Ec2 SpotInstanceRequestFulfilled waiter update -* `service/elasticloadbalancingv2`: Updates service waiters -* `service/email`: Updates service API, documentation, paginators, and examples - * This update adds information about publishing email open and click events. This update also adds information about publishing email events to Amazon Simple Notification Service (Amazon SNS). -* `service/pinpoint`: Updates service API and documentation - * This release of the Pinpoint SDK enables App management - create, delete, update operations, Raw Content delivery for APNs and GCM campaign messages and From Address override. - -Release v1.10.19 (2017-08-01) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/inspector`: Updates service API, documentation, and paginators - * Inspector's StopAssessmentRun API has been updated with a new input option - stopAction. This request parameter can be set to either START_EVALUATION or SKIP_EVALUATION. START_EVALUATION (the default value, and the previous behavior) stops the AWS agent data collection and begins the results evaluation for findings generation based on the data collected so far. SKIP_EVALUATION cancels the assessment run immediately, after which no findings are generated. -* `service/ssm`: Updates service API and documentation - * Adds a SendAutomationSignal API to SSM Service. This API is used to send a signal to an automation execution to change the current behavior or status of the execution. - -Release v1.10.18 (2017-07-27) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * The CreateDefaultVPC API enables you to create a new default VPC . You no longer need to contact AWS support, if your default VPC has been deleted. -* `service/kinesisanalytics`: Updates service API and documentation - * Added additional exception types and clarified documentation. - -Release v1.10.17 (2017-07-27) -=== - -### Service Client Updates -* `service/dynamodb`: Updates service documentation and examples - * Corrected a typo. -* `service/ec2`: Updates service API and documentation - * Amazon EC2 Elastic GPUs allow you to easily attach low-cost graphics acceleration to current generation EC2 instances. With Amazon EC2 Elastic GPUs, you can configure the right amount of graphics acceleration to your particular workload without being constrained by fixed hardware configurations and limited GPU selection. -* `service/monitoring`: Updates service documentation - * This release adds high resolution features to CloudWatch, with support for Custom Metrics down to 1 second and Alarms down to 10 seconds. - -Release v1.10.16 (2017-07-26) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * Cloud Directory adds support for additional batch operations. -* `service/cloudformation`: Updates service API and documentation - * AWS CloudFormation StackSets enables you to manage stacks across multiple accounts and regions. - -### SDK Enhancements -* `aws/signer/v4`: Optimize V4 signer's header duplicate space stripping. [#1417](https://github.com/aws/aws-sdk-go/pull/1417) - -Release v1.10.15 (2017-07-24) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and waiters - * Amazon AppStream 2.0 image builders and fleets can now access applications and network resources that rely on Microsoft Active Directory (AD) for authentication and permissions. This new feature allows you to join your streaming instances to your AD, so you can use your existing AD user management tools. -* `service/ec2`: Updates service API and documentation - * Spot Fleet tagging capability allows customers to automatically tag instances launched by Spot Fleet. You can use this feature to label or distinguish instances created by distinct Spot Fleets. Tagging your EC2 instances also enables you to see instance cost allocation by tag in your AWS bill. - -### SDK Bugs -* `aws/signer/v4`: Fix out of bounds panic in stripExcessSpaces [#1412](https://github.com/aws/aws-sdk-go/pull/1412) - * Fixes the out of bands panic in stripExcessSpaces caused by an incorrect calculation of the stripToIdx value. Simplified to code also. - * Fixes [#1411](https://github.com/aws/aws-sdk-go/issues/1411) -Release v1.10.14 (2017-07-20) -=== - -### Service Client Updates -* `service/elasticmapreduce`: Updates service API and documentation - * Amazon EMR now includes the ability to use a custom Amazon Linux AMI and adjustable root volume size when launching a cluster. - -Release v1.10.13 (2017-07-19) -=== - -### Service Client Updates -* `service/budgets`: Updates service API and documentation - * Update budget Management API's to list/create/update RI_UTILIZATION type budget. Update budget Management API's to support DAILY timeUnit for RI_UTILIZATION type budget. - -### SDK Enhancements -* `service/s3`: Use interfaces assertions instead of ValuesAtPath for S3 field lookups. [#1401](https://github.com/aws/aws-sdk-go/pull/1401) - * Improves the performance across the board for all S3 API calls by removing the usage of `ValuesAtPath` being used for every S3 API call. - -### SDK Bugs -* `aws/request`: waiter test bug - * waiters_test.go file would sometimes fail due to travis hiccups. This occurs because a test would sometimes fail the cancel check and succeed the timeout. However, the timeout check should never occur in that test. This fix introduces a new field that dictates how waiters will sleep. -Release v1.10.12 (2017-07-17) -=== - -### Service Client Updates -* `service/cognito-idp`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - * Lambda@Edge lets you run code closer to your end users without provisioning or managing servers. With Lambda@Edge, your code runs in AWS edge locations, allowing you to respond to your end users at the lowest latency. Your code is triggered by Amazon CloudFront events, such as requests to and from origin servers and viewers, and it is ready to execute at every AWS edge location whenever a request for content is received. You just upload your Node.js code to AWS Lambda and Lambda takes care of everything required to run and scale your code with high availability. You only pay for the compute time you consume - there is no charge when your code is not running. - -Release v1.10.11 (2017-07-14) -=== - -### Service Client Updates -* `service/discovery`: Updates service API and documentation - * Adding feature to the Export API for Discovery Service to allow filters for the export task to allow export based on per agent id. -* `service/ec2`: Updates service API - * New EC2 GPU Graphics instance -* `service/marketplacecommerceanalytics`: Updates service documentation - * Update to Documentation Model For New Report Cadence / Reformat of Docs - -Release v1.10.10 (2017-07-13) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Adds support for management of gateway responses. -* `service/ec2`: Updates service API and documentation - * X-ENI (or Cross-Account ENI) is a new feature that allows the attachment or association of Elastic Network Interfaces (ENI) between VPCs in different AWS accounts located in the same availability zone. With this new capability, service providers and partners can deliver managed solutions in a variety of new architectural patterns where the provider and consumer of the service are in different AWS accounts. -* `service/lex-models`: Updates service documentation - -Release v1.10.9 (2017-07-12) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service API and documentation - * Auto Scaling now supports a new type of scaling policy called target tracking scaling policies that you can use to set up dynamic scaling for your application. -* `service/swf`: Updates service API, documentation, paginators, and examples - * Added support for attaching control data to Lambda tasks. Control data lets you attach arbitrary strings to your decisions and history events. - -Release v1.10.8 (2017-07-06) -=== - -### Service Client Updates -* `service/ds`: Updates service API, documentation, and paginators - * You can now improve the resilience and performance of your Microsoft AD directory by deploying additional domain controllers. Added UpdateNumberofDomainControllers API that allows you to update the number of domain controllers you want for your directory, and DescribeDomainControllers API that allows you to describe the detailed information of each domain controller of your directory. Also added the 'DesiredNumberOfDomainControllers' field to the DescribeDirectories API output for Microsoft AD. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/kinesis`: Updates service API and documentation - * You can now encrypt your data at rest within an Amazon Kinesis Stream using server-side encryption. Server-side encryption via AWS KMS makes it easy for customers to meet strict data management requirements by encrypting their data at rest within the Amazon Kinesis Streams, a fully managed real-time data processing service. -* `service/kms`: Updates service API and documentation - * This release of AWS Key Management Service introduces the ability to determine whether a key is AWS managed or customer managed. -* `service/ssm`: Updates service API and documentation - * Amazon EC2 Systems Manager now expands Patching support to Amazon Linux, Red Hat and Ubuntu in addition to the already supported Windows Server. - -Release v1.10.7 (2017-07-05) -=== - -### Service Client Updates -* `service/monitoring`: Updates service API and documentation - * We are excited to announce the availability of APIs and CloudFormation support for CloudWatch Dashboards. You can use the new dashboard APIs or CloudFormation templates to dynamically build and maintain dashboards to monitor your infrastructure and applications. There are four new dashboard APIs - PutDashboard, GetDashboard, DeleteDashboards, and ListDashboards APIs. PutDashboard is used to create a new dashboard or modify an existing one whereas GetDashboard is the API to get the details of a specific dashboard. ListDashboards and DeleteDashboards are used to get the names or delete multiple dashboards respectively. Getting started with dashboard APIs is similar to any other AWS APIs. The APIs can be accessed through AWS SDK or through CLI tools. -* `service/route53`: Updates service API and documentation - * Bug fix for InvalidChangeBatch exception. - -### SDK Enhancements -* `service/s3/s3manager`: adding cleanup function to batch objects [#1375](https://github.com/aws/aws-sdk-go/issues/1375) - * This enhancement will add an After field that will be called after each iteration of the batch operation. - -Release v1.10.6 (2017-06-30) -=== - -### Service Client Updates -* `service/marketplacecommerceanalytics`: Updates service documentation - * Documentation updates for AWS Marketplace Commerce Analytics. -* `service/s3`: Updates service API and documentation - * API Update for S3: Adding Object Tagging Header to MultipartUpload Initialization - -Release v1.10.5 (2017-06-29) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/events`: Updates service API and documentation - * CloudWatch Events now allows different AWS accounts to share events with each other through a new resource called event bus. Event buses accept events from AWS services, other AWS accounts and PutEvents API calls. Currently all AWS accounts have one default event bus. To send events to another account, customers simply write rules to match the events of interest and attach an event bus in the receiving account as the target to the rule. The PutTargets API has been updated to allow adding cross account event buses as targets. In addition, we have released two new APIs - PutPermission and RemovePermission - that enables customers to add/remove permissions to their default event bus. -* `service/gamelift`: Updates service API and documentation - * Allow developers to download GameLift fleet creation logs to assist with debugging. -* `service/ssm`: Updates service API and documentation - * Adding Resource Data Sync support to SSM Inventory. New APIs: * CreateResourceDataSync - creates a new resource data sync configuration, * ListResourceDataSync - lists existing resource data sync configurations, * DeleteResourceDataSync - deletes an existing resource data sync configuration. - -Release v1.10.4 (2017-06-27) -=== - -### Service Client Updates -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Proper tagging of resources is critical to post-launch operations such as billing, cost allocation, and resource management. By using Service Catalog's TagOption Library, administrators can define a library of re-usable TagOptions that conform to company standards, and associate these with Service Catalog portfolios and products. Learn how to move your current tags to the new library, create new TagOptions, and view and associate your library items with portfolios and products. Understand how to ensure that the right tags are created on products launched through Service Catalog and how to provide users with defined selectable tags. - -### SDK Bugs -* `aws/signer/v4`: checking length on `stripExcessSpaces` [#1372](https://github.com/aws/aws-sdk-go/issues/1372) - * Fixes a bug where `stripExcessSpaces` did not check length against the slice. - * Fixes: [#1371](https://github.com/aws/aws-sdk-go/issues/1371) -Release v1.10.3 (2017-06-23) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * The Lambda Invoke API will now throw new exception InvalidRuntimeException (status code 502) for invokes with deprecated runtimes. - -Release v1.10.2 (2017-06-22) -=== - -### Service Client Updates -* `service/codepipeline`: Updates service API, documentation, and paginators - * A new API, ListPipelineExecutions, enables you to retrieve summary information about the most recent executions in a pipeline, including pipeline execution ID, status, start time, and last updated time. You can request information for a maximum of 100 executions. Pipeline execution data is available for the most recent 12 months of activity. -* `service/dms`: Updates service API and documentation - * Added tagging for DMS certificates. -* `service/elasticloadbalancing`: Updates service waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lightsail`: Updates service API and documentation - * This release adds a new nextPageToken property to the result of the GetOperationsForResource API. Developers can now get the next set of items in a list by making subsequent calls to GetOperationsForResource API with the token from the previous call. This release also deprecates the nextPageCount property, which previously returned null (use the nextPageToken property instead). This release also deprecates the customImageName property on the CreateInstancesRequest class, which was previously ignored by the API. -* `service/route53`: Updates service API and documentation - * This release reintroduces the HealthCheckInUse exception. - -Release v1.10.1 (2017-06-21) -=== - -### Service Client Updates -* `service/dax`: Adds new service - * Amazon DynamoDB Accelerator (DAX) is a fully managed, highly available, in-memory cache for DynamoDB that delivers up to a 10x performance improvement - from milliseconds to microseconds - even at millions of requests per second. DAX does all the heavy lifting required to add in-memory acceleration to your DynamoDB tables, without requiring developers to manage cache invalidation, data population, or cluster management. -* `service/route53`: Updates service API and documentation - * Amazon Route 53 now supports multivalue answers in response to DNS queries, which lets you route traffic approximately randomly to multiple resources, such as web servers. Create one multivalue answer record for each resource and, optionally, associate an Amazon Route 53 health check with each record, and Amazon Route 53 responds to DNS queries with up to eight healthy records. -* `service/ssm`: Updates service API, documentation, and paginators - * Adding hierarchy support to the SSM Parameter Store API. Added support tor tagging. New APIs: GetParameter - retrieves one parameter, DeleteParameters - deletes multiple parameters (max number 10), GetParametersByPath - retrieves parameters located in the hierarchy. Updated APIs: PutParameter - added ability to enforce parameter value by applying regex (AllowedPattern), DescribeParameters - modified to support Tag filtering. -* `service/waf`: Updates service API and documentation - * You can now create, edit, update, and delete a new type of WAF rule with a rate tracking component. -* `service/waf-regional`: Updates service API and documentation - -Release v1.10.0 (2017-06-20) -=== - -### Service Client Updates -* `service/workdocs`: Updates service API and documentation - * This release provides a new API to retrieve the activities performed by WorkDocs users. - -### SDK Features -* `aws/credentials/plugincreds`: Add support for Go plugin for credentials [#1320](https://github.com/aws/aws-sdk-go/pull/1320) - * Adds support for using plugins to retrieve credentials for API requests. This change adds a new package plugincreds under aws/credentials. See the `example/aws/credentials/plugincreds` folder in the SDK for example usage. - -Release v1.9.00 (2017-06-19) -=== - -### Service Client Updates -* `service/organizations`: Updates service API and documentation - * Improvements to Exception Modeling - -### SDK Features -* `service/s3/s3manager`: Adds batch operations to s3manager [#1333](https://github.com/aws/aws-sdk-go/pull/1333) - * Allows for batch upload, download, and delete of objects. Also adds the interface pattern to allow for easy traversal of objects. E.G `DownloadWithIterator`, `UploadWithIterator`, and `BatchDelete`. `BatchDelete` also contains a utility iterator using the `ListObjects` API to easily delete a list of objects. - -Release v1.8.44 (2017-06-16) -=== - -### Service Client Updates -* `service/xray`: Updates service API, documentation, and paginators - * Add a response time histogram to the services in response of GetServiceGraph API. - -Release v1.8.43 (2017-06-15) -=== - -### Service Client Updates -* `service/ec2`: Updates service API and documentation - * Adds API to describe Amazon FPGA Images (AFIs) available to customers, which includes public AFIs, private AFIs that you own, and AFIs owned by other AWS accounts for which you have load permissions. -* `service/ecs`: Updates service API and documentation - * Added support for cpu, memory, and memory reservation container overrides on the RunTask and StartTask APIs. -* `service/iot`: Updates service API and documentation - * Revert the last release: remove CertificatePem from DescribeCertificate API. -* `service/servicecatalog`: Updates service API, documentation, and paginators - * Added ProvisioningArtifactSummaries to DescribeProductAsAdmin's output to show the provisioning artifacts belong to the product. Allow filtering by SourceProductId in SearchProductsAsAdmin for AWS Marketplace products. Added a verbose option to DescribeProvisioningArtifact to display the CloudFormation template used to create the provisioning artifact.Added DescribeProvisionedProduct API. Changed the type of ProvisionedProduct's Status to be distinct from Record's Status. New ProvisionedProduct's Status are AVAILABLE, UNDER_CHANGE, TAINTED, ERROR. Changed Record's Status set of values to CREATED, IN_PROGRESS, IN_PROGRESS_IN_ERROR, SUCCEEDED, FAILED. - -### SDK Bugs -* `private/model/api`: Fix RESTXML support for XML Namespace [#1343](https://github.com/aws/aws-sdk-go/pull/1343) - * Fixes a bug with the SDK's generation of services using the REST XML protocol not annotating shape references with the XML Namespace attribute. - * Fixes [#1334](https://github.com/aws/aws-sdk-go/pull/1334) -Release v1.8.42 (2017-06-14) -=== - -### Service Client Updates -* `service/applicationautoscaling`: Updates service API and documentation -* `service/clouddirectory`: Updates service documentation - * Documentation update for Cloud Directory - -Release v1.8.41 (2017-06-13) -=== - -### Service Client Updates -* `service/configservice`: Updates service API - -Release v1.8.40 (2017-06-13) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * API Update for RDS: this update enables copy-on-write, a new Aurora MySQL Compatible Edition feature that allows users to restore their database, and support copy of TDE enabled snapshot cross region. - -### SDK Bugs -* `aws/request`: Fix NewErrParamMinLen to use correct ParamMinLenErrCode [#1336](https://github.com/aws/aws-sdk-go/issues/1336) - * Fixes the `NewErrParamMinLen` function returning the wrong error code. `ParamMinLenErrCode` should be returned not `ParamMinValueErrCode`. - * Fixes [#1335](https://github.com/aws/aws-sdk-go/issues/1335) -Release v1.8.39 (2017-06-09) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworks`: Updates service API and documentation - * Tagging Support for AWS OpsWorks Stacks - -Release v1.8.38 (2017-06-08) -=== - -### Service Client Updates -* `service/iot`: Updates service API and documentation - * In addition to using certificate ID, AWS IoT customers can now obtain the description of a certificate with the certificate PEM. -* `service/pinpoint`: Updates service API and documentation - * Starting today Amazon Pinpoint adds SMS Text and Email Messaging support in addition to Mobile Push Notifications, providing developers, product managers and marketers with multi-channel messaging capabilities to drive user engagement in their applications. Pinpoint also enables backend services and applications to message users directly and provides advanced user and app analytics to understand user behavior and messaging performance. -* `service/rekognition`: Updates service API and documentation - * API Update for AmazonRekognition: Adding RecognizeCelebrities API - -Release v1.8.37 (2017-06-07) -=== - -### Service Client Updates -* `service/codebuild`: Updates service API and documentation - * Add support to APIs for privileged containers. This change would allow performing privileged operations like starting the Docker daemon inside builds possible in custom docker images. -* `service/greengrass`: Adds new service - * AWS Greengrass is software that lets you run local compute, messaging, and device state synchronization for connected devices in a secure way. With AWS Greengrass, connected devices can run AWS Lambda functions, keep device data in sync, and communicate with other devices securely even when not connected to the Internet. Using AWS Lambda, Greengrass ensures your IoT devices can respond quickly to local events, operate with intermittent connections, and minimize the cost of transmitting IoT data to the cloud. - -Release v1.8.36 (2017-06-06) -=== - -### Service Client Updates -* `service/acm`: Updates service documentation - * Documentation update for AWS Certificate Manager. -* `service/cloudfront`: Updates service documentation - * Doc update to fix incorrect prefix in S3OriginConfig -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/iot`: Updates service API - * Update client side validation for SalesForce action. - -Release v1.8.35 (2017-06-05) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * AppStream 2.0 Custom Security Groups allows you to easily control what network resources your streaming instances and images have access to. You can assign up to 5 security groups per Fleet to control the inbound and outbound network access to your streaming instances to specific IP ranges, network protocols, or ports. -* `service/iot`: Updates service API, documentation, paginators, and examples - * Added Salesforce action to IoT Rules Engine. - -Release v1.8.34 (2017-06-02) -=== - -### Service Client Updates -* `service/kinesisanalytics`: Updates service API, documentation, and paginators - * Kinesis Analytics publishes error messages CloudWatch logs in case of application misconfigurations -* `service/workdocs`: Updates service API and documentation - * This release includes new APIs to manage tags and custom metadata on resources and also new APIs to add and retrieve comments at the document level. - -Release v1.8.33 (2017-06-01) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * AWS CodeDeploy has improved how it manages connections to GitHub accounts and repositories. You can now create and store up to 25 connections to GitHub accounts in order to associate AWS CodeDeploy applications with GitHub repositories. Each connection can support multiple repositories. You can create connections to up to 25 different GitHub accounts, or create more than one connection to a single account. The ListGitHubAccountTokenNames command has been introduced to retrieve the names of stored connections to GitHub accounts that you have created. The name of the connection to GitHub used for an AWS CodeDeploy application is also included in the ApplicationInfo structure. Two new fields, lastAttemptedDeployment and lastSuccessfulDeployment, have been added to DeploymentGroupInfo to improve the handling of deployment group information in the AWS CodeDeploy console. Information about these latest deployments can also be retrieved using the GetDeploymentGroup and BatchGetDeployment group requests. Also includes a region update (us-gov-west-1). -* `service/cognitoidentityprovider`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lexmodelbuildingservice`: Updates service documentation and examples - -### SDK Enhancements -* `aws/defaults`: Exports shared credentials and config default filenames used by the SDK. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * Adds SharedCredentialsFilename and SharedConfigFilename functions to defaults package. - -### SDK Bugs -* `aws/credentials`: Fixes shared credential provider's default filename on Windows. [#1308](https://github.com/aws/aws-sdk-go/pull/1308) - * The shared credentials provider would attempt to use the wrong filename on Windows if the `HOME` environment variable was defined. -* `service/s3/s3manager`: service/s3/s3manager: Fix Downloader ignoring Range get parameter [#1311](https://github.com/aws/aws-sdk-go/pull/1311) - * Fixes the S3 Download Manager ignoring the GetObjectInput's Range parameter. If this parameter is provided it will force the downloader to fallback to a single GetObject request disabling concurrency and automatic part size gets. - * Fixes [#1296](https://github.com/aws/aws-sdk-go/issues/1296) -Release v1.8.32 (2017-05-31) -=== - -### Service Client Updates -* `service/rds`: Updates service API and documentation - * Amazon RDS customers can now easily and quickly stop and start their DB instances. - -Release v1.8.31 (2017-05-30) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Cloud Directory has launched support for Typed Links, enabling customers to create object-to-object relationships that are not hierarchical in nature. Typed Links enable customers to quickly query for data along these relationships. Customers can also enforce referential integrity using Typed Links, ensuring data in use is not inadvertently deleted. -* `service/s3`: Updates service paginators and examples - * New example snippets for Amazon S3. - -Release v1.8.30 (2017-05-25) -=== - -### Service Client Updates -* `service/appstream`: Updates service API and documentation - * Support added for persistent user storage, backed by S3. -* `service/rekognition`: Updates service API and documentation - * Updated the CompareFaces API response to include orientation information, unmatched faces, landmarks, pose, and quality of the compared faces. - -Release v1.8.29 (2017-05-24) -=== - -### Service Client Updates -* `service/iam`: Updates service API - * The unique ID and access key lengths were extended from 32 to 128 -* `service/storagegateway`: Updates service API and documentation - * Two Storage Gateway data types, Tape and TapeArchive, each have a new response element, TapeUsedInBytes. This element helps you manage your virtual tapes. By using TapeUsedInBytes, you can see the amount of data written to each virtual tape. -* `service/sts`: Updates service API, documentation, and paginators - * The unique ID and access key lengths were extended from 32 to 128. - -Release v1.8.28 (2017-05-23) -=== - -### Service Client Updates -* `service/databasemigrationservice`: Updates service API, documentation, paginators, and examples - * This release adds support for using Amazon S3 and Amazon DynamoDB as targets for database migration, and using MongoDB as a source for database migration. For more information, see the AWS Database Migration Service documentation. - -Release v1.8.27 (2017-05-22) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Updates service API, documentation, and paginators - * You can now specify the number of resources returned per page in GetResources operation, as an optional parameter, to easily manage the list of resources returned by your queries. - -### SDK Bugs -* `aws/request`: Add support for PUT temporary redirects (307) [#1283](https://github.com/aws/aws-sdk-go/issues/1283) - * Adds support for Go 1.8's GetBody function allowing the SDK's http request using PUT and POST methods to be redirected with temporary redirects with 307 status code. - * Fixes: [#1267](https://github.com/aws/aws-sdk-go/issues/1267) -* `aws/request`: Add handling for retrying temporary errors during unmarshal [#1289](https://github.com/aws/aws-sdk-go/issues/1289) - * Adds support for retrying temporary errors that occur during unmarshaling of a request's response body. - * Fixes: [#1275](https://github.com/aws/aws-sdk-go/issues/1275) -Release v1.8.26 (2017-05-18) -=== - -### Service Client Updates -* `service/athena`: Adds new service - * This release adds support for Amazon Athena. Amazon Athena is an interactive query service that makes it easy to analyze data in Amazon S3 using standard SQL. Athena is serverless, so there is no infrastructure to manage, and you pay only for the queries that you run. -* `service/lightsail`: Updates service API, documentation, and paginators - * This release adds new APIs that make it easier to set network port configurations on Lightsail instances. Developers can now make a single request to both open and close public ports on an instance using the PutInstancePublicPorts operation. - -### SDK Bugs -* `aws/request`: Fix logging from reporting wrong retry request errors #1281 - * Fixes the SDK's retry request logging to report the the actual error that occurred, not a stubbed Unknown error message. - * Fixes the SDK's response logger to not output the response log multiple times per retry. -Release v1.8.25 (2017-05-17) -=== - -### Service Client Updates -* `service/autoscaling`: Updates service documentation, paginators, and examples - * Various Auto Scaling documentation updates -* `service/cloudwatchevents`: Updates service documentation - * Various CloudWatch Events documentation updates. -* `service/cloudwatchlogs`: Updates service documentation and paginators - * Various CloudWatch Logs documentation updates. -* `service/polly`: Updates service API - * Amazon Polly adds new German voice "Vicki" - -Release v1.8.24 (2017-05-16) -=== - -### Service Client Updates -* `service/codedeploy`: Updates service API and documentation - * This release introduces the previousRevision field in the responses to the GetDeployment and BatchGetDeployments actions. previousRevision provides information about the application revision that was deployed to the deployment group before the most recent successful deployment. Also, the fileExistsBehavior parameter has been added for CreateDeployment action requests. In the past, if the AWS CodeDeploy agent detected files in a target location that weren't part of the application revision from the most recent successful deployment, it would fail the current deployment by default. This new parameter provides options for how the agent handles these files: fail the deployment, retain the content, or overwrite the content. -* `service/gamelift`: Updates service API and documentation - * Allow developers to specify how metrics are grouped in CloudWatch for their GameLift fleets. Developers can also specify how many concurrent game sessions activate on a per-instance basis. -* `service/inspector`: Updates service API, documentation, paginators, and examples - * Adds ability to produce an assessment report that includes detailed and comprehensive results of a specified assessment run. -* `service/kms`: Updates service documentation - * Update documentation for KMS. - -Release v1.8.23 (2017-05-15) -=== - -### Service Client Updates -* `service/ssm`: Updates service API and documentation - * UpdateAssociation API now supports updating document name and targets of an association. GetAutomationExecution API can return FailureDetails as an optional field to the StepExecution Object, which contains failure type, failure stage as well as other failure related information for a failed step. - -### SDK Enhancements -* `aws/session`: SDK should be able to load multiple custom shared config files. [#1258](https://github.com/aws/aws-sdk-go/issues/1258) - * This change adds a `SharedConfigFiles` field to the `session.Options` type that allows you to specify the files, and their order, the SDK will use for loading shared configuration and credentials from when the `Session` is created. Use the `NewSessionWithOptions` Session constructor to specify these options. You'll also most likely want to enable support for the shared configuration file's additional attributes by setting `session.Option`'s `SharedConfigState` to `session.SharedConfigEnabled`. - -Release v1.8.22 (2017-05-11) -=== - -### Service Client Updates -* `service/elb`: Updates service API, documentation, and paginators -* `service/elbv2`: Updates service API and documentation -* `service/lexmodelbuildingservice`: Updates service API and documentation -* `service/organizations`: Updates service API, documentation, paginators, and examples - * AWS Organizations APIs that return an Account object now include the email address associated with the account’s root user. - -Release v1.8.21 (2017-05-09) -=== - -### Service Client Updates -* `service/codestar`: Updates service documentation - * Updated documentation for AWS CodeStar. -* `service/workspaces`: Updates service API, documentation, and paginators - * Doc-only Update for WorkSpaces - -Release v1.8.20 (2017-05-04) -=== - -### Service Client Updates -* `service/ecs`: Updates service API, documentation, and paginators - * Exposes container instance registration time in ECS:DescribeContainerInstances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/marketplaceentitlementservice`: Adds new service -* `service/lambda`: Updates service API and documentation - * Support for UpdateFunctionCode DryRun option - -Release v1.8.19 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding back the removed waiters and paginators. - -Release v1.8.18 (2017-04-28) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service API, documentation, waiters, paginators, and examples - * API update for CloudFormation: New optional parameter ClientRequestToken which can be used as an idempotency token to safely retry certain operations as well as tagging StackEvents. -* `service/rds`: Updates service API, documentation, and examples - * The DescribeDBClusterSnapshots API now returns a SourceDBClusterSnapshotArn field which identifies the source DB cluster snapshot of a copied snapshot. -* `service/rekognition`: Updates service API - * Fix for missing file type check -* `service/snowball`: Updates service API, documentation, and paginators - * The Snowball API has a new exception that can be thrown for list operation requests. -* `service/sqs`: Updates service API, documentation, and paginators - * Adding server-side encryption (SSE) support to SQS by integrating with AWS KMS; adding new queue attributes to SQS CreateQueue, SetQueueAttributes and GetQueueAttributes APIs to support SSE. - -Release v1.8.17 (2017-04-26) -=== - -### Service Client Updates -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * With Amazon Relational Database Service (Amazon RDS) running MySQL or Amazon Aurora, you can now authenticate to your DB instance using IAM database authentication. - -Release v1.8.16 (2017-04-21) -=== - -### Service Client Updates -* `service/appstream`: Updates service API, documentation, and paginators - * The new feature named "Default Internet Access" will enable Internet access from AppStream 2.0 instances - image builders and fleet instances. Admins will check a flag either through AWS management console for AppStream 2.0 or through API while creating an image builder or while creating/updating a fleet. -* `service/kinesis`: Updates service API, documentation, waiters, and paginators - * Adds a new waiter, StreamNotExists, to Kinesis. - -### SDK Enhancements -* `aws/endpoints`: Add utilities improving endpoints lookup (#1218) - * Adds several utilities to the endpoints packages to make looking up partitions, regions, and services easier. - * Fixes #994 - -### SDK Bugs -* `private/protocol/xml/xmlutil`: Fix unmarshaling dropping errors (#1219) - * The XML unmarshaler would drop any serialization or body read error that occurred on the floor effectively hiding any errors that would occur. - * Fixes #1205 - -Release v1.8.15 (2017-04-20) -=== - -### Service Client Updates -* `service/devicefarm`: Updates service API and documentation - * API Update for AWS Device Farm: Support for Deals and Promotions -* `service/directconnect`: Updates service documentation - * Documentation updates for AWS Direct Connect. -* `service/elbv2`: Updates service waiters -* `service/kms`: Updates service documentation and examples - * Doc-only update for Key Management Service (KMS): Update docs for GrantConstraints and GenerateRandom -* `service/route53`: Updates service documentation - * Release notes: SDK documentation now includes examples for ChangeResourceRecordSets for all types of resource record set, such as weighted, alias, and failover. -* `service/route53domains`: Updates service API, documentation, and paginators - * Adding examples and other documentation updates. - -### SDK Enhancements -* `service/s3`: Add utilities to make getting a bucket's region easier (#1207) - * Adds two features which make it easier to get a bucket's region, `s3.NormalizeBucketLocation` and `s3manager.GetBucketRegion`. - -### SDK Bugs -* `service/s3`: Fix HeadObject's incorrect documented error codes (#1213) - * The HeadObject's model incorrectly states that the operation can return the NoSuchKey error code. - * Fixes #1208 - -Release v1.8.14 (2017-04-19) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * Add support for "embed" property. -* `service/codestar`: Adds new service - * AWS CodeStar is a cloud-based service for creating, managing, and working with software development projects on AWS. An AWS CodeStar project creates and integrates AWS services for your project development toolchain. AWS CodeStar also manages the permissions required for project users. -* `service/ec2`: Updates service API and documentation - * Adds support for creating an Amazon FPGA Image (AFI) from a specified design checkpoint (DCP). -* `service/iam`: Updates service API and documentation - * This changes introduces a new IAM role type, Service Linked Role, which works like a normal role but must be managed via services' control. -* `service/lambda`: Updates service API and documentation - * Lambda integration with CloudDebugger service to enable customers to enable tracing for the Lambda functions and send trace information to the CloudDebugger service. -* `service/lexmodelbuildingservice`: Adds new service -* `service/polly`: Updates service API, documentation, and paginators - * API Update for Amazon Polly: Add support for speech marks -* `service/rekognition`: Updates service API and documentation - * Given an image, the API detects explicit or suggestive adult content in the image and returns a list of corresponding labels with confidence scores, as well as a taxonomy (parent-child relation) for each label. - -Release v1.8.13 (2017-04-18) -=== - -### Service Client Updates -* `service/lambda`: Updates service API and documentation - * You can use tags to group and filter your Lambda functions, making it easier to analyze them for billing allocation purposes. For more information, see Tagging Lambda Functions. You can now write or upgrade your Lambda functions using Python version 3.6. For more information, see Programming Model for Authoring Lambda Functions in Python. Note: Features will be rolled out in the US regions on 4/19. - -### SDK Enhancements -* `aws/request`: add support for appengine's custom standard library (#1190) - * Remove syscall error checking on appengine platforms. - -Release v1.8.12 (2017-04-11) -=== - -### Service Client Updates -* `service/apigateway`: Updates service API and documentation - * API Gateway request validators -* `service/batch`: Updates service API and documentation - * API Update for AWS Batch: Customer provided AMI for MANAGED Compute Environment -* `service/gamelift`: Updates service API and documentation - * Allows developers to utilize an improved workflow when calling our Queues API and introduces a new feature that allows developers to specify a maximum allowable latency per Queue. -* `service/opsworks`: Updates service API, documentation, and paginators - * Cloudwatch Logs agent configuration can now be attached to OpsWorks Layers using CreateLayer and UpdateLayer. OpsWorks will then automatically install and manage the CloudWatch Logs agent on the instances part of the OpsWorks Layer. - -### SDK Bugs -* `aws/client`: Fix clients polluting handler list (#1197) - * Fixes the clients potentially polluting the passed in handler list with the client's customizations. This change ensures every client always works with a clean copy of the request handlers and it cannot pollute the handlers back upstream. - * Fixes #1184 -* `aws/request`: Fix waiter error match condition (#1195) - * Fixes the waiters's matching overwriting the request's err, effectively ignoring the error condition. This broke waiters with the FailureWaiterState matcher state. -Release v1.8.11 (2017-04-07) -=== - -### Service Client Updates -* `service/redshift`: Updates service API, documentation, and paginators - * This update adds the GetClusterCredentials API which is used to get temporary login credentials to the cluster. AccountWithRestoreAccess now has a new member AccountAlias, this is the identifier of the AWS support account authorized to restore the specified snapshot. This is added to support the feature where the customer can share their snapshot with the Amazon Redshift Support Account without having to manually specify the AWS Redshift Service account ID on the AWS Console/API. - -Release v1.8.10 (2017-04-06) -=== - -### Service Client Updates -* `service/elbv2`: Updates service documentation - -Release v1.8.9 (2017-04-05) -=== - -### Service Client Updates -* `service/elasticache`: Updates service API, documentation, paginators, and examples - * ElastiCache added support for testing the Elasticache Multi-AZ feature with Automatic Failover. - -Release v1.8.8 (2017-04-04) -=== - -### Service Client Updates -* `service/cloudwatch`: Updates service API, documentation, and paginators - * Amazon Web Services announced the immediate availability of two additional alarm configuration rules for Amazon CloudWatch Alarms. The first rule is for configuring missing data treatment. Customers have the options to treat missing data as alarm threshold breached, alarm threshold not breached, maintain alarm state and the current default treatment. The second rule is for alarms based on percentiles metrics that can trigger unnecassarily if the percentile is calculated from a small number of samples. The new rule can treat percentiles with low sample counts as same as missing data. If the first rule is enabled, the same treatment will be applied when an alarm encounters a percentile with low sample counts. - -Release v1.8.7 (2017-04-03) -=== - -### Service Client Updates -* `service/lexruntimeservice`: Updates service API and documentation - * Adds support to PostContent for speech input - -### SDK Enhancements -* `aws/request`: Improve handler copy, push back, push front performance (#1171) - * Minor optimization to the handler list's handling of copying and pushing request handlers to the handler list. -* Update codegen header to use Go std wording (#1172) - * Go recently accepted the proposal for standard generated file header wording in, https://golang.org/s/generatedcode. - -### SDK Bugs -* `service/dynamodb`: Fix DynamoDB using custom retryer (#1170) - * Fixes (#1139) the DynamoDB service client clobbering any custom retryer that was passed into the service client or Session's config. -Release v1.8.6 (2017-04-01) -=== - -### Service Client Updates -* `service/clouddirectory`: Updates service API and documentation - * ListObjectAttributes now supports filtering by facet. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.8.5 (2017-03-30) -=== - -### Service Client Updates -* `service/cloudformation`: Updates service waiters and paginators - * Adding paginators for ListExports and ListImports -* `service/cloudfront`: Adds new service - * Amazon CloudFront now supports user configurable HTTP Read and Keep-Alive Idle Timeouts for your Custom Origin Servers -* `service/configservice`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/resourcegroupstaggingapi`: Adds new service -* `service/storagegateway`: Updates service API and documentation - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. Once a file share is created, any changes made externally to the S3 bucket will not be reflected by the gateway. Using the cache refresh feature in this update, the customer can trigger an on-demand scan of the keys in their S3 bucket and refresh the file namespace cached on the gateway. It takes as an input the fileShare ARN and refreshes the cache for only that file share. Additionally there is new functionality on file gateway that allows you configure what squash options they would like on their file share, this allows a customer to configure their gateway to not squash root permissions. This can be done by setting options in NfsOptions for CreateNfsFileShare and UpdateNfsFileShare APIs. - -Release v1.8.4 (2017-03-28) -=== - -### Service Client Updates -* `service/batch`: Updates service API, documentation, and paginators - * Customers can now provide a retryStrategy as part of the RegisterJobDefinition and SubmitJob API calls. The retryStrategy object has a number value for attempts. This is the number of non successful executions before a job is considered FAILED. In addition, the JobDetail object now has an attempts field and shows all execution attempts. -* `service/ec2`: Updates service API and documentation - * Customers can now tag their Amazon EC2 Instances and Amazon EBS Volumes at - the time of their creation. You can do this from the EC2 Instance launch - wizard or through the RunInstances or CreateVolume APIs. By tagging - resources at the time of creation, you can eliminate the need to run custom - tagging scripts after resource creation. In addition, you can now set - resource-level permissions on the CreateVolume, CreateTags, DeleteTags, and - the RunInstances APIs. This allows you to implement stronger security - policies by giving you more granular control over which users and groups - have access to these APIs. You can also enforce the use of tagging and - control what tag keys and values are set on your resources. When you combine - tag usage and resource-level IAM policies together, you can ensure your - instances and volumes are properly secured upon creation and achieve more - accurate cost allocation reporting. These new features are provided at no - additional cost. - -### SDK Enhancements -* `aws/request`: Add retry support for RequestTimeoutException (#1158) - * Adds support for retrying RequestTimeoutException error code that is returned by some services. - -### SDK Bugs -* `private/model/api`: Fix Waiter and Paginators panic on nil param inputs (#1157) - * Corrects the code generation for Paginators and waiters that caused a panic if nil input parameters were used with the operations. -Release v1.8.3 (2017-03-27) -=== - -## Service Client Updates -* `service/ssm`: Updates service API, documentation, and paginators - * Updated validation rules for SendCommand and RegisterTaskWithMaintenanceWindow APIs. -Release v1.8.2 (2017-03-24) -=== - -Service Client Updates ---- -* `service/applicationautoscaling`: Updates service API, documentation, and paginators - * Application AutoScaling is launching support for a new target resource (AppStream 2.0 Fleets) as a scalable target. -* `service/cloudtrail`: Updates service API and documentation - * Doc-only Update for CloudTrail: Add required parameters for GetEventSelectors and PutEventSelectors - -Release v1.8.1 (2017-03-23) -=== - -Service Client Updates ---- -* `service/applicationdiscoveryservice`: Updates service API, documentation, and paginators - * Adds export configuration options to the AWS Discovery Service API. -* `service/elbv2`: Updates waiters -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/lambda`: Updates service API and paginators - * Adds support for new runtime Node.js v6.10 for AWS Lambda service - -Release v1.8.0 (2017-03-22) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation -* `service/directconnect`: Updates service API - * Deprecated DescribeConnectionLoa, DescribeInterconnectLoa, AllocateConnectionOnInterconnect and DescribeConnectionsOnInterconnect operations in favor of DescribeLoa, DescribeLoa, AllocateHostedConnection and DescribeHostedConnections respectively. -* `service/marketplacecommerceanalytics`: Updates service API, documentation, and paginators - * This update adds a new data set, us_sales_and_use_tax_records, which enables AWS Marketplace sellers to programmatically access to their U.S. Sales and Use Tax report data. -* `service/pinpoint`: Updates service API and documentation - * Amazon Pinpoint User Segmentation - * Added ability to segment endpoints by user attributes in addition to endpoint attributes. Amazon Pinpoint Event Stream Preview - * Added functionality to publish raw app analytics and campaign events data as events streams to Kinesis and Kinesis Firehose - * The feature provides developers with increased flexibility of exporting raw events to S3, Redshift, Elasticsearch using a Kinesis Firehose stream or enable real time event processing use cases using a Kinesis stream -* `service/rekognition`: Updates service documentation. - -SDK Features ---- -* `aws/request`: Add support for context.Context to SDK API operation requests (#1132) - * Adds support for context.Context to the SDK by adding `WithContext` methods for each API operation, Paginators and Waiters. e.g `PutObjectWithContext`. This change also adds the ability to provide request functional options to the method calls instead of requiring you to use the `Request` API operation method (e.g `PutObjectRequest`). - * Adds a `Complete` Request handler list that will be called ever time a request is completed. This includes both success and failure. Complete will only be called once per API operation request. - * `private/waiter` package moved from the private group to `aws/request/waiter` and made publicly available. - * Adds Context support to all API operations, Waiters(WaitUntil) and Paginators(Pages) methods. - * Adds Context support for s3manager and s3crypto clients. - -SDK Enhancements ---- -* `aws/signer/v4`: Adds support for unsigned payload signer config (#1130) - * Adds configuration option to the v4.Signer to specify the request's body should not be signed. This will only correclty function on services that support unsigned payload. e.g. S3, Glacier. - -SDK Bug Fixes ---- -* `service/s3`: Fix S3 HostID to be available in S3 request error message (#1131) - * Adds a new type s3.RequestFailure which exposes the S3 HostID value from a S3 API operation response. This is helpful when you have an error with S3, and need to contact support. Both RequestID and HostID are needed. -* `private/model/api`: Do not return a link if uid is empty (#1133) - * Fixes SDK's doc generation to not generate API reference doc links if the SDK us unable to create a valid link. -* `aws/request`: Optimization to handler list copy to prevent multiple alloc calls. (#1134) -Release v1.7.9 (2017-03-13) -=== - -Service Client Updates ---- -* `service/devicefarm`: Updates service API, documentation, paginators, and examples - * Network shaping allows users to simulate network connections and conditions while testing their Android, iOS, and web apps with AWS Device Farm. -* `service/cloudwatchevents`: Updates service API, documentation, and examples - -SDK Enhancement -=== -* `aws/session`: Add support for side loaded CA bundles (#1117) - * Adds supports for side loading Certificate Authority bundle files to the SDK using AWS_CA_BUNDLE environment variable or CustomCABundle session option. -* `service/s3/s3crypto`: Add support for AES/CBC/PKCS5Padding (#1124) - -SDK Bug -=== -* `service/rds`: Fixing issue when not providing `SourceRegion` on cross -region operations (#1127) -* `service/rds`: Enables cross region for `CopyDBClusterSnapshot` and -`CreateDBCluster` (#1128) - -Release v1.7.8 (2017-03-10) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service paginators - * Add paginators for Codedeploy -* `service/emr`: Updates service API, documentation, and paginators - * This release includes support for instance fleets in Amazon EMR. - -Release v1.7.7 (2017-03-09) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API, documentation, and paginators - * API Gateway has added support for ACM certificates on custom domain names. Both Amazon-issued certificates and uploaded third-part certificates are supported. -* `service/clouddirectory`: Updates service API, documentation, and paginators - * Introduces a new Cloud Directory API that enables you to retrieve all available parent paths for any type of object (a node, leaf node, policy node, and index node) in a hierarchy. - -Release v1.7.6 (2017-03-09) -=== - -Service Client Updates ---- -* `service/organizations`: Updates service documentation and examples - * Doc-only Update for Organizations: Add SDK Code Snippets -* `service/workdocs`: Adds new service - * The Administrative SDKs for Amazon WorkDocs provides full administrator level access to WorkDocs site resources, allowing developers to integrate their applications to manage WorkDocs users, content and permissions programmatically - -Release v1.7.5 (2017-03-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Add support to using encrypted clusters as cross-region replication masters. Update CopyDBClusterSnapshot API to support encrypted cross region copy of Aurora cluster snapshots. - -Release v1.7.4 (2017-03-06) -=== - -Service Client Updates ---- -* `service/budgets`: Updates service API and paginators - * When creating or editing a budget via the AWS Budgets API you can define notifications that are sent to subscribers when the actual or forecasted value for cost or usage exceeds the notificationThreshold associated with the budget notification object. Starting today, the maximum allowed value for the notificationThreshold was raised from 100 to 300. This change was made to give you more flexibility when setting budget notifications. -* `service/cloudtrail`: Updates service documentation and paginators - * Doc-only update for AWSCloudTrail: Updated links/descriptions -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/opsworkscm`: Updates service API, documentation, and paginators - * OpsWorks for Chef Automate has added a new field "AssociatePublicIpAddress" to the CreateServer request, "CloudFormationStackArn" to the Server model and "TERMINATED" server state. - - -Release v1.7.3 (2017-02-28) -=== - -Service Client Updates ---- -* `service/mturk`: Renaming service - * service/mechanicalturkrequesterservice was renamed to service/mturk. Be sure to change any references of the old client to the new. - -Release v1.7.2 (2017-02-28) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API and documentation - * Release notes: Time to Live (TTL) is a feature that allows you to define when items in a table expire and can be purged from the database, so that you don't have to track expired data and delete it manually. With TTL enabled on a DynamoDB table, you can set a timestamp for deletion on a per-item basis, allowing you to limit storage usage to only those records that are relevant. -* `service/iam`: Updates service API, documentation, and paginators - * This release adds support for AWS Organizations service control policies (SCPs) to SimulatePrincipalPolicy operation. If there are SCPs associated with the simulated user's account, their effect on the result is captured in the OrganizationDecisionDetail element in the EvaluationResult. -* `service/mechanicalturkrequesterservice`: Adds new service - * Amazon Mechanical Turk is a web service that provides an on-demand, scalable, human workforce to complete jobs that humans can do better than computers, for example, recognizing objects in photos. -* `service/organizations`: Adds new service - * AWS Organizations is a web service that enables you to consolidate your multiple AWS accounts into an organization and centrally manage your accounts and their resources. -* `service/dynamodbstreams`: Updates service API, documentation, and paginators -* `service/waf`: Updates service API, documentation, and paginators - * Aws WAF - For GetSampledRequests action, changed max number of samples from 100 to 500. -* `service/wafregional`: Updates service API, documentation, and paginators - -Release v1.7.1 (2017-02-24) -=== - -Service Client Updates ---- -* `service/elasticsearchservice`: Updates service API, documentation, paginators, and examples - * Added three new API calls to existing Amazon Elasticsearch service to expose Amazon Elasticsearch imposed limits to customers. - -Release v1.7.0 (2017-02-23) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API - * New EC2 I3 instance type - -SDK Bug ---- -* `service/s3/s3manager`: Adding support for SSE (#1097) - * Fixes SSE fields not being applied to a part during multi part upload. - -SDK Feature ---- -* `aws/session`: Add support for AssumeRoles with MFA (#1088) - * Adds support for assuming IAM roles with MFA enabled. A TokenProvider func was added to stscreds.AssumeRoleProvider that will be called each time the role's credentials need to be refreshed. A basic token provider that sources the MFA token from stdin as stscreds.StdinTokenProvider. -* `aws/session`: Update SDK examples and docs to use session.Must (#1099) - * Updates the SDK's example and docs to use session.Must where possible to highlight its usage as apposed to session error checking that is most cases errors will be terminal to the application anyways. -Release v1.6.27 (2017-02-22) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Updates service documentation - * ListObjectAttributes documentation updated based on forum feedback -* `service/elasticbeanstalk`: Updates service API, documentation, and paginators - * Elastic Beanstalk adds support for creating and managing custom platform. -* `service/gamelift`: Updates service API, documentation, and paginators - * Allow developers to configure global queues for creating GameSessions. Allow PlayerData on PlayerSessions to store player-specific data. -* `service/route53`: Updates service API, documentation, and examples - * Added support for operations CreateVPCAssociationAuthorization and DeleteVPCAssociationAuthorization to throw a ConcurrentModification error when a conflicting modification occurs in parallel to the authorizations in place for a given hosted zone. - -Release v1.6.26 (2017-02-21) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * Added the billingProduct parameter to the RegisterImage API. - -Release v1.6.25 (2017-02-17) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API, documentation, and paginators - * This update will introduce the ability for Direct Connect customers to take advantage of Link Aggregation (LAG). This allows you to bundle many individual physical interfaces into a single logical interface, referred to as a LAG. This makes administration much simpler as the majority of configuration is done on the LAG while you are free to add or remove physical interfaces from the bundle as bandwidth demand increases or decreases. A concrete example of the simplification added by LAG is that customers need only a single BGP session as opposed to one session per physical connection. - -Release v1.6.24 (2017-02-16) -=== - -Service Client Updates ---- -* `service/cognitoidentity`: Updates service API, documentation, and paginators - * Allow createIdentityPool and updateIdentityPool API to set server side token check value on identity pool -* `service/configservice`: Updates service API and documentation - * AWS Config now supports a new test mode for the PutEvaluations API. Set the TestMode parameter to true in your custom rule to verify whether your AWS Lambda function will deliver evaluation results to AWS Config. No updates occur to your existing evaluations, and evaluation results are not sent to AWS Config. - -Release v1.6.23 (2017-02-15) -=== - -Service Client Updates ---- -* `service/kms`: Updates service API, documentation, paginators, and examples - * his release of AWS Key Management Service introduces the ability to tag keys. Tagging keys can help you organize your keys and track your KMS costs in the cost allocation report. This release also increases the maximum length of a key ID to accommodate ARNs that include a long key alias. - -Release v1.6.22 (2017-02-14) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Adds support for the new Modify Volumes apis. - -Release v1.6.21 (2017-02-11) -=== - -Service Client Updates ---- -* `service/storagegateway`: Updates service API, documentation, and paginators - * File gateway mode in AWS Storage gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. This is done by creating Nfs file shares using existing APIs CreateNfsFileShare. Using the feature in this update, the customer can restrict the clients that have read/write access to the gateway by specifying the list of clients as a list of IP addresses or CIDR blocks. This list can be specified using the API CreateNfsFileShare while creating new file shares, or UpdateNfsFileShare while update existing file shares. To find out the list of clients that have access, the existing API DescribeNfsFileShare will now output the list of clients that have access. - -Release v1.6.20 (2017-02-09) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API and documentation - * This feature allows customers to associate an IAM profile to running instances that do not have any. -* `service/rekognition`: Updates service API and documentation - * DetectFaces and IndexFaces operations now return an estimate of the age of the face as an age range. - -SDK Features ---- -* `aws/endpoints`: Add option to resolve unknown endpoints (#1074) -Release v1.6.19 (2017-02-08) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service examples - * Doc Update -* `service/lexruntimeservice`: Adds new service - * Preview release - -SDK Bug Fixes ---- -* `private/protocol/json`: Fixes json to throw an error if a float number is (+/-)Inf and NaN (#1068) -* `private/model/api`: Fix documentation error listing (#1067) - -SDK Features ---- -* `private/model`: Add service response error code generation (#1061) - -Release v1.6.18 (2017-01-27) -=== - -Service Client Updates ---- -* `service/clouddirectory`: Adds new service - * Amazon Cloud Directory is a highly scalable, high performance, multi-tenant directory service in the cloud. Its web-based directories make it easy for you to organize and manage application resources such as users, groups, locations, devices, policies, and the rich relationships between them. -* `service/codedeploy`: Updates service API, documentation, and paginators - * This release of AWS CodeDeploy introduces support for blue/green deployments. In a blue/green deployment, the current set of instances in a deployment group is replaced by new instances that have the latest application revision installed on them. After traffic is rerouted behind a load balancer to the replacement instances, the original instances can be terminated automatically or kept running for other uses. -* `service/ec2`: Updates service API and documentation - * Adds instance health check functionality to replace unhealthy EC2 Spot fleet instances with fresh ones. -* `service/rds`: Updates service API and documentation - * Snapshot Engine Version Upgrade - -Release v1.6.17 (2017-01-25) -=== - -Service Client Updates ---- -* `service/elbv2`: Updates service API, documentation, and paginators - * Application Load Balancers now support native Internet Protocol version 6 (IPv6) in an Amazon Virtual Private Cloud (VPC). With this ability, clients can now connect to the Application Load Balancer in a dual-stack mode via either IPv4 or IPv6. -* `service/rds`: Updates service API and documentation - * Cross Region Read Replica Copying (CreateDBInstanceReadReplica) - -Release v1.6.16 (2017-01-24) -=== - -Service Client Updates ---- -* `service/codebuild`: Updates service documentation and paginators - * Documentation updates -* `service/codecommit`: Updates service API, documentation, and paginators - * AWS CodeCommit now includes the option to view the differences between a commit and its parent commit from within the console. You can view the differences inline (Unified view) or side by side (Split view). To view information about the differences between a commit and something other than its parent, you can use the AWS CLI and the get-differences and get-blob commands, or you can use the GetDifferences and GetBlob APIs. -* `service/ecs`: Updates service API and documentation - * Amazon ECS now supports a state for container instances that can be used to drain a container instance in preparation for maintenance or cluster scale down. - -Release v1.6.15 (2017-01-20) -=== - -Service Client Updates ---- -* `service/acm`: Updates service API, documentation, and paginators - * Update for AWS Certificate Manager: Updated response elements for DescribeCertificate API in support of managed renewal -* `service/health`: Updates service documentation - -Release v1.6.14 (2017-01-19) -=== - -Service Client Updates ---- -* `service/ec2`: Updates service API, documentation, and paginators - * Amazon EC2 Spot instances now support dedicated tenancy, providing the ability to run Spot instances single-tenant manner on physically isolated hardware within a VPC to satisfy security, privacy, or other compliance requirements. Dedicated Spot instances can be requested using RequestSpotInstances and RequestSpotFleet. - -Release v1.6.13 (2017-01-18) -=== - -Service Client Updates ---- -* `service/rds`: Updates service API, documentation, and paginators - -Release v1.6.12 (2017-01-17) -=== - -Service Client Updates ---- -* `service/dynamodb`: Updates service API, documentation, and paginators - * Tagging Support for Amazon DynamoDB Tables and Indexes -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/glacier`: Updates service API, paginators, and examples - * Doc-only Update for Glacier: Added code snippets -* `service/polly`: Updates service documentation and examples - * Doc-only update for Amazon Polly -- added snippets -* `service/rekognition`: Updates service documentation and paginators - * Added code samples to Rekognition reference topics. -* `service/route53`: Updates service API and paginators - * Add ca-central-1 and eu-west-2 enum values to CloudWatchRegion enum - -Release v1.6.11 (2017-01-16) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API, documentation, and paginators -* `service/costandusagereportservice`: Adds new service - * The AWS Cost and Usage Report Service API allows you to enable and disable the Cost & Usage report, as well as modify the report name, the data granularity, and the delivery preferences. -* `service/dynamodb`: Updates service API, documentation, and examples - * Snippets for the DynamoDB API. -* `service/elasticache`: Updates service API, documentation, and examples - * Adds new code examples. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.10 (2017-01-04) -=== - -Service Client Updates ---- -* `service/configservice`: Updates service API and documentation - * AWSConfig is planning to add support for OversizedConfigurationItemChangeNotification message type in putConfigRule. After this release customers can use/write rules based on OversizedConfigurationItemChangeNotification mesage type. -* `service/efs`: Updates service API, documentation, and examples - * Doc-only Update for EFS: Added code snippets -* `service/iam`: Updates service documentation and examples -* `service/lambda`: Updates service documentation and examples - * Doc only updates for Lambda: Added code snippets -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Added support for data set disbursed_amount_by_instance_hours, with historical data available starting 2012-09-04. New data is published to this data set every 30 days. -* `service/rds`: Updates service documentation - * Updated documentation for CopyDBSnapshot. -* `service/rekognition`: Updates service documentation and examples - * Doc-only Update for Rekognition: Added code snippets -* `service/snowball`: Updates service examples -* `service/dynamodbstreams`: Updates service API and examples - * Doc-only Update for DynamoDB Streams: Added code snippets - -SDK Feature ---- -* `private/model/api`: Increasing the readability of code generated files. (#1024) -Release v1.6.9 (2016-12-30) -=== - -Service Client Updates ---- -* `service/codedeploy`: Updates service API and documentation - * CodeDeploy will support Iam Session Arns in addition to Iam User Arns for on premise host authentication. -* `service/ecs`: Updates service API and documentation - * Amazon EC2 Container Service (ECS) now supports the ability to customize the placement of tasks on container instances. -* `aws/endpoints`: Updated Regions and Endpoints metadata. - -Release v1.6.8 (2016-12-22) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation - * Amazon API Gateway is adding support for generating SDKs in more languages. This update introduces two new operations used to dynamically discover these SDK types and what configuration each type accepts. -* `service/directoryservice`: Updates service documentation - * Added code snippets for the DS SDKs -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/iam`: Updates service API and documentation - * Adds service-specific credentials to IAM service to make it easier to onboard CodeCommit customers. These are username/password credentials that work with a single service. -* `service/kms`: Updates service API, documentation, and examples - * Update docs and add SDK examples - -Release v1.6.7 (2016-12-22) -=== - -Service Client Updates ---- -* `service/ecr`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/rds`: Updates service API and documentation - * Cross Region Encrypted Snapshot Copying (CopyDBSnapshot) - -Release v1.6.6 (2016-12-20) -=== - -Service Client Updates ---- -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/firehose`: Updates service API, documentation, and examples - * Processing feature enables users to process and modify records before Amazon Firehose delivers them to destinations. -* `service/route53`: Updates service API and documentation - * Enum updates for eu-west-2 and ca-central-1 -* `service/storagegateway`: Updates service API, documentation, and examples - * File gateway is a new mode in the AWS Storage Gateway that support a file interface into S3, alongside the current block-based volume and VTL storage. File gateway combines a service and virtual software appliance, enabling you to store and retrieve objects in Amazon S3 using industry standard file protocols such as NFS. The software appliance, or gateway, is deployed into your on-premises environment as a virtual machine (VM) running on VMware ESXi. The gateway provides access to objects in S3 as files on a Network File System (NFS) mount point. - -Release v1.6.5 (2016-12-19) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation - * Minor doc update for CloudFormation. -* `service/cloudtrail`: Updates service paginators -* `service/cognitoidentity`: Updates service API and documentation - * We are adding Groups to Cognito user pools. Developers can perform CRUD operations on groups, add and remove users from groups, list users in groups, etc. We are adding fine-grained role-based access control for Cognito identity pools. Developers can configure an identity pool to get the IAM role from an authenticated user's token, or they can configure rules that will map a user to a different role -* `service/applicationdiscoveryservice`: Updates service API and documentation - * Adds new APIs to group discovered servers into Applications with get summary and neighbors. Includes additional filters for ListConfigurations and DescribeAgents API. -* `service/inspector`: Updates service API, documentation, and examples - * Doc-only Update for Inspector: Adding SDK code snippets for Inspector -* `service/sqs`: Updates service documentation - -SDK Bug Fixes ---- -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1011) - * Fixes: Not retrying when PriorRequestNotComplete #1009 - -SDK Feature ---- -* `private/model/api`: Adds crosslinking to service documentation (#1010) - -Release v1.6.4 (2016-12-15) -=== - -Service Client Updates ---- -* `service/cognitoidentityprovider`: Updates service API and documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/ssm`: Updates service API and documentation - * This will provide customers with access to the Patch Baseline and Patch Compliance APIs. - -SDK Bug Fixes ---- -* `service/route53`: Fix URL path cleaning for Route53 API requests (#1006) - * Fixes: SerializationError when using Route53 ChangeResourceRecordSets #1005 -* `aws/request`: Add PriorRequestNotComplete to throttle retry codes (#1002) - * Fixes: Not retrying when PriorRequestNotComplete #1001 - -Release v1.6.3 (2016-12-14) -=== - -Service Client Updates ---- -* `service/batch`: Adds new service - * AWS Batch is a batch computing service that lets customers define queues and compute environments and then submit work as batch jobs. -* `service/databasemigrationservice`: Updates service API and documentation - * Adds support for SSL enabled Oracle endpoints and task modification. -* `service/elasticbeanstalk`: Updates service documentation -* `aws/endpoints`: Updated Regions and Endpoints metadata. -* `service/cloudwatchlogs`: Updates service API and documentation - * Add support for associating LogGroups with AWSTagris tags -* `service/marketplacecommerceanalytics`: Updates service API and documentation - * Add new enum to DataSetType: sales_compensation_billed_revenue -* `service/rds`: Updates service documentation - * Doc-only Update for RDS: New versions available in CreateDBInstance -* `service/sts`: Updates service documentation - * Adding Code Snippet Examples for SDKs for STS - -SDK Bug Fixes ---- -* `aws/request`: Fix retrying timeout requests (#981) - * Fixes: Requests Retrying is broken if the error was caused due to a client timeout #947 -* `aws/request`: Fix for Go 1.8 request incorrectly sent with body (#991) - * Fixes: service/route53: ListHostedZones hangs and then fails with go1.8 #984 -* private/protocol/rest: Use RawPath instead of Opaque (#993) - * Fixes: HTTP2 request failing with REST protocol services, e.g AWS X-Ray -* private/model/api: Generate REST-JSON JSONVersion correctly (#998) - * Fixes: REST-JSON protocol service code missing JSONVersion metadata. - -Release v1.6.2 (2016-12-08) -=== - -Service Client Updates ---- -* `service/cloudfront`: Add lambda function associations to cache behaviors -* `service/codepipeline`: This is a doc-only update request to incorporate some recent minor revisions to the doc content. -* `service/rds`: Updates service API and documentation -* `service/wafregional`: With this new feature, customers can use AWS WAF directly on Application Load Balancers in a VPC within available regions to protect their websites and web services from malicious attacks such as SQL injection, Cross Site Scripting, bad bots, etc. - -Release v1.6.1 (2016-12-07) -=== - -Service Client Updates ---- -* `service/config`: Updates service API -* `service/s3`: Updates service API -* `service/sqs`: Updates service API and documentation - -Release v1.6.0 (2016-12-06) -=== - -Service Client Updates ---- -* `service/config`: Updates service API and documentation -* `service/ec2`: Updates service API -* `service/sts`: Updates service API, documentation, and examples - -SDK Bug Fixes ---- -* private/protocol/xml/xmlutil: Fix SDK XML unmarshaler #975 - * Fixes GetBucketACL Grantee required type always nil. #916 - -SDK Feature ---- -* aws/endpoints: Add endpoint metadata to SDK #961 - * Adds Region and Endpoint metadata to the SDK. This allows you to enumerate regions and endpoint metadata based on a defined model embedded in the SDK. - -Release v1.5.13 (2016-12-01) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/appstream`: Adds new service -* `service/codebuild`: Adds new service -* `service/directconnect`: Updates service API and documentation -* `service/ec2`: Adds new service -* `service/elasticbeanstalk`: Updates service API and documentation -* `service/health`: Adds new service -* `service/lambda`: Updates service API and documentation -* `service/opsworkscm`: Adds new service -* `service/pinpoint`: Adds new service -* `service/shield`: Adds new service -* `service/ssm`: Updates service API and documentation -* `service/states`: Adds new service -* `service/xray`: Adds new service - -Release v1.5.12 (2016-11-30) -=== - -Service Client Updates ---- -* `service/lightsail`: Adds new service -* `service/polly`: Adds new service -* `service/rekognition`: Adds new service -* `service/snowball`: Updates service API and documentation - -Release v1.5.11 (2016-11-29) -=== - -Service Client Updates ---- -`service/s3`: Updates service API and documentation - -Release v1.5.10 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/glacier`: Updates service API, documentation, and examples -* `service/route53`: Updates service API and documentation -* `service/s3`: Updates service API and documentation - -SDK Bug Fixes ---- -* `private/protocol/xml/xmlutil`: Fixes xml marshaler to unmarshal properly -into tagged fields -[#916](https://github.com/aws/aws-sdk-go/issues/916) - -Release v1.5.9 (2016-11-22) -=== - -Service Client Updates ---- -* `service/cloudtrail`: Updates service API and documentation -* `service/ecs`: Updates service API and documentation - -Release v1.5.8 (2016-11-18) -=== - -Service Client Updates ---- -* `service/application-autoscaling`: Updates service API and documentation -* `service/elasticmapreduce`: Updates service API and documentation -* `service/elastictranscoder`: Updates service API, documentation, and examples -* `service/gamelift`: Updates service API and documentation -* `service/lambda`: Updates service API and documentation - -Release v1.5.7 (2016-11-18) -=== - -Service Client Updates ---- -* `service/apigateway`: Updates service API and documentation -* `service/meteringmarketplace`: Updates service API and documentation -* `service/monitoring`: Updates service API and documentation -* `service/sqs`: Updates service API, documentation, and examples - -Release v1.5.6 (2016-11-16) -=== - -Service Client Updates ---- -`service/route53`: Updates service API and documentation -`service/servicecatalog`: Updates service API and documentation - -Release v1.5.5 (2016-11-15) -=== - -Service Client Updates ---- -* `service/ds`: Updates service API and documentation -* `service/elasticache`: Updates service API and documentation -* `service/kinesis`: Updates service API and documentation - -Release v1.5.4 (2016-11-15) -=== - -Service Client Updates ---- -* `service/cognito-idp`: Updates service API and documentation - -Release v1.5.3 (2016-11-11) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service documentation and examples -* `service/logs`: Updates service API and documentation - -Release v1.5.2 (2016-11-03) -=== - -Service Client Updates ---- -* `service/directconnect`: Updates service API and documentation - -Release v1.5.1 (2016-11-02) -=== - -Service Client Updates ---- -* `service/email`: Updates service API and documentation - -Release v1.5.0 (2016-11-01) -=== - -Service Client Updates ---- -* `service/cloudformation`: Updates service API and documentation -* `service/ecr`: Updates service paginators - -SDK Feature Updates ---- -* `private/model/api`: Add generated setters for API parameters (#918) - * Adds setters to the SDK's API parameter types, and are a convenience method that reduce the need to use `aws.String` and like utility. - -Release v1.4.22 (2016-10-25) -=== - -Service Client Updates ---- -* `service/elasticloadbalancingv2`: Updates service documentation. -* `service/autoscaling`: Updates service documentation. - -Release v1.4.21 (2016-10-24) -=== - -Service Client Updates ---- -* `service/sms`: AWS Server Migration Service (SMS) is an agentless service which makes it easier and faster for you to migrate thousands of on-premises workloads to AWS. AWS SMS allows you to automate, schedule, and track incremental replications of live server volumes, making it easier for you to coordinate large-scale server migrations. -* `service/ecs`: Updates documentation. - -SDK Feature Updates ---- -* `private/models/api`: Improve code generation of documentation. - -Release v1.4.20 (2016-10-20) -=== - -Service Client Updates ---- -* `service/budgets`: Adds new service, AWS Budgets. -* `service/waf`: Updates service documentation. - -Release v1.4.19 (2016-10-18) -=== - -Service Client Updates ---- -* `service/cloudfront`: Updates service API and documentation. - * Ability to use Amazon CloudFront to deliver your content both via IPv6 and IPv4 using HTTP/HTTPS. -* `service/configservice`: Update service API and documentation. -* `service/iot`: Updates service API and documentation. -* `service/kinesisanalytics`: Updates service API and documentation. - * Whenever Amazon Kinesis Analytics is not able to detect schema for the given streaming source on DiscoverInputSchema API, we would return the raw records that was sampled to detect the schema. -* `service/rds`: Updates service API and documentation. - * Amazon Aurora integrates with other AWS services to allow you to extend your Aurora DB cluster to utilize other capabilities in the AWS cloud. Permission to access other AWS services is granted by creating an IAM role with the necessary permissions, and then associating the role with your DB cluster. - -SDK Feature Updates ---- -* `service/dynamodb/dynamodbattribute`: Add UnmarshalListOfMaps #897 - * Adds support for unmarshaling a list of maps. This is useful for unmarshaling the DynamoDB AttributeValue list of maps returned by APIs like Query and Scan. - -Release v1.4.18 (2016-10-17) -=== - -Service Model Updates ---- -* `service/route53`: Updates service API and documentation. - -Release v1.4.17 -=== - -Service Model Updates ---- -* `service/acm`: Update service API, and documentation. - * This change allows users to import third-party SSL/TLS certificates into ACM. -* `service/elasticbeanstalk`: Update service API, documentation, and pagination. - * Elastic Beanstalk DescribeApplicationVersions API is being updated to support pagination. -* `service/gamelift`: Update service API, and documentation. - * New APIs to protect game developer resource (builds, alias, fleets, instances, game sessions and player sessions) against abuse. - -SDK Features ---- -* `service/s3`: Add support for accelerate with dualstack [#887](https://github.com/aws/aws-sdk-go/issues/887) - -Release v1.4.16 (2016-10-13) -=== - -Service Model Updates ---- -* `service/ecr`: Update Amazon EC2 Container Registry service model - * DescribeImages is a new api used to expose image metadata which today includes image size and image creation timestamp. -* `service/elasticache`: Update Amazon ElastiCache service model - * Elasticache is launching a new major engine release of Redis, 3.2 (providing stability updates and new command sets over 2.8), as well as ElasticSupport for enabling Redis Cluster in 3.2, which provides support for multiple node groups to horizontally scale data, as well as superior engine failover capabilities - -SDK Bug Fixes ---- -* `aws/session`: Skip shared config on read errors [#883](https://github.com/aws/aws-sdk-go/issues/883) -* `aws/signer/v4`: Add support for URL.EscapedPath to signer [#885](https://github.com/aws/aws-sdk-go/issues/885) - -SDK Features ---- -* `private/model/api`: Add docs for errors to API operations [#881](https://github.com/aws/aws-sdk-go/issues/881) -* `private/model/api`: Improve field and waiter doc strings [#879](https://github.com/aws/aws-sdk-go/issues/879) -* `service/dynamodb/dynamodbattribute`: Allow multiple struct tag elements [#886](https://github.com/aws/aws-sdk-go/issues/886) -* Add build tags to internal SDK tools [#880](https://github.com/aws/aws-sdk-go/issues/880) - -Release v1.4.15 (2016-10-06) -=== - -Service Model Updates ---- -* `service/cognitoidentityprovider`: Update Amazon Cognito Identity Provider service model -* `service/devicefarm`: Update AWS Device Farm documentation -* `service/opsworks`: Update AWS OpsWorks service model -* `service/s3`: Update Amazon Simple Storage Service model -* `service/waf`: Update AWS WAF service model - -SDK Bug Fixes ---- -* `aws/request`: Fix HTTP Request Body race condition [#874](https://github.com/aws/aws-sdk-go/issues/874) - -SDK Feature Updates ---- -* `aws/ec2metadata`: Add support for EC2 User Data [#872](https://github.com/aws/aws-sdk-go/issues/872) -* `aws/signer/v4`: Remove logic determining if request needs to be resigned [#876](https://github.com/aws/aws-sdk-go/issues/876) - -Release v1.4.14 (2016-09-29) -=== -* `service/ec2`: api, documentation, and paginators updates. -* `service/s3`: api and documentation updates. - -Release v1.4.13 (2016-09-27) -=== -* `service/codepipeline`: documentation updates. -* `service/cloudformation`: api and documentation updates. -* `service/kms`: documentation updates. -* `service/elasticfilesystem`: documentation updates. -* `service/snowball`: documentation updates. diff --git a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md b/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md deleted file mode 100644 index 8a1927a..0000000 --- a/vendor/github.com/aws/aws-sdk-go/CHANGELOG_PENDING.md +++ /dev/null @@ -1,5 +0,0 @@ -### SDK Features - -### SDK Enhancements - -### SDK Bugs diff --git a/vendor/github.com/aws/aws-sdk-go/CODE_OF_CONDUCT.md b/vendor/github.com/aws/aws-sdk-go/CODE_OF_CONDUCT.md deleted file mode 100644 index 3b64466..0000000 --- a/vendor/github.com/aws/aws-sdk-go/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md b/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md deleted file mode 100644 index 9f4a0c1..0000000 --- a/vendor/github.com/aws/aws-sdk-go/CONTRIBUTING.md +++ /dev/null @@ -1,127 +0,0 @@ -Contributing to the AWS SDK for Go - -We work hard to provide a high-quality and useful SDK, and we greatly value -feedback and contributions from our community. Whether it's a bug report, -new feature, correction, or additional documentation, we welcome your issues -and pull requests. Please read through this document before submitting any -issues or pull requests to ensure we have all the necessary information to -effectively respond to your bug report or contribution. - - -## Filing Bug Reports - -You can file bug reports against the SDK on the [GitHub issues][issues] page. - -If you are filing a report for a bug or regression in the SDK, it's extremely -helpful to provide as much information as possible when opening the original -issue. This helps us reproduce and investigate the possible bug without having -to wait for this extra information to be provided. Please read the following -guidelines prior to filing a bug report. - -1. Search through existing [issues][] to ensure that your specific issue has - not yet been reported. If it is a common issue, it is likely there is - already a bug report for your problem. - -2. Ensure that you have tested the latest version of the SDK. Although you - may have an issue against an older version of the SDK, we cannot provide - bug fixes for old versions. It's also possible that the bug may have been - fixed in the latest release. - -3. Provide as much information about your environment, SDK version, and - relevant dependencies as possible. For example, let us know what version - of Go you are using, which and version of the operating system, and the - the environment your code is running in. e.g Container. - -4. Provide a minimal test case that reproduces your issue or any error - information you related to your problem. We can provide feedback much - more quickly if we know what operations you are calling in the SDK. If - you cannot provide a full test case, provide as much code as you can - to help us diagnose the problem. Any relevant information should be provided - as well, like whether this is a persistent issue, or if it only occurs - some of the time. - - -## Submitting Pull Requests - -We are always happy to receive code and documentation contributions to the SDK. -Please be aware of the following notes prior to opening a pull request: - -1. The SDK is released under the [Apache license][license]. Any code you submit - will be released under that license. For substantial contributions, we may - ask you to sign a [Contributor License Agreement (CLA)][cla]. - -2. If you would like to implement support for a significant feature that is not - yet available in the SDK, please talk to us beforehand to avoid any - duplication of effort. - -3. Wherever possible, pull requests should contain tests as appropriate. - Bugfixes should contain tests that exercise the corrected behavior (i.e., the - test should fail without the bugfix and pass with it), and new features - should be accompanied by tests exercising the feature. - -4. Pull requests that contain failing tests will not be merged until the test - failures are addressed. Pull requests that cause a significant drop in the - SDK's test coverage percentage are unlikely to be merged until tests have - been added. - -5. The JSON files under the SDK's `models` folder are sourced from outside the SDK. - Such as `models/apis/ec2/2016-11-15/api.json`. We will not accept pull requests - directly on these models. If you discover an issue with the models please - create a [GitHub issue][issues] describing the issue. - -### Testing - -To run the tests locally, running the `make unit` command will `go get` the -SDK's testing dependencies, and run vet, link and unit tests for the SDK. - -``` -make unit -``` - -Standard go testing functionality is supported as well. To test SDK code that -is tagged with `codegen` you'll need to set the build tag in the go test -command. The `make unit` command will do this automatically. - -``` -go test -tags codegen ./private/... -``` - -See the `Makefile` for additional testing tags that can be used in testing. - -To test on multiple platform the SDK includes several DockerFiles under the -`awstesting/sandbox` folder, and associated make recipes to execute -unit testing within environments configured for specific Go versions. - -``` -make sandbox-test-go18 -``` - -To run all sandbox environments use the following make recipe - -``` -# Optionally update the Go tip that will be used during the batch testing -make update-aws-golang-tip - -# Run all SDK tests for supported Go versions in sandboxes -make sandbox-test -``` - -In addition the sandbox environment include make recipes for interactive modes -so you can run command within the Docker container and context of the SDK. - -``` -make sandbox-go18 -``` - -### Changelog - -You can see all release changes in the `CHANGELOG.md` file at the root of the -repository. The release notes added to this file will contain service client -updates, and major SDK changes. - -[issues]: https://github.com/aws/aws-sdk-go/issues -[pr]: https://github.com/aws/aws-sdk-go/pulls -[license]: http://aws.amazon.com/apache2.0/ -[cla]: http://en.wikipedia.org/wiki/Contributor_License_Agreement -[releasenotes]: https://github.com/aws/aws-sdk-go/releases - diff --git a/vendor/github.com/aws/aws-sdk-go/Gopkg.lock b/vendor/github.com/aws/aws-sdk-go/Gopkg.lock deleted file mode 100644 index 81273b9..0000000 --- a/vendor/github.com/aws/aws-sdk-go/Gopkg.lock +++ /dev/null @@ -1,16 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:13fe471d0ed891e8544eddfeeb0471fd3c9f2015609a1c000aefdedf52a19d40" - name = "github.com/jmespath/go-jmespath" - packages = ["."] - pruneopts = "" - revision = "c2b33e84" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = ["github.com/jmespath/go-jmespath"] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/vendor/github.com/aws/aws-sdk-go/Gopkg.toml b/vendor/github.com/aws/aws-sdk-go/Gopkg.toml deleted file mode 100644 index 60688e2..0000000 --- a/vendor/github.com/aws/aws-sdk-go/Gopkg.toml +++ /dev/null @@ -1,43 +0,0 @@ - -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - -ignored = [ - # Testing/Example/Codegen dependencies - "github.com/stretchr/testify", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/require", - "github.com/go-sql-driver/mysql", - "github.com/gucumber/gucumber", - "github.com/pkg/errors", - "golang.org/x/net", - "golang.org/x/net/html", - "golang.org/x/net/http2", - "golang.org/x/text", - "golang.org/x/text/html", - "golang.org/x/tools", - "golang.org/x/tools/go/loader", -] - -[[constraint]] - name = "github.com/jmespath/go-jmespath" - revision = "c2b33e84" - #version = "0.2.2" diff --git a/vendor/github.com/aws/aws-sdk-go/Makefile b/vendor/github.com/aws/aws-sdk-go/Makefile deleted file mode 100644 index abcab84..0000000 --- a/vendor/github.com/aws/aws-sdk-go/Makefile +++ /dev/null @@ -1,235 +0,0 @@ -LINTIGNOREDOC='service/[^/]+/(api|service|waiters)\.go:.+(comment on exported|should have comment or be unexported)' -LINTIGNORECONST='service/[^/]+/(api|service|waiters)\.go:.+(type|struct field|const|func) ([^ ]+) should be ([^ ]+)' -LINTIGNORESTUTTER='service/[^/]+/(api|service)\.go:.+(and that stutters)' -LINTIGNOREINFLECT='service/[^/]+/(api|errors|service)\.go:.+(method|const) .+ should be ' -LINTIGNOREINFLECTS3UPLOAD='service/s3/s3manager/upload\.go:.+struct field SSEKMSKeyId should be ' -LINTIGNOREENDPOINTS='aws/endpoints/(defaults|dep_service_ids).go:.+(method|const) .+ should be ' -LINTIGNOREDEPS='vendor/.+\.go' -LINTIGNOREPKGCOMMENT='service/[^/]+/doc_custom.go:.+package comment should be of the form' -UNIT_TEST_TAGS="example codegen awsinclude" - -# SDK's Core and client packages that are compatable with Go 1.5+. -SDK_CORE_PKGS=./aws/... ./private/... ./internal/... -SDK_CLIENT_PKGS=./service/... -SDK_COMPA_PKGS=${SDK_CORE_PKGS} ${SDK_CLIENT_PKGS} - -# SDK additional packages that are used for development of the SDK. -SDK_EXAMPLES_PKGS=./examples/... -SDK_TESTING_PKGS=./awstesting/... -SDK_MODELS_PKGS=./models/... -SDK_ALL_PKGS=${SDK_COMPA_PKGS} ${SDK_TESTING_PKGS} ${SDK_EXAMPLES_PKGS} ${SDK_MODELS_PKGS} - -all: generate unit - -help: - @echo "Please use \`make ' where is one of" - @echo " api_info to print a list of services and versions" - @echo " docs to build SDK documentation" - @echo " unit to run unit tests" - @echo " integration to run integration tests" - @echo " performance to run performance tests" - @echo " verify to verify tests" - @echo " lint to lint the SDK" - @echo " vet to vet the SDK" - @echo " generate to go generate and make services" - @echo " gen-test to generate protocol tests" - @echo " gen-services to generate services" - @echo " get-deps to go get the SDK dependencies" - -################### -# Code Generation # -################### -generate: cleanup-models gen-test gen-endpoints gen-services - -gen-test: gen-protocol-test gen-codegen-test - -gen-codegen-test: get-deps-codegen - @echo "Generating SDK API tests" - go generate ./private/model/api/codegentest/service - -gen-services: get-deps-codegen - @echo "Generating SDK clients" - go generate ./service - -gen-protocol-test: get-deps-codegen - @echo "Generating SDK protocol tests" - go generate ./private/protocol/... - -gen-endpoints: get-deps-codegen - @echo "Generating SDK endpoints" - go generate ./models/endpoints/ - -cleanup-models: get-deps-codegen - @echo "Cleaning up stale model versions" - go run -tags codegen ./private/model/cli/cleanup-models/* "./models/apis/*/*/api-2.json" - -################### -# Unit/CI Testing # -################### -unit: get-deps verify - @echo "go test SDK and vendor packages" - go test -tags ${UNIT_TEST_TAGS} ${SDK_ALL_PKGS} - -unit-with-race-cover: get-deps verify - @echo "go test SDK and vendor packages" - go test -tags ${UNIT_TEST_TAGS} -race -cpu=1,2,4 ${SDK_ALL_PKGS} - -unit-old-go-race-cover: get-deps-tests - @echo "go test SDK only packages for old Go versions" - go test -race -cpu=1,2,4 ${SDK_COMPA_PKGS} - -ci-test: generate unit-with-race-cover ci-test-generate-validate - -ci-test-generate-validate: - @echo "CI test validate no generated code changes" - git add . -A - gitstatus=`git diff --cached --ignore-space-change`; \ - echo "$$gitstatus"; \ - if [ "$$gitstatus" != "" ] && [ "$$gitstatus" != "skipping validation" ]; then echo "$$gitstatus"; exit 1; fi - -####################### -# Integration Testing # -####################### -integration: core-integ client-integ - -core-integ: - @echo "Integration Testing SDK core" - AWS_REGION="" go test -count=1 -tags "integration" -v -run '^TestInteg_' ./aws/... ./private/... ./internal/... ./awstesting/... - -client-integ: - @echo "Integration Testing SDK clients" - AWS_REGION="" go test -count=1 -tags "integration" -v -run '^TestInteg_' ./service/... - -s3crypto-integ: - @echo "Integration Testing S3 Cyrpto utility" - AWS_REGION="" go test -count=1 -tags "s3crypto_integ integration" -v -run '^TestInteg_' ./service/s3/s3crypto - -cleanup-integ-buckets: - @echo "Cleaning up SDK integraiton resources" - go run -tags "integration" ./awstesting/cmd/bucket_cleanup/main.go "aws-sdk-go-integration" - -################### -# Sandbox Testing # -################### -sandbox-tests: sandbox-test-go15 sandbox-test-go16 sandbox-test-go17 sandbox-test-go18 sandbox-test-go19 sandbox-test-go110 sandbox-test-go111 sandbox-test-gotip - -sandbox-build-go15: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5 -t "aws-sdk-go-1.5" . -sandbox-go15: sandbox-build-go15 - docker run -i -t aws-sdk-go-1.5 bash -sandbox-test-go15: sandbox-build-go15 - docker run -t aws-sdk-go-1.5 - -sandbox-build-go15-novendorexp: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.5-novendorexp -t "aws-sdk-go-1.5-novendorexp" . -sandbox-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -i -t aws-sdk-go-1.5-novendorexp bash -sandbox-test-go15-novendorexp: sandbox-build-go15-novendorexp - docker run -t aws-sdk-go-1.5-novendorexp - -sandbox-build-go16: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.6 -t "aws-sdk-go-1.6" . -sandbox-go16: sandbox-build-go16 - docker run -i -t aws-sdk-go-1.6 bash -sandbox-test-go16: sandbox-build-go16 - docker run -t aws-sdk-go-1.6 - -sandbox-build-go17: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.7 -t "aws-sdk-go-1.7" . -sandbox-go17: sandbox-build-go17 - docker run -i -t aws-sdk-go-1.7 bash -sandbox-test-go17: sandbox-build-go17 - docker run -t aws-sdk-go-1.7 - -sandbox-build-go18: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.8 -t "aws-sdk-go-1.8" . -sandbox-go18: sandbox-build-go18 - docker run -i -t aws-sdk-go-1.8 bash -sandbox-test-go18: sandbox-build-go18 - docker run -t aws-sdk-go-1.8 - -sandbox-build-go19: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.9 -t "aws-sdk-go-1.9" . -sandbox-go19: sandbox-build-go19 - docker run -i -t aws-sdk-go-1.9 bash -sandbox-test-go19: sandbox-build-go19 - docker run -t aws-sdk-go-1.9 - -sandbox-build-go110: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.10 -t "aws-sdk-go-1.10" . -sandbox-go110: sandbox-build-go110 - docker run -i -t aws-sdk-go-1.10 bash -sandbox-test-go110: sandbox-build-go110 - docker run -t aws-sdk-go-1.10 - -sandbox-build-go111: - docker build -f ./awstesting/sandbox/Dockerfile.test.go1.11 -t "aws-sdk-go-1.11" . -sandbox-go111: sandbox-build-go111 - docker run -i -t aws-sdk-go-1.11 bash -sandbox-test-go111: sandbox-build-go111 - docker run -t aws-sdk-go-1.11 - -sandbox-build-gotip: - @echo "Run make update-aws-golang-tip, if this test fails because missing aws-golang:tip container" - docker build -f ./awstesting/sandbox/Dockerfile.test.gotip -t "aws-sdk-go-tip" . -sandbox-gotip: sandbox-build-gotip - docker run -i -t aws-sdk-go-tip bash -sandbox-test-gotip: sandbox-build-gotip - docker run -t aws-sdk-go-tip - -update-aws-golang-tip: - docker build --no-cache=true -f ./awstesting/sandbox/Dockerfile.golang-tip -t "aws-golang:tip" . - -################## -# Linting/Verify # -################## -verify: get-deps-verify lint vet - -lint: - @echo "go lint SDK and vendor packages" - @lint=`golint ./...`; \ - dolint=`echo "$$lint" | grep -E -v -e ${LINTIGNOREDOC} -e ${LINTIGNORECONST} -e ${LINTIGNORESTUTTER} -e ${LINTIGNOREINFLECT} -e ${LINTIGNOREDEPS} -e ${LINTIGNOREINFLECTS3UPLOAD} -e ${LINTIGNOREPKGCOMMENT} -e ${LINTIGNOREENDPOINTS}`; \ - echo "$$dolint"; \ - if [ "$$dolint" != "" ]; then exit 1; fi - -vet: - go vet -tags "example codegen awsinclude integration" --all ${SDK_ALL_PKGS} - -################ -# Dependencies # -################ -get-deps: get-deps-tests get-deps-x-tests get-deps-codegen get-deps-verify - -get-deps-tests: - @echo "go get SDK testing dependencies" - go get github.com/stretchr/testify - -get-deps-x-tests: - @echo "go get SDK testing golang.org/x dependencies" - go get golang.org/x/net/http2 - -get-deps-codegen: get-deps-x-tests - @echo "go get SDK codegen dependencies" - go get golang.org/x/net/html - -get-deps-verify: - @echo "go get SDK verification utilities" - go get golang.org/x/lint/golint - -bench: - @echo "go bench SDK packages" - go test -run NONE -bench . -benchmem -tags 'bench' ${SDK_ALL_PKGS} - -bench-protocol: - @echo "go bench SDK protocol marshallers" - go test -run NONE -bench . -benchmem -tags 'bench' ./private/protocol/... - -############# -# Utilities # -############# -docs: - @echo "generate SDK docs" - $(AWS_DOC_GEN_TOOL) `pwd` - -api_info: - @go run private/model/cli/api-info/api-info.go diff --git a/vendor/github.com/aws/aws-sdk-go/README.md b/vendor/github.com/aws/aws-sdk-go/README.md deleted file mode 100644 index 2b275db..0000000 --- a/vendor/github.com/aws/aws-sdk-go/README.md +++ /dev/null @@ -1,500 +0,0 @@ -[![API Reference](https://img.shields.io/badge/api-reference-blue.svg)](https://docs.aws.amazon.com/sdk-for-go/api) [![Join the chat at https://gitter.im/aws/aws-sdk-go](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/aws/aws-sdk-go?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Build Status](https://img.shields.io/travis/aws/aws-sdk-go.svg)](https://travis-ci.org/aws/aws-sdk-go) [![Apache V2 License](https://img.shields.io/badge/license-Apache%20V2-blue.svg)](https://github.com/aws/aws-sdk-go/blob/master/LICENSE.txt) - -# AWS SDK for Go - -aws-sdk-go is the official AWS SDK for the Go programming language. - -Checkout our [release notes](https://github.com/aws/aws-sdk-go/releases) for -information about the latest bug fixes, updates, and features added to the SDK. - -We [announced](https://aws.amazon.com/blogs/developer/aws-sdk-for-go-2-0-developer-preview/) the Developer Preview for the [v2 AWS SDK for Go](https://github.com/aws/aws-sdk-go-v2). The v2 SDK source is available at https://github.com/aws/aws-sdk-go-v2, and add it to your project with `go get github.com/aws/aws-sdk-go-v2`. Check out the v2 SDK's [changes and updates](https://github.com/aws/aws-sdk-go-v2/blob/master/CHANGELOG.md), and let us know what you think. We want your feedback. - -## Installing - -Use `go get` to retrieve the SDK to add it to your `GOPATH` workspace, or -project's Go module dependencies. - - go get github.com/aws/aws-sdk-go - -To update the SDK use `go get -u` to retrieve the latest version of the SDK. - - go get -u github.com/aws/aws-sdk-go - -### Dependencies - -The SDK includes a `vendor` folder containing the runtime dependencies of the -SDK. The metadata of the SDK's dependencies can be found in the Go module file -`go.mod` or Dep file `Gopkg.toml`. - -### Go Modules - -If you are using Go modules, your `go get` will default to the latest tagged -release version of the SDK. To get a specific release version of the SDK use -`@` in your `go get` command. - - go get github.com/aws/aws-sdk-go@v1.15.77 - -To get the latest SDK repository change use `@latest`. - - go get github.com/aws/aws-sdk-go@latest - -### Go 1.5 - -If you are using Go 1.5 without vendoring enabled, (`GO15VENDOREXPERIMENT=1`), -you will need to use `...` when retrieving the SDK to get its dependencies. - - go get github.com/aws/aws-sdk-go/... - -This will still include the `vendor` folder. The `vendor` folder can be deleted -if not used by your environment. - - rm -rf $GOPATH/src/github.com/aws/aws-sdk-go/vendor - -## Getting Help - -Please use these community resources for getting help. We use the GitHub issues -for tracking bugs and feature requests. - -* Ask a question on [StackOverflow](http://stackoverflow.com/) and tag it with the [`aws-sdk-go`](http://stackoverflow.com/questions/tagged/aws-sdk-go) tag. -* Come join the AWS SDK for Go community chat on [gitter](https://gitter.im/aws/aws-sdk-go). -* Open a support ticket with [AWS Support](http://docs.aws.amazon.com/awssupport/latest/user/getting-started.html). -* If you think you may have found a bug, please open an [issue](https://github.com/aws/aws-sdk-go/issues/new). - -## Opening Issues - -If you encounter a bug with the AWS SDK for Go we would like to hear about it. -Search the [existing issues](https://github.com/aws/aws-sdk-go/issues) and see -if others are also experiencing the issue before opening a new issue. Please -include the version of AWS SDK for Go, Go language, and OS you’re using. Please -also include reproduction case when appropriate. - -The GitHub issues are intended for bug reports and feature requests. For help -and questions with using AWS SDK for GO please make use of the resources listed -in the [Getting Help](https://github.com/aws/aws-sdk-go#getting-help) section. -Keeping the list of open issues lean will help us respond in a timely manner. - -## Reference Documentation - -[`Getting Started Guide`](https://aws.amazon.com/sdk-for-go/) - This document -is a general introduction on how to configure and make requests with the SDK. -If this is your first time using the SDK, this documentation and the API -documentation will help you get started. This document focuses on the syntax -and behavior of the SDK. The [Service Developer -Guide](https://aws.amazon.com/documentation/) will help you get started using -specific AWS services. - -[`SDK API Reference -Documentation`](https://docs.aws.amazon.com/sdk-for-go/api/) - Use this -document to look up all API operation input and output parameters for AWS -services supported by the SDK. The API reference also includes documentation of -the SDK, and examples how to using the SDK, service client API operations, and -API operation require parameters. - -[`Service Developer Guide`](https://aws.amazon.com/documentation/) - Use this -documentation to learn how to interface with AWS services. These are great -guides both, if you're getting started with a service, or looking for more -information on a service. You should not need this document for coding, though -in some cases, services may supply helpful samples that you might want to look -out for. - -[`SDK Examples`](https://github.com/aws/aws-sdk-go/tree/master/example) - -Included in the SDK's repo are several hand crafted examples using the SDK -features and AWS services. - -## Overview of SDK's Packages - -The SDK is composed of two main components, SDK core, and service clients. -The SDK core packages are all available under the aws package at the root of -the SDK. Each client for a supported AWS service is available within its own -package under the service folder at the root of the SDK. - - * aws - SDK core, provides common shared types such as Config, Logger, - and utilities to make working with API parameters easier. - - * awserr - Provides the error interface that the SDK will use for all - errors that occur in the SDK's processing. This includes service API - response errors as well. The Error type is made up of a code and message. - Cast the SDK's returned error type to awserr.Error and call the Code - method to compare returned error to specific error codes. See the package's - documentation for additional values that can be extracted such as RequestID. - - * credentials - Provides the types and built in credentials providers - the SDK will use to retrieve AWS credentials to make API requests with. - Nested under this folder are also additional credentials providers such as - stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. - - * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. - Use this to lookup AWS service endpoint information such as which services - are in a region, and what regions a service is in. Constants are also provided - for all region identifiers, e.g UsWest2RegionID for "us-west-2". - - * session - Provides initial default configuration, and load - configuration from external sources such as environment and shared - credentials file. - - * request - Provides the API request sending, and retry logic for the SDK. - This package also includes utilities for defining your own request - retryer, and configuring how the SDK processes the request. - - * service - Clients for AWS services. All services supported by the SDK are - available under this folder. - -## How to Use the SDK's AWS Service Clients - -The SDK includes the Go types and utilities you can use to make requests to -AWS service APIs. Within the service folder at the root of the SDK you'll find -a package for each AWS service the SDK supports. All service clients follows -a common pattern of creation and usage. - -When creating a client for an AWS service you'll first need to have a Session -value constructed. The Session provides shared configuration that can be shared -between your service clients. When service clients are created you can pass -in additional configuration via the aws.Config type to override configuration -provided by in the Session to create service client instances with custom -configuration. - -Once the service's client is created you can use it to make API requests the -AWS service. These clients are safe to use concurrently. - -## Configuring the SDK - -In the AWS SDK for Go, you can configure settings for service clients, such -as the log level and maximum number of retries. Most settings are optional; -however, for each service client, you must specify a region and your credentials. -The SDK uses these values to send requests to the correct AWS region and sign -requests with the correct credentials. You can specify these values as part -of a session or as environment variables. - -See the SDK's [configuration guide][config_guide] for more information. - -See the [session][session_pkg] package documentation for more information on how to use Session -with the SDK. - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information on configuration -options. - -[config_guide]: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -[session_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -[config_typ]: https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -[aws_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/ - -### Configuring Credentials - -When using the SDK you'll generally need your AWS credentials to authenticate -with AWS services. The SDK supports multiple methods of supporting these -credentials. By default the SDK will source credentials automatically from -its default credential chain. See the session package for more information -on this chain, and how to configure it. The common items in the credential -chain are the following: - - * Environment Credentials - Set of environment variables that are useful - when sub processes are created for specific roles. - - * Shared Credentials file (~/.aws/credentials) - This file stores your - credentials based on a profile name and is useful for local development. - - * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials - to application running on an EC2 instance. This removes the need to manage - credential files in production. - -Credentials can be configured in code as well by setting the Config's Credentials -value to a custom provider or using one of the providers included with the -SDK to bypass the default credential chain and use a custom one. This is -helpful when you want to instruct the SDK to only use a specific set of -credentials or providers. - -This example creates a credential provider for assuming an IAM role, "myRoleARN" -and configures the S3 service client to use that role for API requests. - -```go - // 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}) -``` - -See the [credentials][credentials_pkg] package documentation for more information on credential -providers included with the SDK, and how to customize the SDK's usage of -credentials. - -The SDK has support for the shared configuration file (~/.aws/config). This -support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -or enabling the feature in code when creating a Session via the -Option's SharedConfigState parameter. - -```go - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) -``` - -[credentials_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials - -### Configuring AWS Region - -In addition to the credentials you'll need to specify the region the SDK -will use to make AWS API requests to. In the SDK you can specify the region -either with an environment variable, or directly in code when a Session or -service client is created. The last value specified in code wins if the region -is specified multiple ways. - -To set the region via the environment variable set the "AWS_REGION" to the -region you want to the SDK to use. Using this method to set the region will -allow you to run your application in multiple regions without needing additional -code in the application to select the region. - - AWS_REGION=us-west-2 - -The endpoints package includes constants for all regions the SDK knows. The -values are all suffixed with RegionID. These values are helpful, because they -reduce the need to type the region string manually. - -To set the region on a Session use the aws package's Config struct parameter -Region to the AWS region you want the service clients created from the session to -use. This is helpful when you want to create multiple service clients, and -all of the clients make API requests to the same region. - -```go - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - })) -``` - -See the [endpoints][endpoints_pkg] package for the AWS Regions and Endpoints metadata. - -In addition to setting the region when creating a Session you can also set -the region on a per service client bases. This overrides the region of a -Session. This is helpful when you want to create service clients in specific -regions different from the Session's region. - -```go - svc := s3.New(sess, &aws.Config{ - Region: aws.String(endpoints.UsWest2RegionID), - }) -``` - -See the [Config][config_typ] type in the [aws][aws_pkg] package for more information and additional -options such as setting the Endpoint, and other service client configuration options. - -[endpoints_pkg]: https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ - -## Making API Requests - -Once the client is created you can make an API request to the service. -Each API method takes a input parameter, and returns the service response -and an error. The SDK provides methods for making the API call in multiple ways. - -In this list we'll use the S3 ListObjects API as an example for the different -ways of making API requests. - - * ListObjects - Base API operation that will make the API request to the service. - - * ListObjectsRequest - API methods suffixed with Request will construct the - API request, but not send it. This is also helpful when you want to get a - presigned URL for a request, and share the presigned URL instead of your - application making the request directly. - - * ListObjectsPages - Same as the base API operation, but uses a callback to - automatically handle pagination of the API's response. - - * ListObjectsWithContext - Same as base API operation, but adds support for - the Context pattern. This is helpful for controlling the canceling of in - flight requests. See the Go standard library context package for more - information. This method also takes request package's Option functional - options as the variadic argument for modifying how the request will be - made, or extracting information from the raw HTTP response. - - * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for - the Context pattern. Similar to ListObjectsWithContext this method also - takes the request package's Option function option types as the variadic - argument. - -In addition to the API operations the SDK also includes several higher level -methods that abstract checking for and waiting for an AWS resource to be in -a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -the different forms of waiters. - - * WaitUntilBucketExists. - Method to make API request to query an AWS service for - a resource's state. Will return successfully when that state is accomplished. - - * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds - support for the Context pattern. In addition these methods take request - package's WaiterOptions to configure the waiter, and how underlying request - will be made by the SDK. - -The API method will document which error codes the service might return for -the operation. These errors will also be available as const strings prefixed -with "ErrCode" in the service client's package. If there are no errors listed -in the API's SDK documentation you'll need to consult the AWS service's API -documentation for the errors that could be returned. - -```go - ctx := context.Background() - - result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ - Bucket: aws.String("my-bucket"), - Key: aws.String("my-key"), - }) - if err != nil { - // Cast err to awserr.Error to handle specific error codes. - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == s3.ErrCodeNoSuchKey { - // Specific error code handling - } - return err - } - - // Make sure to close the body when done with it for S3 GetObject APIs or - // will leak connections. - defer result.Body.Close() - - fmt.Println("Object Size:", aws.Int64Value(result.ContentLength)) -``` - -### API Request Pagination and Resource Waiters - -Pagination helper methods are suffixed with "Pages", and provide the -functionality needed to round trip API page requests. Pagination methods -take a callback function that will be called for each page of the API's response. - -```go - objects := []string{} - err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ - Bucket: aws.String(myBucket), - }, func(p *s3.ListObjectsOutput, lastPage bool) bool { - for _, o := range p.Contents { - objects = append(objects, aws.StringValue(o.Key)) - } - return true // continue paging - }) - if err != nil { - panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) - } - - fmt.Println("Objects in bucket:", objects) -``` - -Waiter helper methods provide the functionality to wait for an AWS resource -state. These methods abstract the logic needed to check the state of an -AWS resource, and wait until that resource is in a desired state. The waiter -will block until the resource is in the state that is desired, an error occurs, -or the waiter times out. If a resource times out the error code returned will -be request.WaiterResourceNotReadyErrorCode. - -```go - err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ - Bucket: aws.String(myBucket), - }) - if err != nil { - aerr, ok := err.(awserr.Error) - if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { - fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") - } - panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) - } - fmt.Println("Bucket", myBucket, "exists") -``` - -## Complete SDK Example - -This example shows a complete working Go file which will upload a file to S3 -and use the Context pattern to implement timeout logic that will cancel the -request if it takes too long. This example highlights how to use sessions, -create a service client, make a request, handle the error, and process the -response. - -```go - package main - - import ( - "context" - "flag" - "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/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/s3" - ) - - // Uploads a file to S3 given a bucket and object key. Also takes a duration - // value to terminate the update if it doesn't complete within that time. - // - // The AWS Region needs to be provided in the AWS shared config or on the - // environment variable as `AWS_REGION`. Credentials also must be provided - // Will default to shared config file, but can load from environment if provided. - // - // Usage: - // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail - // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt - func main() { - var bucket, key string - var timeout time.Duration - - flag.StringVar(&bucket, "b", "", "Bucket name.") - flag.StringVar(&key, "k", "", "Object key name.") - flag.DurationVar(&timeout, "d", 0, "Upload timeout.") - flag.Parse() - - // All clients require a Session. The Session provides the client with - // shared configuration such as region, endpoint, and credentials. A - // Session should be shared where possible to take advantage of - // configuration and credential caching. See the session package for - // more information. - sess := session.Must(session.NewSession()) - - // Create a new instance of the service's client with a Session. - // Optional aws.Config values can also be provided as variadic arguments - // to the New function. This option allows you to provide service - // specific configuration. - svc := s3.New(sess) - - // Create a context with a timeout that will abort the upload if it takes - // more than the passed in timeout. - ctx := context.Background() - var cancelFn func() - if timeout > 0 { - ctx, cancelFn = context.WithTimeout(ctx, timeout) - } - // Ensure the context is canceled to prevent leaking. - // See context package for more information, https://golang.org/pkg/context/ - defer cancelFn() - - // Uploads the object to S3. The Context will interrupt the request if the - // timeout expires. - _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ - Bucket: aws.String(bucket), - Key: aws.String(key), - Body: os.Stdin, - }) - if err != nil { - if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { - // If the SDK can determine the request or retry delay was canceled - // by a context the CanceledErrorCode error code will be returned. - fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) - } else { - fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) - } - os.Exit(1) - } - - fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) - } -``` - -## License - -This SDK is distributed under the -[Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0), -see LICENSE.txt and NOTICE.txt for more information. diff --git a/vendor/github.com/aws/aws-sdk-go/buildspec.yml b/vendor/github.com/aws/aws-sdk-go/buildspec.yml deleted file mode 100644 index 2defb7f..0000000 --- a/vendor/github.com/aws/aws-sdk-go/buildspec.yml +++ /dev/null @@ -1,21 +0,0 @@ -version: 0.2 - -phases: - build: - commands: - - echo Build started on `date` - - export GOPATH=/go - - export SDK_CB_ROOT=`pwd` - - export SDK_GO_ROOT=/go/src/github.com/aws/aws-sdk-go - - mkdir -p /go/src/github.com/aws - - ln -s $SDK_CB_ROOT $SDK_GO_ROOT - - cd $SDK_GO_ROOT - - make ci-test - - cd $SDK_CB_ROOT - - #echo Compiling the Go code... - post_build: - commands: - - echo Build completed on `date` -#artifacts: -# files: -# - hello diff --git a/vendor/github.com/aws/aws-sdk-go/doc.go b/vendor/github.com/aws/aws-sdk-go/doc.go deleted file mode 100644 index 32b806a..0000000 --- a/vendor/github.com/aws/aws-sdk-go/doc.go +++ /dev/null @@ -1,405 +0,0 @@ -// Package sdk is the official AWS SDK for the Go programming language. -// -// The AWS SDK for Go provides APIs and utilities that developers can use to -// build Go applications that use AWS services, such as Amazon Elastic Compute -// Cloud (Amazon EC2) and Amazon Simple Storage Service (Amazon S3). -// -// The SDK removes the complexity of coding directly against a web service -// interface. It hides a lot of the lower-level plumbing, such as authentication, -// request retries, and error handling. -// -// The SDK also includes helpful utilities on top of the AWS APIs that add additional -// capabilities and functionality. For example, the Amazon S3 Download and Upload -// Manager will automatically split up large objects into multiple parts and -// transfer them concurrently. -// -// See the s3manager package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/ -// -// Getting More Information -// -// Checkout the Getting Started Guide and API Reference Docs detailed the SDK's -// components and details on each AWS client the SDK supports. -// -// The Getting Started Guide provides examples and detailed description of how -// to get setup with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/welcome.html -// -// The API Reference Docs include a detailed breakdown of the SDK's components -// such as utilities and AWS clients. Use this as a reference of the Go types -// included with the SDK, such as AWS clients, API operations, and API parameters. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// Overview of SDK's Packages -// -// The SDK is composed of two main components, SDK core, and service clients. -// The SDK core packages are all available under the aws package at the root of -// the SDK. Each client for a supported AWS service is available within its own -// package under the service folder at the root of the SDK. -// -// * aws - SDK core, provides common shared types such as Config, Logger, -// and utilities to make working with API parameters easier. -// -// * awserr - Provides the error interface that the SDK will use for all -// errors that occur in the SDK's processing. This includes service API -// response errors as well. The Error type is made up of a code and message. -// Cast the SDK's returned error type to awserr.Error and call the Code -// method to compare returned error to specific error codes. See the package's -// documentation for additional values that can be extracted such as RequestId. -// -// * credentials - Provides the types and built in credentials providers -// the SDK will use to retrieve AWS credentials to make API requests with. -// Nested under this folder are also additional credentials providers such as -// stscreds for assuming IAM roles, and ec2rolecreds for EC2 Instance roles. -// -// * endpoints - Provides the AWS Regions and Endpoints metadata for the SDK. -// Use this to lookup AWS service endpoint information such as which services -// are in a region, and what regions a service is in. Constants are also provided -// for all region identifiers, e.g UsWest2RegionID for "us-west-2". -// -// * session - Provides initial default configuration, and load -// configuration from external sources such as environment and shared -// credentials file. -// -// * request - Provides the API request sending, and retry logic for the SDK. -// This package also includes utilities for defining your own request -// retryer, and configuring how the SDK processes the request. -// -// * service - Clients for AWS services. All services supported by the SDK are -// available under this folder. -// -// How to Use the SDK's AWS Service Clients -// -// The SDK includes the Go types and utilities you can use to make requests to -// AWS service APIs. Within the service folder at the root of the SDK you'll find -// a package for each AWS service the SDK supports. All service clients follows -// a common pattern of creation and usage. -// -// When creating a client for an AWS service you'll first need to have a Session -// value constructed. The Session provides shared configuration that can be shared -// between your service clients. When service clients are created you can pass -// in additional configuration via the aws.Config type to override configuration -// provided by in the Session to create service client instances with custom -// configuration. -// -// Once the service's client is created you can use it to make API requests the -// AWS service. These clients are safe to use concurrently. -// -// Configuring the SDK -// -// In the AWS SDK for Go, you can configure settings for service clients, such -// as the log level and maximum number of retries. Most settings are optional; -// however, for each service client, you must specify a region and your credentials. -// The SDK uses these values to send requests to the correct AWS region and sign -// requests with the correct credentials. You can specify these values as part -// of a session or as environment variables. -// -// See the SDK's configuration guide for more information. -// https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html -// -// See the session package documentation for more information on how to use Session -// with the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/session/ -// -// See the Config type in the aws package for more information on configuration -// options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Configuring Credentials -// -// When using the SDK you'll generally need your AWS credentials to authenticate -// with AWS services. The SDK supports multiple methods of supporting these -// credentials. By default the SDK will source credentials automatically from -// its default credential chain. See the session package for more information -// on this chain, and how to configure it. The common items in the credential -// chain are the following: -// -// * Environment Credentials - Set of environment variables that are useful -// when sub processes are created for specific roles. -// -// * Shared Credentials file (~/.aws/credentials) - This file stores your -// credentials based on a profile name and is useful for local development. -// -// * EC2 Instance Role Credentials - Use EC2 Instance Role to assign credentials -// to application running on an EC2 instance. This removes the need to manage -// credential files in production. -// -// Credentials can be configured in code as well by setting the Config's Credentials -// value to a custom provider or using one of the providers included with the -// SDK to bypass the default credential chain and use a custom one. This is -// helpful when you want to instruct the SDK to only use a specific set of -// credentials or providers. -// -// This example creates a credential provider for assuming an IAM role, "myRoleARN" -// and configures the S3 service client to use that role for API requests. -// -// // 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})/ -// -// See the credentials package documentation for more information on credential -// providers included with the SDK, and how to customize the SDK's usage of -// credentials. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/credentials -// -// The SDK has support for the shared configuration file (~/.aws/config). This -// support can be enabled by setting the environment variable, "AWS_SDK_LOAD_CONFIG=1", -// or enabling the feature in code when creating a Session via the -// Option's SharedConfigState parameter. -// -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -// -// Configuring AWS Region -// -// In addition to the credentials you'll need to specify the region the SDK -// will use to make AWS API requests to. In the SDK you can specify the region -// either with an environment variable, or directly in code when a Session or -// service client is created. The last value specified in code wins if the region -// is specified multiple ways. -// -// To set the region via the environment variable set the "AWS_REGION" to the -// region you want to the SDK to use. Using this method to set the region will -// allow you to run your application in multiple regions without needing additional -// code in the application to select the region. -// -// AWS_REGION=us-west-2 -// -// The endpoints package includes constants for all regions the SDK knows. The -// values are all suffixed with RegionID. These values are helpful, because they -// reduce the need to type the region string manually. -// -// To set the region on a Session use the aws package's Config struct parameter -// Region to the AWS region you want the service clients created from the session to -// use. This is helpful when you want to create multiple service clients, and -// all of the clients make API requests to the same region. -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String(endpoints.UsWest2RegionID), -// })) -// -// See the endpoints package for the AWS Regions and Endpoints metadata. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/endpoints/ -// -// In addition to setting the region when creating a Session you can also set -// the region on a per service client bases. This overrides the region of a -// Session. This is helpful when you want to create service clients in specific -// regions different from the Session's region. -// -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String(endpoints.UsWest2RegionID), -// }) -// -// See the Config type in the aws package for more information and additional -// options such as setting the Endpoint, and other service client configuration options. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// Making API Requests -// -// Once the client is created you can make an API request to the service. -// Each API method takes a input parameter, and returns the service response -// and an error. The SDK provides methods for making the API call in multiple ways. -// -// In this list we'll use the S3 ListObjects API as an example for the different -// ways of making API requests. -// -// * ListObjects - Base API operation that will make the API request to the service. -// -// * ListObjectsRequest - API methods suffixed with Request will construct the -// API request, but not send it. This is also helpful when you want to get a -// presigned URL for a request, and share the presigned URL instead of your -// application making the request directly. -// -// * ListObjectsPages - Same as the base API operation, but uses a callback to -// automatically handle pagination of the API's response. -// -// * ListObjectsWithContext - Same as base API operation, but adds support for -// the Context pattern. This is helpful for controlling the canceling of in -// flight requests. See the Go standard library context package for more -// information. This method also takes request package's Option functional -// options as the variadic argument for modifying how the request will be -// made, or extracting information from the raw HTTP response. -// -// * ListObjectsPagesWithContext - same as ListObjectsPages, but adds support for -// the Context pattern. Similar to ListObjectsWithContext this method also -// takes the request package's Option function option types as the variadic -// argument. -// -// In addition to the API operations the SDK also includes several higher level -// methods that abstract checking for and waiting for an AWS resource to be in -// a desired state. In this list we'll use WaitUntilBucketExists to demonstrate -// the different forms of waiters. -// -// * WaitUntilBucketExists. - Method to make API request to query an AWS service for -// a resource's state. Will return successfully when that state is accomplished. -// -// * WaitUntilBucketExistsWithContext - Same as WaitUntilBucketExists, but adds -// support for the Context pattern. In addition these methods take request -// package's WaiterOptions to configure the waiter, and how underlying request -// will be made by the SDK. -// -// The API method will document which error codes the service might return for -// the operation. These errors will also be available as const strings prefixed -// with "ErrCode" in the service client's package. If there are no errors listed -// in the API's SDK documentation you'll need to consult the AWS service's API -// documentation for the errors that could be returned. -// -// ctx := context.Background() -// -// result, err := svc.GetObjectWithContext(ctx, &s3.GetObjectInput{ -// Bucket: aws.String("my-bucket"), -// Key: aws.String("my-key"), -// }) -// if err != nil { -// // Cast err to awserr.Error to handle specific error codes. -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == s3.ErrCodeNoSuchKey { -// // Specific error code handling -// } -// return err -// } -// -// // Make sure to close the body when done with it for S3 GetObject APIs or -// // will leak connections. -// defer result.Body.Close() -// -// fmt.Println("Object Size:", aws.StringValue(result.ContentLength)) -// -// API Request Pagination and Resource Waiters -// -// Pagination helper methods are suffixed with "Pages", and provide the -// functionality needed to round trip API page requests. Pagination methods -// take a callback function that will be called for each page of the API's response. -// -// objects := []string{} -// err := svc.ListObjectsPagesWithContext(ctx, &s3.ListObjectsInput{ -// Bucket: aws.String(myBucket), -// }, func(p *s3.ListObjectsOutput, lastPage bool) bool { -// for _, o := range p.Contents { -// objects = append(objects, aws.StringValue(o.Key)) -// } -// return true // continue paging -// }) -// if err != nil { -// panic(fmt.Sprintf("failed to list objects for bucket, %s, %v", myBucket, err)) -// } -// -// fmt.Println("Objects in bucket:", objects) -// -// Waiter helper methods provide the functionality to wait for an AWS resource -// state. These methods abstract the logic needed to to check the state of an -// AWS resource, and wait until that resource is in a desired state. The waiter -// will block until the resource is in the state that is desired, an error occurs, -// or the waiter times out. If a resource times out the error code returned will -// be request.WaiterResourceNotReadyErrorCode. -// -// err := svc.WaitUntilBucketExistsWithContext(ctx, &s3.HeadBucketInput{ -// Bucket: aws.String(myBucket), -// }) -// if err != nil { -// aerr, ok := err.(awserr.Error) -// if ok && aerr.Code() == request.WaiterResourceNotReadyErrorCode { -// fmt.Fprintf(os.Stderr, "timed out while waiting for bucket to exist") -// } -// panic(fmt.Errorf("failed to wait for bucket to exist, %v", err)) -// } -// fmt.Println("Bucket", myBucket, "exists") -// -// Complete SDK Example -// -// This example shows a complete working Go file which will upload a file to S3 -// and use the Context pattern to implement timeout logic that will cancel the -// request if it takes too long. This example highlights how to use sessions, -// create a service client, make a request, handle the error, and process the -// response. -// -// package main -// -// import ( -// "context" -// "flag" -// "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/request" -// "github.com/aws/aws-sdk-go/aws/session" -// "github.com/aws/aws-sdk-go/service/s3" -// ) -// -// // Uploads a file to S3 given a bucket and object key. Also takes a duration -// // value to terminate the update if it doesn't complete within that time. -// // -// // The AWS Region needs to be provided in the AWS shared config or on the -// // environment variable as `AWS_REGION`. Credentials also must be provided -// // Will default to shared config file, but can load from environment if provided. -// // -// // Usage: -// // # Upload myfile.txt to myBucket/myKey. Must complete within 10 minutes or will fail -// // go run withContext.go -b mybucket -k myKey -d 10m < myfile.txt -// func main() { -// var bucket, key string -// var timeout time.Duration -// -// flag.StringVar(&bucket, "b", "", "Bucket name.") -// flag.StringVar(&key, "k", "", "Object key name.") -// flag.DurationVar(&timeout, "d", 0, "Upload timeout.") -// flag.Parse() -// -// // All clients require a Session. The Session provides the client with -// // shared configuration such as region, endpoint, and credentials. A -// // Session should be shared where possible to take advantage of -// // configuration and credential caching. See the session package for -// // more information. -// sess := session.Must(session.NewSession()) -// -// // Create a new instance of the service's client with a Session. -// // Optional aws.Config values can also be provided as variadic arguments -// // to the New function. This option allows you to provide service -// // specific configuration. -// svc := s3.New(sess) -// -// // Create a context with a timeout that will abort the upload if it takes -// // more than the passed in timeout. -// ctx := context.Background() -// var cancelFn func() -// if timeout > 0 { -// ctx, cancelFn = context.WithTimeout(ctx, timeout) -// } -// // Ensure the context is canceled to prevent leaking. -// // See context package for more information, https://golang.org/pkg/context/ -// defer cancelFn() -// -// // Uploads the object to S3. The Context will interrupt the request if the -// // timeout expires. -// _, err := svc.PutObjectWithContext(ctx, &s3.PutObjectInput{ -// Bucket: aws.String(bucket), -// Key: aws.String(key), -// Body: os.Stdin, -// }) -// if err != nil { -// if aerr, ok := err.(awserr.Error); ok && aerr.Code() == request.CanceledErrorCode { -// // If the SDK can determine the request or retry delay was canceled -// // by a context the CanceledErrorCode error code will be returned. -// fmt.Fprintf(os.Stderr, "upload canceled due to timeout, %v\n", err) -// } else { -// fmt.Fprintf(os.Stderr, "failed to upload object, %v\n", err) -// } -// os.Exit(1) -// } -// -// fmt.Printf("successfully uploaded file to %s/%s\n", bucket, key) -// } -package sdk diff --git a/vendor/github.com/aws/aws-sdk-go/go.mod b/vendor/github.com/aws/aws-sdk-go/go.mod deleted file mode 100644 index 329c3ea..0000000 --- a/vendor/github.com/aws/aws-sdk-go/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/aws/aws-sdk-go - -require github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af diff --git a/vendor/github.com/aws/aws-sdk-go/go.sum b/vendor/github.com/aws/aws-sdk-go/go.sum deleted file mode 100644 index d07bf6d..0000000 --- a/vendor/github.com/aws/aws-sdk-go/go.sum +++ /dev/null @@ -1,2 +0,0 @@ -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= -github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/default_value_decoders.go b/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/default_value_decoders.go deleted file mode 100644 index 71f6fdb..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/default_value_decoders.go +++ /dev/null @@ -1,822 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package bsoncodec - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "net/url" - "reflect" - "strconv" - "time" - - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" -) - -var defaultValueDecoders DefaultValueDecoders - -// DefaultValueDecoders is a namespace type for the default ValueDecoders used -// when creating a registry. -type DefaultValueDecoders struct{} - -// RegisterDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with -// the provided RegistryBuilder. -// -// There is no support for decoding map[string]interface{} becuase there is no decoder for -// interface{}, so users must either register this decoder themselves or use the -// EmptyInterfaceDecoder avaialble in the bson package. -func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder) { - if rb == nil { - panic(errors.New("argument to RegisterDefaultDecoders must not be nil")) - } - - rb. - RegisterDecoder(reflect.PtrTo(tByteSlice), ValueDecoderFunc(dvd.ByteSliceDecodeValue)). - RegisterDecoder(reflect.PtrTo(tTime), ValueDecoderFunc(dvd.TimeDecodeValue)). - RegisterDecoder(reflect.PtrTo(tEmpty), ValueDecoderFunc(dvd.EmptyInterfaceDecodeValue)). - RegisterDecoder(reflect.PtrTo(tOID), ValueDecoderFunc(dvd.ObjectIDDecodeValue)). - RegisterDecoder(reflect.PtrTo(tDecimal), ValueDecoderFunc(dvd.Decimal128DecodeValue)). - RegisterDecoder(reflect.PtrTo(tJSONNumber), ValueDecoderFunc(dvd.JSONNumberDecodeValue)). - RegisterDecoder(reflect.PtrTo(tURL), ValueDecoderFunc(dvd.URLDecodeValue)). - RegisterDecoder(tValueUnmarshaler, ValueDecoderFunc(dvd.ValueUnmarshalerDecodeValue)). - RegisterDefaultDecoder(reflect.Bool, ValueDecoderFunc(dvd.BooleanDecodeValue)). - RegisterDefaultDecoder(reflect.Int, ValueDecoderFunc(dvd.IntDecodeValue)). - RegisterDefaultDecoder(reflect.Int8, ValueDecoderFunc(dvd.IntDecodeValue)). - RegisterDefaultDecoder(reflect.Int16, ValueDecoderFunc(dvd.IntDecodeValue)). - RegisterDefaultDecoder(reflect.Int32, ValueDecoderFunc(dvd.IntDecodeValue)). - RegisterDefaultDecoder(reflect.Int64, ValueDecoderFunc(dvd.IntDecodeValue)). - RegisterDefaultDecoder(reflect.Uint, ValueDecoderFunc(dvd.UintDecodeValue)). - RegisterDefaultDecoder(reflect.Uint8, ValueDecoderFunc(dvd.UintDecodeValue)). - RegisterDefaultDecoder(reflect.Uint16, ValueDecoderFunc(dvd.UintDecodeValue)). - RegisterDefaultDecoder(reflect.Uint32, ValueDecoderFunc(dvd.UintDecodeValue)). - RegisterDefaultDecoder(reflect.Uint64, ValueDecoderFunc(dvd.UintDecodeValue)). - RegisterDefaultDecoder(reflect.Float32, ValueDecoderFunc(dvd.FloatDecodeValue)). - RegisterDefaultDecoder(reflect.Float64, ValueDecoderFunc(dvd.FloatDecodeValue)). - RegisterDefaultDecoder(reflect.Array, ValueDecoderFunc(dvd.SliceDecodeValue)). - RegisterDefaultDecoder(reflect.Map, ValueDecoderFunc(dvd.MapDecodeValue)). - RegisterDefaultDecoder(reflect.Slice, ValueDecoderFunc(dvd.SliceDecodeValue)). - RegisterDefaultDecoder(reflect.String, ValueDecoderFunc(dvd.StringDecodeValue)). - RegisterDefaultDecoder(reflect.Struct, &StructCodec{cache: make(map[reflect.Type]*structDescription), parser: DefaultStructTagParser}) -} - -// BooleanDecodeValue is the ValueDecoderFunc for bool types. -func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Boolean { - return fmt.Errorf("cannot decode %v into a boolean", vr.Type()) - } - - var err error - if target, ok := i.(*bool); ok && target != nil { // if it is nil, we go the slow path. - *target, err = vr.ReadBoolean() - return err - } - - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || !val.Elem().CanSet() { - return errors.New("BooleanDecodeValue can only be used to decode settable (non-nil) values") - } - val = val.Elem() - if val.Type().Kind() != reflect.Bool { - return ValueDecoderError{Name: "BooleanDecodeValue", Types: []interface{}{bool(true)}, Received: i} - } - - b, err := vr.ReadBoolean() - val.SetBool(b) - return err -} - -// IntDecodeValue is the ValueDecoderFunc for bool types. -func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - var i64 int64 - var err error - switch vr.Type() { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return err - } - i64 = int64(i32) - case bsontype.Int64: - i64, err = vr.ReadInt64() - if err != nil { - return err - } - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return err - } - if !dc.Truncate && math.Floor(f64) != f64 { - return errors.New("IntDecodeValue can only truncate float64 to an integer type when truncation is enabled") - } - if f64 > float64(math.MaxInt64) { - return fmt.Errorf("%g overflows int64", f64) - } - i64 = int64(f64) - default: - return fmt.Errorf("cannot decode %v into an integer type", vr.Type()) - } - - switch target := i.(type) { - case *int8: - if target == nil { - return errors.New("IntDecodeValue can only be used to decode non-nil *int8") - } - if i64 < math.MinInt8 || i64 > math.MaxInt8 { - return fmt.Errorf("%d overflows int8", i64) - } - *target = int8(i64) - return nil - case *int16: - if target == nil { - return errors.New("IntDecodeValue can only be used to decode non-nil *int16") - } - if i64 < math.MinInt16 || i64 > math.MaxInt16 { - return fmt.Errorf("%d overflows int16", i64) - } - *target = int16(i64) - return nil - case *int32: - if target == nil { - return errors.New("IntDecodeValue can only be used to decode non-nil *int32") - } - if i64 < math.MinInt32 || i64 > math.MaxInt32 { - return fmt.Errorf("%d overflows int32", i64) - } - *target = int32(i64) - return nil - case *int64: - if target == nil { - return errors.New("IntDecodeValue can only be used to decode non-nil *int64") - } - *target = int64(i64) - return nil - case *int: - if target == nil { - return errors.New("IntDecodeValue can only be used to decode non-nil *int") - } - if int64(int(i64)) != i64 { // Can we fit this inside of an int - return fmt.Errorf("%d overflows int", i64) - } - *target = int(i64) - return nil - } - - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || !val.Elem().CanSet() { - return fmt.Errorf("IntDecodeValue can only be used to decode settable (non-nil) values") - } - val = val.Elem() - - switch val.Type().Kind() { - case reflect.Int8: - if i64 < math.MinInt8 || i64 > math.MaxInt8 { - return fmt.Errorf("%d overflows int8", i64) - } - case reflect.Int16: - if i64 < math.MinInt16 || i64 > math.MaxInt16 { - return fmt.Errorf("%d overflows int16", i64) - } - case reflect.Int32: - if i64 < math.MinInt32 || i64 > math.MaxInt32 { - return fmt.Errorf("%d overflows int32", i64) - } - case reflect.Int64: - case reflect.Int: - if int64(int(i64)) != i64 { // Can we fit this inside of an int - return fmt.Errorf("%d overflows int", i64) - } - default: - return ValueDecoderError{ - Name: "IntDecodeValue", - Types: []interface{}{(*int8)(nil), (*int16)(nil), (*int32)(nil), (*int64)(nil), (*int)(nil)}, - Received: i, - } - } - - val.SetInt(i64) - return nil -} - -// UintDecodeValue is the ValueDecoderFunc for uint types. -func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - var i64 int64 - var err error - switch vr.Type() { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return err - } - i64 = int64(i32) - case bsontype.Int64: - i64, err = vr.ReadInt64() - if err != nil { - return err - } - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return err - } - if !dc.Truncate && math.Floor(f64) != f64 { - return errors.New("UintDecodeValue can only truncate float64 to an integer type when truncation is enabled") - } - if f64 > float64(math.MaxInt64) { - return fmt.Errorf("%g overflows int64", f64) - } - i64 = int64(f64) - default: - return fmt.Errorf("cannot decode %v into an integer type", vr.Type()) - } - - switch target := i.(type) { - case *uint8: - if target == nil { - return errors.New("UintDecodeValue can only be used to decode non-nil *uint8") - } - if i64 < 0 || i64 > math.MaxUint8 { - return fmt.Errorf("%d overflows uint8", i64) - } - *target = uint8(i64) - return nil - case *uint16: - if target == nil { - return errors.New("UintDecodeValue can only be used to decode non-nil *uint16") - } - if i64 < 0 || i64 > math.MaxUint16 { - return fmt.Errorf("%d overflows uint16", i64) - } - *target = uint16(i64) - return nil - case *uint32: - if target == nil { - return errors.New("UintDecodeValue can only be used to decode non-nil *uint32") - } - if i64 < 0 || i64 > math.MaxUint32 { - return fmt.Errorf("%d overflows uint32", i64) - } - *target = uint32(i64) - return nil - case *uint64: - if target == nil { - return errors.New("UintDecodeValue can only be used to decode non-nil *uint64") - } - if i64 < 0 { - return fmt.Errorf("%d overflows uint64", i64) - } - *target = uint64(i64) - return nil - case *uint: - if target == nil { - return errors.New("UintDecodeValue can only be used to decode non-nil *uint") - } - if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint - return fmt.Errorf("%d overflows uint", i64) - } - *target = uint(i64) - return nil - } - - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || !val.Elem().CanSet() { - return errors.New("UintDecodeValue can only be used to decode settable (non-nil) values") - } - val = val.Elem() - - switch val.Type().Kind() { - case reflect.Uint8: - if i64 < 0 || i64 > math.MaxUint8 { - return fmt.Errorf("%d overflows uint8", i64) - } - case reflect.Uint16: - if i64 < 0 || i64 > math.MaxUint16 { - return fmt.Errorf("%d overflows uint16", i64) - } - case reflect.Uint32: - if i64 < 0 || i64 > math.MaxUint32 { - return fmt.Errorf("%d overflows uint32", i64) - } - case reflect.Uint64: - if i64 < 0 { - return fmt.Errorf("%d overflows uint64", i64) - } - case reflect.Uint: - if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint - return fmt.Errorf("%d overflows uint", i64) - } - default: - return ValueDecoderError{ - Name: "UintDecodeValue", - Types: []interface{}{(*uint8)(nil), (*uint16)(nil), (*uint32)(nil), (*uint64)(nil), (*uint)(nil)}, - Received: i, - } - } - - val.SetUint(uint64(i64)) - return nil -} - -// FloatDecodeValue is the ValueDecoderFunc for float types. -func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - var f float64 - var err error - switch vr.Type() { - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return err - } - f = float64(i32) - case bsontype.Int64: - i64, err := vr.ReadInt64() - if err != nil { - return err - } - f = float64(i64) - case bsontype.Double: - f, err = vr.ReadDouble() - if err != nil { - return err - } - default: - return fmt.Errorf("cannot decode %v into a float32 or float64 type", vr.Type()) - } - - switch target := i.(type) { - case *float32: - if target == nil { - return errors.New("FloatDecodeValue can only be used to decode non-nil *float32") - } - if !ec.Truncate && float64(float32(f)) != f { - return errors.New("FloatDecodeValue can only convert float64 to float32 when truncation is allowed") - } - *target = float32(f) - return nil - case *float64: - if target == nil { - return errors.New("FloatDecodeValue can only be used to decode non-nil *float64") - } - *target = f - return nil - } - - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || !val.Elem().CanSet() { - return errors.New("FloatDecodeValue can only be used to decode settable (non-nil) values") - } - val = val.Elem() - - switch val.Type().Kind() { - case reflect.Float32: - if !ec.Truncate && float64(float32(f)) != f { - return errors.New("FloatDecodeValue can only convert float64 to float32 when truncation is allowed") - } - case reflect.Float64: - default: - return ValueDecoderError{Name: "FloatDecodeValue", Types: []interface{}{(*float32)(nil), (*float64)(nil)}, Received: i} - } - - val.SetFloat(f) - return nil -} - -// StringDecodeValue is the ValueDecoderFunc for string types. -func (dvd DefaultValueDecoders) StringDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - var str string - var err error - switch vr.Type() { - // TODO(GODRIVER-577): Handle JavaScript and Symbol BSON types when allowed. - case bsontype.String: - str, err = vr.ReadString() - if err != nil { - return err - } - default: - return fmt.Errorf("cannot decode %v into a string type", vr.Type()) - } - - switch t := i.(type) { - case *string: - if t == nil { - return errors.New("StringDecodeValue can only be used to decode non-nil *string") - } - *t = str - return nil - } - - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || !val.Elem().CanSet() { - return errors.New("StringDecodeValue can only be used to decode settable (non-nil) values") - } - val = val.Elem() - - if val.Type().Kind() != reflect.String { - return ValueDecoderError{ - Name: "StringDecodeValue", - Types: []interface{}{(*string)(nil)}, - Received: i, - } - } - - val.SetString(str) - return nil -} - -// ObjectIDDecodeValue is the ValueDecoderFunc for objectid.ObjectID. -func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.ObjectID { - return fmt.Errorf("cannot decode %v into an ObjectID", vr.Type()) - } - - target, ok := i.(*objectid.ObjectID) - if !ok || target == nil { - return ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []interface{}{(*objectid.ObjectID)(nil)}, Received: i} - } - - oid, err := vr.ReadObjectID() - if err != nil { - return err - } - - *target = oid - return nil -} - -// Decimal128DecodeValue is the ValueDecoderFunc for decimal.Decimal128. -func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Decimal128 { - return fmt.Errorf("cannot decode %v into a decimal.Decimal128", vr.Type()) - } - - target, ok := i.(*decimal.Decimal128) - if !ok || target == nil { - return ValueDecoderError{Name: "Decimal128DecodeValue", Types: []interface{}{(*decimal.Decimal128)(nil)}, Received: i} - } - - d128, err := vr.ReadDecimal128() - if err != nil { - return err - } - - *target = d128 - return nil -} - -// JSONNumberDecodeValue is the ValueDecoderFunc for json.Number. -func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - target, ok := i.(*json.Number) - if !ok || target == nil { - return ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []interface{}{(*json.Number)(nil)}, Received: i} - } - - switch vr.Type() { - case bsontype.Double: - f64, err := vr.ReadDouble() - if err != nil { - return err - } - *target = json.Number(strconv.FormatFloat(f64, 'g', -1, 64)) - case bsontype.Int32: - i32, err := vr.ReadInt32() - if err != nil { - return err - } - *target = json.Number(strconv.FormatInt(int64(i32), 10)) - case bsontype.Int64: - i64, err := vr.ReadInt64() - if err != nil { - return err - } - *target = json.Number(strconv.FormatInt(i64, 10)) - default: - return fmt.Errorf("cannot decode %v into a json.Number", vr.Type()) - } - - return nil -} - -// URLDecodeValue is the ValueDecoderFunc for url.URL. -func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.String { - return fmt.Errorf("cannot decode %v into a *url.URL", vr.Type()) - } - - str, err := vr.ReadString() - if err != nil { - return err - } - - u, err := url.Parse(str) - if err != nil { - return err - } - - err = ValueDecoderError{Name: "URLDecodeValue", Types: []interface{}{(*url.URL)(nil), (**url.URL)(nil)}, Received: i} - - // It's valid to use either a *url.URL or a url.URL - switch target := i.(type) { - case *url.URL: - if target == nil { - return err - } - *target = *u - case **url.URL: - if target == nil { - return err - } - *target = u - default: - return err - } - return nil -} - -// TimeDecodeValue is the ValueDecoderFunc for time.Time. -func (dvd DefaultValueDecoders) TimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.DateTime { - return fmt.Errorf("cannot decode %v into a time.Time", vr.Type()) - } - - dt, err := vr.ReadDateTime() - if err != nil { - return err - } - - if target, ok := i.(*time.Time); ok && target != nil { - *target = time.Unix(dt/1000, dt%1000*1000000) - return nil - } - - if target, ok := i.(**time.Time); ok && target != nil { - tt := *target - if tt == nil { - tt = new(time.Time) - } - *tt = time.Unix(dt/1000, dt%1000*1000000) - *target = tt - return nil - } - - return ValueDecoderError{ - Name: "TimeDecodeValue", - Types: []interface{}{(*time.Time)(nil), (**time.Time)(nil)}, - Received: i, - } -} - -// ByteSliceDecodeValue is the ValueDecoderFunc for []byte. -func (dvd DefaultValueDecoders) ByteSliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Binary { - return fmt.Errorf("cannot decode %v into a *[]byte", vr.Type()) - } - - target, ok := i.(*[]byte) - if !ok || target == nil { - return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []interface{}{(*[]byte)(nil)}, Received: i} - } - - data, subtype, err := vr.ReadBinary() - if err != nil { - return err - } - if subtype != 0x00 { - return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 for %s, got %v", bsontype.Binary, subtype) - } - - *target = data - return nil -} - -// MapDecodeValue is the ValueDecoderFunc for map[string]* types. -func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() { - return fmt.Errorf("MapDecodeValue can only be used to decode non-nil pointers to map values, got %T", i) - } - - if val.Elem().Kind() != reflect.Map || val.Elem().Type().Key().Kind() != reflect.String || !val.Elem().CanSet() { - return errors.New("MapDecodeValue can only decode settable maps with string keys") - } - - dr, err := vr.ReadDocument() - if err != nil { - return err - } - - if val.Elem().IsNil() { - val.Elem().Set(reflect.MakeMap(val.Elem().Type())) - } - - mVal := val.Elem() - - eType := mVal.Type().Elem() - decoder, err := dc.LookupDecoder(eType) - if err != nil { - return err - } - - for { - key, vr, err := dr.ReadElement() - if err == bsonrw.ErrEOD { - break - } - if err != nil { - return err - } - - ptr := reflect.New(eType) - - err = decoder.DecodeValue(dc, vr, ptr.Interface()) - if err != nil { - return err - } - - mVal.SetMapIndex(reflect.ValueOf(key), ptr.Elem()) - } - return err -} - -// SliceDecodeValue is the ValueDecoderFunc for []* types. -func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - val := reflect.ValueOf(i) - if !val.IsValid() || val.Kind() != reflect.Ptr || val.IsNil() { - return fmt.Errorf("SliceDecodeValue can only be used to decode non-nil pointers to slice or array values, got %T", i) - } - - switch val.Elem().Kind() { - case reflect.Slice, reflect.Array: - if !val.Elem().CanSet() { - return errors.New("SliceDecodeValue can only decode settable slice and array values") - } - default: - return fmt.Errorf("SliceDecodeValue can only decode settable slice and array values, got %T", i) - } - - switch vr.Type() { - case bsontype.Array: - case bsontype.Null: - if val.Elem().Kind() != reflect.Slice { - return fmt.Errorf("cannot decode %v into an array", vr.Type()) - } - null := reflect.Zero(val.Elem().Type()) - val.Elem().Set(null) - return vr.ReadNull() - default: - return fmt.Errorf("cannot decode %v into a slice", vr.Type()) - } - - eType := val.Type().Elem().Elem() - - ar, err := vr.ReadArray() - if err != nil { - return err - } - - elems, err := dvd.decodeDefault(dc, ar, eType) - if err != nil { - return err - } - - switch val.Elem().Kind() { - case reflect.Slice: - slc := reflect.MakeSlice(val.Elem().Type(), len(elems), len(elems)) - - for idx, elem := range elems { - slc.Index(idx).Set(elem) - } - - val.Elem().Set(slc) - case reflect.Array: - if len(elems) > val.Elem().Len() { - return fmt.Errorf("more elements returned in array than can fit inside %s", val.Elem().Type()) - } - - for idx, elem := range elems { - val.Elem().Index(idx).Set(elem) - } - } - - return nil -} - -// ValueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations. -func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - val := reflect.ValueOf(i) - var valueUnmarshaler ValueUnmarshaler - if val.Kind() == reflect.Ptr && val.IsNil() { - return fmt.Errorf("ValueUnmarshalerDecodeValue can only unmarshal into non-nil ValueUnmarshaler values, got %T", i) - } - if val.Type().Implements(tValueUnmarshaler) { - valueUnmarshaler = val.Interface().(ValueUnmarshaler) - } else if val.Type().Kind() == reflect.Ptr && val.Elem().Type().Implements(tValueUnmarshaler) { - if val.Elem().Kind() == reflect.Ptr && val.Elem().IsNil() { - val.Elem().Set(reflect.New(val.Type().Elem().Elem())) - } - valueUnmarshaler = val.Elem().Interface().(ValueUnmarshaler) - } else { - return fmt.Errorf("ValueUnmarshalerDecodeValue can only handle types or pointers to types that are a ValueUnmarshaler, got %T", i) - } - - t, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) - if err != nil { - return err - } - - return valueUnmarshaler.UnmarshalBSONValue(t, src) -} - -// EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}. -func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - target, ok := i.(*interface{}) - if !ok || target == nil { - return fmt.Errorf("EmptyInterfaceDecodeValue can only be used to decode non-nil *interface{} values, provided type if %T", i) - } - - // fn is a function we call to assign val back to the target, we do this so - // we can keep down on the repeated code in this method. In all of the - // implementations this is a closure, so we don't need to provide the - // target as a parameter. - var fn func() - var val interface{} - var rtype reflect.Type - - switch vr.Type() { - case bsontype.Double: - val = new(float64) - rtype = tFloat64 - fn = func() { *target = *(val.(*float64)) } - case bsontype.String: - val = new(string) - rtype = tString - fn = func() { *target = *(val.(*string)) } - case bsontype.Boolean: - val = new(bool) - rtype = tBool - fn = func() { *target = *(val.(*bool)) } - case bsontype.Int32: - val = new(int32) - rtype = tInt32 - fn = func() { *target = *(val.(*int32)) } - case bsontype.Int64: - val = new(int64) - rtype = tInt64 - fn = func() { *target = *(val.(*int64)) } - case bsontype.Decimal128: - val = new(decimal.Decimal128) - rtype = tDecimal - fn = func() { *target = *(val.(*decimal.Decimal128)) } - default: - return fmt.Errorf("Type %s is not a valid BSON type and has no default Go type to decode into", vr.Type()) - } - - decoder, err := dc.LookupDecoder(rtype) - if err != nil { - return err - } - err = decoder.DecodeValue(dc, vr, val) - if err != nil { - return err - } - - fn() - return nil -} - -func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, ar bsonrw.ArrayReader, eType reflect.Type) ([]reflect.Value, error) { - elems := make([]reflect.Value, 0) - - decoder, err := dc.LookupDecoder(eType) - if err != nil { - return nil, err - } - - for { - vr, err := ar.ReadValue() - if err == bsonrw.ErrEOA { - break - } - if err != nil { - return nil, err - } - - ptr := reflect.New(eType) - - err = decoder.DecodeValue(dc, vr, ptr.Interface()) - if err != nil { - return nil, err - } - elems = append(elems, ptr.Elem()) - } - - return elems, nil -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/default_value_encoders.go b/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/default_value_encoders.go deleted file mode 100644 index 48b5a5b..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/default_value_encoders.go +++ /dev/null @@ -1,491 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package bsoncodec - -import ( - "encoding/json" - "errors" - "fmt" - "math" - "net/url" - "reflect" - "time" - - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" -) - -var defaultValueEncoders DefaultValueEncoders - -// DefaultValueEncoders is a namespace type for the default ValueEncoders used -// when creating a registry. -type DefaultValueEncoders struct{} - -// RegisterDefaultEncoders will register the encoder methods attached to DefaultValueEncoders with -// the provided RegistryBuilder. -func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) { - if rb == nil { - panic(errors.New("argument to RegisterDefaultEncoders must not be nil")) - } - rb. - RegisterEncoder(tByteSlice, ValueEncoderFunc(dve.ByteSliceEncodeValue)). - RegisterEncoder(tTime, ValueEncoderFunc(dve.TimeEncodeValue)). - RegisterEncoder(reflect.PtrTo(tEmpty), ValueEncoderFunc(dve.EmptyInterfaceEncodeValue)). - RegisterEncoder(tOID, ValueEncoderFunc(dve.ObjectIDEncodeValue)). - RegisterEncoder(tDecimal, ValueEncoderFunc(dve.Decimal128EncodeValue)). - RegisterEncoder(tJSONNumber, ValueEncoderFunc(dve.JSONNumberEncodeValue)). - RegisterEncoder(tURL, ValueEncoderFunc(dve.URLEncodeValue)). - RegisterEncoder(tValueMarshaler, ValueEncoderFunc(dve.ValueMarshalerEncodeValue)). - RegisterEncoder(tProxy, ValueEncoderFunc(dve.ProxyEncodeValue)). - RegisterDefaultEncoder(reflect.Bool, ValueEncoderFunc(dve.BooleanEncodeValue)). - RegisterDefaultEncoder(reflect.Int, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int8, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int16, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int32, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Int64, ValueEncoderFunc(dve.IntEncodeValue)). - RegisterDefaultEncoder(reflect.Uint, ValueEncoderFunc(dve.UintEncodeValue)). - RegisterDefaultEncoder(reflect.Uint8, ValueEncoderFunc(dve.UintEncodeValue)). - RegisterDefaultEncoder(reflect.Uint16, ValueEncoderFunc(dve.UintEncodeValue)). - RegisterDefaultEncoder(reflect.Uint32, ValueEncoderFunc(dve.UintEncodeValue)). - RegisterDefaultEncoder(reflect.Uint64, ValueEncoderFunc(dve.UintEncodeValue)). - RegisterDefaultEncoder(reflect.Float32, ValueEncoderFunc(dve.FloatEncodeValue)). - RegisterDefaultEncoder(reflect.Float64, ValueEncoderFunc(dve.FloatEncodeValue)). - RegisterDefaultEncoder(reflect.Array, ValueEncoderFunc(dve.SliceEncodeValue)). - RegisterDefaultEncoder(reflect.Map, ValueEncoderFunc(dve.MapEncodeValue)). - RegisterDefaultEncoder(reflect.Slice, ValueEncoderFunc(dve.SliceEncodeValue)). - RegisterDefaultEncoder(reflect.String, ValueEncoderFunc(dve.StringEncodeValue)). - RegisterDefaultEncoder(reflect.Struct, &StructCodec{cache: make(map[reflect.Type]*structDescription), parser: DefaultStructTagParser}) -} - -// BooleanEncodeValue is the ValueEncoderFunc for bool types. -func (dve DefaultValueEncoders) BooleanEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - b, ok := i.(bool) - if !ok { - if reflect.TypeOf(i).Kind() != reflect.Bool { - return ValueEncoderError{Name: "BooleanEncodeValue", Types: []interface{}{bool(true)}, Received: i} - } - - b = reflect.ValueOf(i).Bool() - } - - return vw.WriteBoolean(b) -} - -// IntEncodeValue is the ValueEncoderFunc for int types. -func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch t := i.(type) { - case int8: - return vw.WriteInt32(int32(t)) - case int16: - return vw.WriteInt32(int32(t)) - case int32: - return vw.WriteInt32(t) - case int64: - if ec.MinSize && t <= math.MaxInt32 { - return vw.WriteInt32(int32(t)) - } - return vw.WriteInt64(t) - case int: - if ec.MinSize && t <= math.MaxInt32 { - return vw.WriteInt32(int32(t)) - } - return vw.WriteInt64(int64(t)) - } - - val := reflect.ValueOf(i) - switch val.Type().Kind() { - case reflect.Int8, reflect.Int16, reflect.Int32: - return vw.WriteInt32(int32(val.Int())) - case reflect.Int, reflect.Int64: - i64 := val.Int() - if ec.MinSize && i64 <= math.MaxInt32 { - return vw.WriteInt32(int32(i64)) - } - return vw.WriteInt64(i64) - } - - return ValueEncoderError{ - Name: "IntEncodeValue", - Types: []interface{}{int8(0), int16(0), int32(0), int64(0), int(0)}, - Received: i, - } -} - -// UintEncodeValue is the ValueEncoderFunc for uint types. -func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch t := i.(type) { - case uint8: - return vw.WriteInt32(int32(t)) - case uint16: - return vw.WriteInt32(int32(t)) - case uint: - if ec.MinSize && t <= math.MaxInt32 { - return vw.WriteInt32(int32(t)) - } - if uint64(t) > math.MaxInt64 { - return fmt.Errorf("%d overflows int64", t) - } - return vw.WriteInt64(int64(t)) - case uint32: - if ec.MinSize && t <= math.MaxInt32 { - return vw.WriteInt32(int32(t)) - } - return vw.WriteInt64(int64(t)) - case uint64: - if ec.MinSize && t <= math.MaxInt32 { - return vw.WriteInt32(int32(t)) - } - if t > math.MaxInt64 { - return fmt.Errorf("%d overflows int64", t) - } - return vw.WriteInt64(int64(t)) - } - - val := reflect.ValueOf(i) - switch val.Type().Kind() { - case reflect.Uint8, reflect.Uint16: - return vw.WriteInt32(int32(val.Uint())) - case reflect.Uint, reflect.Uint32, reflect.Uint64: - u64 := val.Uint() - if ec.MinSize && u64 <= math.MaxInt32 { - return vw.WriteInt32(int32(u64)) - } - if u64 > math.MaxInt64 { - return fmt.Errorf("%d overflows int64", u64) - } - return vw.WriteInt64(int64(u64)) - } - - return ValueEncoderError{ - Name: "UintEncodeValue", - Types: []interface{}{uint8(0), uint16(0), uint32(0), uint64(0), uint(0)}, - Received: i, - } -} - -// FloatEncodeValue is the ValueEncoderFunc for float types. -func (dve DefaultValueEncoders) FloatEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch t := i.(type) { - case float32: - return vw.WriteDouble(float64(t)) - case float64: - return vw.WriteDouble(t) - } - - val := reflect.ValueOf(i) - switch val.Type().Kind() { - case reflect.Float32, reflect.Float64: - return vw.WriteDouble(val.Float()) - } - - return ValueEncoderError{Name: "FloatEncodeValue", Types: []interface{}{float32(0), float64(0)}, Received: i} -} - -// StringEncodeValue is the ValueEncoderFunc for string types. -func (dve DefaultValueEncoders) StringEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch t := i.(type) { - // TODO(GODRIVER-577): Encode strings to either JavaScript or Symbol. - case string: - return vw.WriteString(t) - } - - val := reflect.ValueOf(i) - if val.Type().Kind() != reflect.String { - return ValueEncoderError{ - Name: "StringEncodeValue", - Types: []interface{}{string("")}, - Received: i, - } - } - - return vw.WriteString(val.String()) -} - -// ObjectIDEncodeValue is the ValueEncoderFunc for objectid.ObjectID. -func (dve DefaultValueEncoders) ObjectIDEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var oid objectid.ObjectID - switch t := i.(type) { - case objectid.ObjectID: - oid = t - case *objectid.ObjectID: - if t == nil { - return vw.WriteNull() - } - oid = *t - default: - return ValueEncoderError{ - Name: "ObjectIDEncodeValue", - Types: []interface{}{objectid.ObjectID{}, (*objectid.ObjectID)(nil)}, - Received: i, - } - } - - return vw.WriteObjectID(oid) -} - -// Decimal128EncodeValue is the ValueEncoderFunc for decimal.Decimal128. -func (dve DefaultValueEncoders) Decimal128EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var d128 decimal.Decimal128 - switch t := i.(type) { - case decimal.Decimal128: - d128 = t - case *decimal.Decimal128: - if t == nil { - return vw.WriteNull() - } - d128 = *t - default: - return ValueEncoderError{ - Name: "Decimal128EncodeValue", - Types: []interface{}{decimal.Decimal128{}, (*decimal.Decimal128)(nil)}, - Received: i, - } - } - - return vw.WriteDecimal128(d128) -} - -// JSONNumberEncodeValue is the ValueEncoderFunc for json.Number. -func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var jsnum json.Number - switch t := i.(type) { - case json.Number: - jsnum = t - case *json.Number: - if t == nil { - return vw.WriteNull() - } - jsnum = *t - default: - return ValueEncoderError{ - Name: "JSONNumberEncodeValue", - Types: []interface{}{json.Number(""), (*json.Number)(nil)}, - Received: i, - } - } - - // Attempt int first, then float64 - if i64, err := jsnum.Int64(); err == nil { - return dve.IntEncodeValue(ec, vw, i64) - } - - f64, err := jsnum.Float64() - if err != nil { - return err - } - - return dve.FloatEncodeValue(ec, vw, f64) -} - -// URLEncodeValue is the ValueEncoderFunc for url.URL. -func (dve DefaultValueEncoders) URLEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var u *url.URL - switch t := i.(type) { - case url.URL: - u = &t - case *url.URL: - if t == nil { - return vw.WriteNull() - } - u = t - default: - return ValueEncoderError{ - Name: "URLEncodeValue", - Types: []interface{}{url.URL{}, (*url.URL)(nil)}, - Received: i, - } - } - - return vw.WriteString(u.String()) -} - -// TimeEncodeValue is the ValueEncoderFunc for time.TIme. -func (dve DefaultValueEncoders) TimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var tt time.Time - switch t := i.(type) { - case time.Time: - tt = t - case *time.Time: - if t == nil { - return vw.WriteNull() - } - tt = *t - default: - return ValueEncoderError{ - Name: "TimeEncodeValue", - Types: []interface{}{time.Time{}, (*time.Time)(nil)}, - Received: i, - } - } - - return vw.WriteDateTime(tt.Unix()*1000 + int64(tt.Nanosecond()/1e6)) -} - -// ByteSliceEncodeValue is the ValueEncoderFunc for []byte. -func (dve DefaultValueEncoders) ByteSliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var slcb []byte - switch t := i.(type) { - case []byte: - slcb = t - case *[]byte: - if t == nil { - return vw.WriteNull() - } - slcb = *t - default: - return ValueEncoderError{ - Name: "ByteSliceEncodeValue", - Types: []interface{}{[]byte{}, (*[]byte)(nil)}, - Received: i, - } - } - - return vw.WriteBinary(slcb) -} - -// MapEncodeValue is the ValueEncoderFunc for map[string]* types. -func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - val := reflect.ValueOf(i) - if val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { - return errors.New("MapEncodeValue can only encode maps with string keys") - } - - dw, err := vw.WriteDocument() - if err != nil { - return err - } - - return dve.mapEncodeValue(ec, dw, val, nil) -} - -// mapEncodeValue handles encoding of the values of a map. The collisionFn returns -// true if the provided key exists, this is mainly used for inline maps in the -// struct codec. -func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { - - encoder, err := ec.LookupEncoder(val.Type().Elem()) - if err != nil { - return err - } - - keys := val.MapKeys() - for _, key := range keys { - if collisionFn != nil && collisionFn(key.String()) { - return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key) - } - vw, err := dw.WriteDocumentElement(key.String()) - if err != nil { - return err - } - - err = encoder.EncodeValue(ec, vw, val.MapIndex(key).Interface()) - if err != nil { - return err - } - } - - return dw.WriteDocumentEnd() -} - -// SliceEncodeValue is the ValueEncoderFunc for []* types. -func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - val := reflect.ValueOf(i) - switch val.Kind() { - case reflect.Array: - case reflect.Slice: - if val.IsNil() { // When nil, special case to null - return vw.WriteNull() - } - default: - return errors.New("SliceEncodeValue can only encode arrays and slices") - } - - length := val.Len() - - aw, err := vw.WriteArray() - if err != nil { - return err - } - - // We do this outside of the loop because an array or a slice can only have - // one element type. If it's the empty interface, we'll use the empty - // interface codec. - var encoder ValueEncoder - switch val.Type().Elem() { - // case tElement: - // encoder = ValueEncoderFunc(dve.elementEncodeValue) - default: - encoder, err = ec.LookupEncoder(val.Type().Elem()) - if err != nil { - return err - } - } - for idx := 0; idx < length; idx++ { - vw, err := aw.WriteArrayElement() - if err != nil { - return err - } - - err = encoder.EncodeValue(ec, vw, val.Index(idx).Interface()) - if err != nil { - return err - } - } - - return aw.WriteArrayEnd() -} - -// EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}. -func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - encoder, err := ec.LookupEncoder(reflect.TypeOf(i)) - if err != nil { - return err - } - - return encoder.EncodeValue(ec, vw, i) -} - -// ValueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations. -func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - vm, ok := i.(ValueMarshaler) - if !ok { - return ValueEncoderError{ - Name: "ValueMarshalerEncodeValue", - Types: []interface{}{(ValueMarshaler)(nil)}, - Received: i, - } - } - - t, val, err := vm.MarshalBSONValue() - if err != nil { - return err - } - return bsonrw.Copier{}.CopyValueFromBytes(vw, t, val) -} - -// ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations. -func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - proxy, ok := i.(Proxy) - if !ok { - return ValueEncoderError{ - Name: "ProxyEncodeValue", - Types: []interface{}{(Proxy)(nil)}, - Received: i, - } - } - - val, err := proxy.ProxyBSON() - if err != nil { - return err - } - encoder, err := ec.LookupEncoder(reflect.TypeOf(val)) - if err != nil { - return err - } - return encoder.EncodeValue(ec, vw, val) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/mode.go b/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/mode.go deleted file mode 100644 index c5644d0..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/mode.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package bsonrw - -import "fmt" - -type mode int - -const ( - _ mode = iota - mTopLevel - mDocument - mArray - mValue - mElement - mCodeWithScope - mSpacer -) - -func (m mode) String() string { - var str string - - switch m { - case mTopLevel: - str = "TopLevel" - case mDocument: - str = "DocumentMode" - case mArray: - str = "ArrayMode" - case mValue: - str = "ValueMode" - case mElement: - str = "ElementMode" - case mCodeWithScope: - str = "CodeWithScopeMode" - case mSpacer: - str = "CodeWithScopeSpacerFrame" - default: - str = "UnknownMode" - } - - return str -} - -// TransitionError is an error returned when an invalid progressing a -// ValueReader or ValueWriter state machine occurs. -type TransitionError struct { - parent mode - current mode - destination mode -} - -func (te TransitionError) Error() string { - if te.destination == mode(0) { - return fmt.Sprintf("invalid state transition: cannot read/write value while in %s", te.current) - } - if te.parent == mode(0) { - return fmt.Sprintf("invalid state transition: %s -> %s", te.current, te.destination) - } - return fmt.Sprintf("invalid state transition: %s -> %s; parent %s", te.current, te.destination, te.parent) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/primitive_codecs.go b/vendor/github.com/mongodb/mongo-go-driver/bson/primitive_codecs.go deleted file mode 100644 index 369187c..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/primitive_codecs.go +++ /dev/null @@ -1,930 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package bson - -import ( - "errors" - "fmt" - "reflect" - - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/bson/primitive" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -var primitiveCodecs PrimitiveCodecs - -// PrimitiveCodecs is a namespace for all of the default bsoncodec.Codecs for the primitive types -// defined in this package. -type PrimitiveCodecs struct { - x bsonx.PrimitiveCodecs -} - -// RegisterPrimitiveCodecs will register the encode and decode methods attached to PrimitiveCodecs -// with the provided RegistryBuilder. if rb is nil, a new empty RegistryBuilder will be created. -func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder) { - if rb == nil { - panic(errors.New("argument to RegisterPrimitiveCodecs must not be nil")) - } - - rb. - RegisterEncoder(tDocument, bsoncodec.ValueEncoderFunc(pc.x.DocumentEncodeValue)). - RegisterEncoder(tArray, bsoncodec.ValueEncoderFunc(pc.x.ArrayEncodeValue)). - RegisterEncoder(tValue, bsoncodec.ValueEncoderFunc(pc.x.ValueEncodeValue)). - RegisterEncoder(reflect.PtrTo(tRawValue), bsoncodec.ValueEncoderFunc(pc.RawValueEncodeValue)). - RegisterEncoder(reflect.PtrTo(tElementSlice), bsoncodec.ValueEncoderFunc(pc.x.ElementSliceEncodeValue)). - RegisterEncoder(reflect.PtrTo(tBinary), bsoncodec.ValueEncoderFunc(pc.BinaryEncodeValue)). - RegisterEncoder(reflect.PtrTo(tUndefined), bsoncodec.ValueEncoderFunc(pc.UndefinedEncodeValue)). - RegisterEncoder(reflect.PtrTo(tDateTime), bsoncodec.ValueEncoderFunc(pc.DateTimeEncodeValue)). - RegisterEncoder(reflect.PtrTo(tNull), bsoncodec.ValueEncoderFunc(pc.NullEncodeValue)). - RegisterEncoder(reflect.PtrTo(tRegex), bsoncodec.ValueEncoderFunc(pc.RegexEncodeValue)). - RegisterEncoder(reflect.PtrTo(tDBPointer), bsoncodec.ValueEncoderFunc(pc.DBPointerEncodeValue)). - RegisterEncoder(reflect.PtrTo(tCodeWithScope), bsoncodec.ValueEncoderFunc(pc.CodeWithScopeEncodeValue)). - RegisterEncoder(reflect.PtrTo(tTimestamp), bsoncodec.ValueEncoderFunc(pc.TimestampEncodeValue)). - RegisterEncoder(reflect.PtrTo(tMinKey), bsoncodec.ValueEncoderFunc(pc.MinKeyEncodeValue)). - RegisterEncoder(reflect.PtrTo(tMaxKey), bsoncodec.ValueEncoderFunc(pc.MaxKeyEncodeValue)). - RegisterEncoder(reflect.PtrTo(tRaw), bsoncodec.ValueEncoderFunc(pc.RawEncodeValue)). - RegisterEncoder(reflect.PtrTo(tD), bsoncodec.ValueEncoderFunc(pc.DEncodeValue)). - RegisterDecoder(tDocument, bsoncodec.ValueDecoderFunc(pc.x.DocumentDecodeValue)). - RegisterDecoder(tArray, bsoncodec.ValueDecoderFunc(pc.x.ArrayDecodeValue)). - RegisterDecoder(tValue, bsoncodec.ValueDecoderFunc(pc.x.ValueDecodeValue)). - RegisterDecoder(reflect.PtrTo(tRawValue), bsoncodec.ValueDecoderFunc(pc.RawValueDecodeValue)). - RegisterDecoder(reflect.PtrTo(tElementSlice), bsoncodec.ValueDecoderFunc(pc.x.ElementSliceDecodeValue)). - RegisterDecoder(reflect.PtrTo(tBinary), bsoncodec.ValueDecoderFunc(pc.BinaryDecodeValue)). - RegisterDecoder(reflect.PtrTo(tUndefined), bsoncodec.ValueDecoderFunc(pc.UndefinedDecodeValue)). - RegisterDecoder(reflect.PtrTo(tDateTime), bsoncodec.ValueDecoderFunc(pc.DateTimeDecodeValue)). - RegisterDecoder(reflect.PtrTo(tNull), bsoncodec.ValueDecoderFunc(pc.NullDecodeValue)). - RegisterDecoder(reflect.PtrTo(tRegex), bsoncodec.ValueDecoderFunc(pc.RegexDecodeValue)). - RegisterDecoder(reflect.PtrTo(tDBPointer), bsoncodec.ValueDecoderFunc(pc.DBPointerDecodeValue)). - RegisterDecoder(reflect.PtrTo(tCodeWithScope), bsoncodec.ValueDecoderFunc(pc.CodeWithScopeDecodeValue)). - RegisterDecoder(reflect.PtrTo(tTimestamp), bsoncodec.ValueDecoderFunc(pc.TimestampDecodeValue)). - RegisterDecoder(reflect.PtrTo(tMinKey), bsoncodec.ValueDecoderFunc(pc.MinKeyDecodeValue)). - RegisterDecoder(reflect.PtrTo(tMaxKey), bsoncodec.ValueDecoderFunc(pc.MaxKeyDecodeValue)). - RegisterDecoder(reflect.PtrTo(tRaw), bsoncodec.ValueDecoderFunc(pc.RawDecodeValue)). - RegisterDecoder(reflect.PtrTo(tEmpty), bsoncodec.ValueDecoderFunc(pc.EmptyInterfaceDecodeValue)). - RegisterDecoder(reflect.PtrTo(tD), bsoncodec.ValueDecoderFunc(pc.DDecodeValue)) -} - -// JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type. -func (PrimitiveCodecs) JavaScriptEncodeValue(ectx bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var js primitive.JavaScript - switch t := i.(type) { - case primitive.JavaScript: - js = t - case *primitive.JavaScript: - if t == nil { - return vw.WriteNull() - } - js = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "JavaScriptEncodeValue", - Types: []interface{}{primitive.JavaScript(""), (*primitive.JavaScript)(nil)}, - Received: i, - } - } - - return vw.WriteJavascript(string(js)) -} - -// SymbolEncodeValue is the ValueEncoderFunc for the primitive.Symbol type. -func (PrimitiveCodecs) SymbolEncodeValue(ectx bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var symbol primitive.Symbol - switch t := i.(type) { - case primitive.Symbol: - symbol = t - case *primitive.Symbol: - if t == nil { - return vw.WriteNull() - } - symbol = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "SymbolEncodeValue", - Types: []interface{}{primitive.Symbol(""), (*primitive.Symbol)(nil)}, - Received: i, - } - } - - return vw.WriteJavascript(string(symbol)) -} - -// JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type. -func (PrimitiveCodecs) JavaScriptDecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.JavaScript { - return fmt.Errorf("cannot decode %v into a primitive.JavaScript", vr.Type()) - } - - js, err := vr.ReadJavascript() - if err != nil { - return err - } - - if target, ok := i.(*primitive.JavaScript); ok && target != nil { - *target = primitive.JavaScript(js) - return nil - } - - if target, ok := i.(**primitive.JavaScript); ok && target != nil { - pjs := *target - if pjs == nil { - pjs = new(primitive.JavaScript) - } - *pjs = primitive.JavaScript(js) - *target = pjs - return nil - } - - return bsoncodec.ValueDecoderError{ - Name: "JavaScriptDecodeValue", - Types: []interface{}{(*primitive.JavaScript)(nil), (**primitive.JavaScript)(nil)}, - Received: i, - } -} - -// SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type. -func (PrimitiveCodecs) SymbolDecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Symbol { - return fmt.Errorf("cannot decode %v into a primitive.Symbol", vr.Type()) - } - - symbol, err := vr.ReadSymbol() - if err != nil { - return err - } - - if target, ok := i.(*primitive.Symbol); ok && target != nil { - *target = primitive.Symbol(symbol) - return nil - } - - if target, ok := i.(**primitive.Symbol); ok && target != nil { - psymbol := *target - if psymbol == nil { - psymbol = new(primitive.Symbol) - } - *psymbol = primitive.Symbol(symbol) - *target = psymbol - return nil - } - - return bsoncodec.ValueDecoderError{Name: "SymbolDecodeValue", Types: []interface{}{(*primitive.Symbol)(nil), (**primitive.Symbol)(nil)}, Received: i} -} - -// BinaryEncodeValue is the ValueEncoderFunc for Binary. -func (PrimitiveCodecs) BinaryEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var b primitive.Binary - switch t := i.(type) { - case primitive.Binary: - b = t - case *primitive.Binary: - if t == nil { - return vw.WriteNull() - } - b = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "BinaryEncodeValue", - Types: []interface{}{primitive.Binary{}, (*primitive.Binary)(nil)}, - Received: i, - } - } - - return vw.WriteBinaryWithSubtype(b.Data, b.Subtype) -} - -// BinaryDecodeValue is the ValueDecoderFunc for Binary. -func (PrimitiveCodecs) BinaryDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Binary { - return fmt.Errorf("cannot decode %v into a Binary", vr.Type()) - } - - data, subtype, err := vr.ReadBinary() - if err != nil { - return err - } - - if target, ok := i.(*primitive.Binary); ok && target != nil { - *target = primitive.Binary{Data: data, Subtype: subtype} - return nil - } - - if target, ok := i.(**primitive.Binary); ok && target != nil { - pb := *target - if pb == nil { - pb = new(primitive.Binary) - } - *pb = primitive.Binary{Data: data, Subtype: subtype} - *target = pb - return nil - } - - return bsoncodec.ValueDecoderError{Name: "BinaryDecodeValue", Types: []interface{}{(*primitive.Binary)(nil)}, Received: i} -} - -// UndefinedEncodeValue is the ValueEncoderFunc for Undefined. -func (PrimitiveCodecs) UndefinedEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch tt := i.(type) { - case primitive.Undefined: - case *primitive.Undefined: - if tt == nil { - return vw.WriteNull() - } - default: - return bsoncodec.ValueEncoderError{ - Name: "UndefinedEncodeValue", - Types: []interface{}{primitive.Undefined{}, (*primitive.Undefined)(nil)}, - Received: i, - } - } - - return vw.WriteUndefined() -} - -// UndefinedDecodeValue is the ValueDecoderFunc for Undefined. -func (PrimitiveCodecs) UndefinedDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Undefined { - return fmt.Errorf("cannot decode %v into an Undefined", vr.Type()) - } - - target, ok := i.(*primitive.Undefined) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "UndefinedDecodeValue", Types: []interface{}{(*primitive.Undefined)(nil)}, Received: i} - } - - *target = primitive.Undefined{} - return vr.ReadUndefined() -} - -// DateTimeEncodeValue is the ValueEncoderFunc for DateTime. -func (PrimitiveCodecs) DateTimeEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var dt primitive.DateTime - switch t := i.(type) { - case primitive.DateTime: - dt = t - case *primitive.DateTime: - if t == nil { - return vw.WriteNull() - } - dt = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "DateTimeEncodeValue", - Types: []interface{}{primitive.DateTime(0), (*primitive.DateTime)(nil)}, - Received: i, - } - } - - return vw.WriteDateTime(int64(dt)) -} - -// DateTimeDecodeValue is the ValueDecoderFunc for DateTime. -func (PrimitiveCodecs) DateTimeDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.DateTime { - return fmt.Errorf("cannot decode %v into a DateTime", vr.Type()) - } - - target, ok := i.(*primitive.DateTime) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "DateTimeDecodeValue", Types: []interface{}{(*primitive.DateTime)(nil)}, Received: i} - } - - dt, err := vr.ReadDateTime() - if err != nil { - return err - } - - *target = primitive.DateTime(dt) - return nil -} - -// NullEncodeValue is the ValueEncoderFunc for Null. -func (PrimitiveCodecs) NullEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch i.(type) { - case primitive.Null, *primitive.Null: - default: - return bsoncodec.ValueEncoderError{ - Name: "NullEncodeValue", - Types: []interface{}{primitive.Null{}, (*primitive.Null)(nil)}, - Received: i, - } - } - - return vw.WriteNull() -} - -// NullDecodeValue is the ValueDecoderFunc for Null. -func (PrimitiveCodecs) NullDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Null { - return fmt.Errorf("cannot decode %v into a Null", vr.Type()) - } - - target, ok := i.(*primitive.Null) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "NullDecodeValue", Types: []interface{}{(*primitive.Null)(nil)}, Received: i} - } - - *target = primitive.Null{} - return vr.ReadNull() -} - -// RegexEncodeValue is the ValueEncoderFunc for Regex. -func (PrimitiveCodecs) RegexEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var regex primitive.Regex - switch t := i.(type) { - case primitive.Regex: - regex = t - case *primitive.Regex: - if t == nil { - return vw.WriteNull() - } - regex = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "RegexEncodeValue", - Types: []interface{}{primitive.Regex{}, (*primitive.Regex)(nil)}, - Received: i, - } - } - - return vw.WriteRegex(regex.Pattern, regex.Options) -} - -// RegexDecodeValue is the ValueDecoderFunc for Regex. -func (PrimitiveCodecs) RegexDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Regex { - return fmt.Errorf("cannot decode %v into a Regex", vr.Type()) - } - - target, ok := i.(*primitive.Regex) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "RegexDecodeValue", Types: []interface{}{(*primitive.Regex)(nil)}, Received: i} - } - - pattern, options, err := vr.ReadRegex() - if err != nil { - return err - } - - *target = primitive.Regex{Pattern: pattern, Options: options} - return nil -} - -// DBPointerEncodeValue is the ValueEncoderFunc for DBPointer. -func (PrimitiveCodecs) DBPointerEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var dbp primitive.DBPointer - switch t := i.(type) { - case primitive.DBPointer: - dbp = t - case *primitive.DBPointer: - if t == nil { - return vw.WriteNull() - } - dbp = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "DBPointerEncodeValue", - Types: []interface{}{primitive.DBPointer{}, (*primitive.DBPointer)(nil)}, - Received: i, - } - } - - return vw.WriteDBPointer(dbp.DB, dbp.Pointer) -} - -// DBPointerDecodeValue is the ValueDecoderFunc for DBPointer. -func (PrimitiveCodecs) DBPointerDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.DBPointer { - return fmt.Errorf("cannot decode %v into a DBPointer", vr.Type()) - } - - target, ok := i.(*primitive.DBPointer) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "DBPointerDecodeValue", Types: []interface{}{(*primitive.DBPointer)(nil)}, Received: i} - } - - ns, pointer, err := vr.ReadDBPointer() - if err != nil { - return err - } - - *target = primitive.DBPointer{DB: ns, Pointer: pointer} - return nil -} - -// CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope. -func (pc PrimitiveCodecs) CodeWithScopeEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var cws primitive.CodeWithScope - switch t := i.(type) { - case primitive.CodeWithScope: - cws = t - case *primitive.CodeWithScope: - if t == nil { - return vw.WriteNull() - } - cws = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "CodeWithScopeEncodeValue", - Types: []interface{}{primitive.CodeWithScope{}, (*primitive.CodeWithScope)(nil)}, - Received: i, - } - } - - dw, err := vw.WriteCodeWithScope(string(cws.Code)) - if err != nil { - return err - } - - doc, err := MarshalWithRegistry(ec.Registry, cws.Scope) - if err != nil { - return err - } - - return pc.encodeRaw(ec, dw, doc) -} - -// CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope. -func (pc PrimitiveCodecs) CodeWithScopeDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.CodeWithScope { - return fmt.Errorf("cannot decode %v into a CodeWithScope", vr.Type()) - } - - target, ok := i.(*primitive.CodeWithScope) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{ - Name: "CodeWithScopeDecodeValue", - Types: []interface{}{(*primitive.CodeWithScope)(nil)}, - Received: i, - } - } - - code, dr, err := vr.ReadCodeWithScope() - if err != nil { - return err - } - - var scope bsonx.Doc - err = pc.x.DecodeDocument(dc, dr, &scope) - if err != nil { - return err - } - - *target = primitive.CodeWithScope{Code: primitive.JavaScript(code), Scope: scope} - return nil -} - -// TimestampEncodeValue is the ValueEncoderFunc for Timestamp. -func (PrimitiveCodecs) TimestampEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var ts primitive.Timestamp - switch t := i.(type) { - case primitive.Timestamp: - ts = t - case *primitive.Timestamp: - if t == nil { - return vw.WriteNull() - } - ts = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "TimestampEncodeValue", - Types: []interface{}{primitive.Timestamp{}, (*primitive.Timestamp)(nil)}, - Received: i, - } - } - - return vw.WriteTimestamp(ts.T, ts.I) -} - -// TimestampDecodeValue is the ValueDecoderFunc for Timestamp. -func (PrimitiveCodecs) TimestampDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.Timestamp { - return fmt.Errorf("cannot decode %v into a Timestamp", vr.Type()) - } - - target, ok := i.(*primitive.Timestamp) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "TimestampDecodeValue", Types: []interface{}{(*primitive.Timestamp)(nil)}, Received: i} - } - - t, incr, err := vr.ReadTimestamp() - if err != nil { - return err - } - - *target = primitive.Timestamp{T: t, I: incr} - return nil -} - -// MinKeyEncodeValue is the ValueEncoderFunc for MinKey. -func (PrimitiveCodecs) MinKeyEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch tt := i.(type) { - case primitive.MinKey: - case *primitive.MinKey: - if tt == nil { - return vw.WriteNull() - } - default: - return bsoncodec.ValueEncoderError{ - Name: "MinKeyEncodeValue", - Types: []interface{}{primitive.MinKey{}, (*primitive.MinKey)(nil)}, - Received: i, - } - } - - return vw.WriteMinKey() -} - -// MinKeyDecodeValue is the ValueDecoderFunc for MinKey. -func (PrimitiveCodecs) MinKeyDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.MinKey { - return fmt.Errorf("cannot decode %v into a MinKey", vr.Type()) - } - - target, ok := i.(*primitive.MinKey) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "MinKeyDecodeValue", Types: []interface{}{(*primitive.MinKey)(nil)}, Received: i} - } - - *target = primitive.MinKey{} - return vr.ReadMinKey() -} - -// MaxKeyEncodeValue is the ValueEncoderFunc for MaxKey. -func (PrimitiveCodecs) MaxKeyEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - switch tt := i.(type) { - case primitive.MaxKey: - case *primitive.MaxKey: - if tt == nil { - return vw.WriteNull() - } - default: - return bsoncodec.ValueEncoderError{ - Name: "MaxKeyEncodeValue", - Types: []interface{}{primitive.MaxKey{}, (*primitive.MaxKey)(nil)}, - Received: i, - } - } - - return vw.WriteMaxKey() -} - -// MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey. -func (PrimitiveCodecs) MaxKeyDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - if vr.Type() != bsontype.MaxKey { - return fmt.Errorf("cannot decode %v into a MaxKey", vr.Type()) - } - - target, ok := i.(*primitive.MaxKey) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "MaxKeyDecodeValue", Types: []interface{}{(*primitive.MaxKey)(nil)}, Received: i} - } - - *target = primitive.MaxKey{} - return vr.ReadMaxKey() -} - -// RawValueEncodeValue is the ValueEncoderFunc for RawValue. -func (PrimitiveCodecs) RawValueEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var rawvalue RawValue - switch t := i.(type) { - case RawValue: - rawvalue = t - case *RawValue: - if t == nil { - return vw.WriteNull() - } - rawvalue = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "RawValueEncodeValue", - Types: []interface{}{RawValue{}, (*RawValue)(nil)}, - Received: i, - } - } - - return bsonrw.Copier{}.CopyValueFromBytes(vw, rawvalue.Type, rawvalue.Value) -} - -// RawValueDecodeValue is the ValueDecoderFunc for RawValue. -func (PrimitiveCodecs) RawValueDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - var target *RawValue - fail := func() error { - return bsoncodec.ValueDecoderError{ - Name: "RawValueDecodeValue", - Types: []interface{}{(*RawValue)(nil), (**RawValue)(nil)}, - Received: i, - } - } - switch t := i.(type) { - case *RawValue: - if t == nil { - return fail() - } - target = t - case **RawValue: - if t == nil { - return fail() - } - if *t == nil { - *t = new(RawValue) - } - target = *t - default: - return fail() - } - - t, val, err := bsonrw.Copier{}.CopyValueToBytes(vr) - if err != nil { - return err - } - - target.Type, target.Value, target.r = t, val, dc.Registry - return nil -} - -// RawEncodeValue is the ValueEncoderFunc for Reader. -func (PrimitiveCodecs) RawEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - rdr, ok := i.(Raw) - if !ok { - return bsoncodec.ValueEncoderError{ - Name: "RawEncodeValue", - Types: []interface{}{Raw{}}, - Received: i, - } - } - - return bsonrw.Copier{}.CopyDocumentFromBytes(vw, rdr) -} - -// RawDecodeValue is the ValueDecoderFunc for Reader. -func (PrimitiveCodecs) RawDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - rdr, ok := i.(*Raw) - if !ok { - return bsoncodec.ValueDecoderError{Name: "RawDecodeValue", Types: []interface{}{(*Raw)(nil)}, Received: i} - } - - if rdr == nil { - return errors.New("RawDecodeValue can only be used to decode non-nil *Reader") - } - - if *rdr == nil { - *rdr = make(Raw, 0) - } else { - *rdr = (*rdr)[:0] - } - - var err error - *rdr, err = bsonrw.Copier{}.AppendDocumentBytes(*rdr, vr) - return err -} - -// EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}. -func (PrimitiveCodecs) EmptyInterfaceDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - target, ok := i.(*interface{}) - if !ok || target == nil { - return fmt.Errorf("EmptyInterfaceDecodeValue can only be used to decode non-nil *interface{} values, provided type if %T", i) - } - - // fn is a function we call to assign val back to the target, we do this so - // we can keep down on the repeated code in this method. In all of the - // implementations this is a closure, so we don't need to provide the - // target as a parameter. - var fn func() - var val interface{} - var rtype reflect.Type - - switch vr.Type() { - case bsontype.Double: - val = new(float64) - rtype = tFloat64 - fn = func() { *target = *(val.(*float64)) } - case bsontype.String: - val = new(string) - rtype = tString - fn = func() { *target = *(val.(*string)) } - case bsontype.EmbeddedDocument: - val = new(bsonx.Doc) - rtype = tDocument - fn = func() { *target = *val.(*bsonx.Doc) } - case bsontype.Array: - val = new(bsonx.Arr) - rtype = tArray - fn = func() { *target = *val.(*bsonx.Arr) } - case bsontype.Binary: - val = new(primitive.Binary) - rtype = tBinary - fn = func() { *target = *(val.(*primitive.Binary)) } - case bsontype.Undefined: - val = new(primitive.Undefined) - rtype = tUndefined - fn = func() { *target = *(val.(*primitive.Undefined)) } - case bsontype.ObjectID: - val = new(objectid.ObjectID) - rtype = tOID - fn = func() { *target = *(val.(*objectid.ObjectID)) } - case bsontype.Boolean: - val = new(bool) - rtype = tBool - fn = func() { *target = *(val.(*bool)) } - case bsontype.DateTime: - val = new(primitive.DateTime) - rtype = tDateTime - fn = func() { *target = *(val.(*primitive.DateTime)) } - case bsontype.Null: - val = new(primitive.Null) - rtype = tNull - fn = func() { *target = *(val.(*primitive.Null)) } - case bsontype.Regex: - val = new(primitive.Regex) - rtype = tRegex - fn = func() { *target = *(val.(*primitive.Regex)) } - case bsontype.DBPointer: - val = new(primitive.DBPointer) - rtype = tDBPointer - fn = func() { *target = *(val.(*primitive.DBPointer)) } - case bsontype.JavaScript: - val = new(primitive.JavaScript) - rtype = tJavaScript - fn = func() { *target = *(val.(*primitive.JavaScript)) } - case bsontype.Symbol: - val = new(primitive.Symbol) - rtype = tSymbol - fn = func() { *target = *(val.(*primitive.Symbol)) } - case bsontype.CodeWithScope: - val = new(primitive.CodeWithScope) - rtype = tCodeWithScope - fn = func() { *target = *(val.(*primitive.CodeWithScope)) } - case bsontype.Int32: - val = new(int32) - rtype = tInt32 - fn = func() { *target = *(val.(*int32)) } - case bsontype.Int64: - val = new(int64) - rtype = tInt64 - fn = func() { *target = *(val.(*int64)) } - case bsontype.Timestamp: - val = new(primitive.Timestamp) - rtype = tTimestamp - fn = func() { *target = *(val.(*primitive.Timestamp)) } - case bsontype.Decimal128: - val = new(decimal.Decimal128) - rtype = tDecimal - fn = func() { *target = *(val.(*decimal.Decimal128)) } - case bsontype.MinKey: - val = new(primitive.MinKey) - rtype = tMinKey - fn = func() { *target = *(val.(*primitive.MinKey)) } - case bsontype.MaxKey: - val = new(primitive.MaxKey) - rtype = tMaxKey - fn = func() { *target = *(val.(*primitive.MaxKey)) } - default: - return fmt.Errorf("Type %s is not a valid BSON type and has no default Go type to decode into", vr.Type()) - } - - decoder, err := dc.LookupDecoder(rtype) - if err != nil { - return err - } - err = decoder.DecodeValue(dc, vr, val) - if err != nil { - return err - } - - fn() - return nil -} - -// DEncodeValue is the ValueEncoderFunc for D and *D. -func (pc PrimitiveCodecs) DEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var d D - switch tt := i.(type) { - case D: - d = tt - case *D: - if tt == nil { - return vw.WriteNull() - } - d = *tt - default: - return bsoncodec.ValueEncoderError{Name: "DEncodeValue", Types: []interface{}{D{}, (*D)(nil)}, Received: i} - } - - dw, err := vw.WriteDocument() - if err != nil { - return err - } - - for _, e := range d { - vw, err := dw.WriteDocumentElement(e.Key) - if err != nil { - return err - } - - encoder, err := ec.LookupEncoder(reflect.TypeOf(e.Value)) - if err != nil { - return err - } - - err = encoder.EncodeValue(ec, vw, e.Value) - if err != nil { - return err - } - } - - return dw.WriteDocumentEnd() -} - -// DDecodeValue is the ValueDecoderFunc for *D and **D. -func (pc PrimitiveCodecs) DDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - var target *D - fail := func() error { - return bsoncodec.ValueDecoderError{Name: "DDecodeValue", Types: []interface{}{(*D)(nil), (**D)(nil)}, Received: i} - } - switch tt := i.(type) { - case *D: - if tt == nil { - return fail() - } - target = tt - case **D: - if tt == nil { - return fail() - } - if vr.Type() == bsontype.Null { - err := vr.ReadNull() - *tt = nil - return err - } - if *tt == nil { - *tt = new(D) - } - target = *tt - default: - return fail() - } - - switch vr.Type() { - case bsontype.Type(0), bsontype.EmbeddedDocument: - default: - return fmt.Errorf("cannot decode %v into a D", vr.Type()) - } - - dr, err := vr.ReadDocument() - if err != nil { - return err - } - - *target = (*target)[:0] - - for { - key, vr, err := dr.ReadElement() - if err == bsonrw.ErrEOD { - break - } - if err != nil { - return err - } - - var val interface{} - err = pc.EmptyInterfaceDecodeValue(dc, vr, &val) - if err != nil { - return err - } - - *target = append(*target, E{Key: key, Value: val}) - } - - return nil -} - -func (pc PrimitiveCodecs) encodeRaw(ec bsoncodec.EncodeContext, dw bsonrw.DocumentWriter, raw Raw) error { - var copier bsonrw.Copier - elems, err := raw.Elements() - if err != nil { - return err - } - for _, elem := range elems { - dvw, err := dw.WriteDocumentElement(elem.Key()) - if err != nil { - return err - } - - val := elem.Value() - err = copier.CopyValueFromBytes(dvw, val.Type, val.Value) - if err != nil { - return err - } - } - - return dw.WriteDocumentEnd() -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/cursor.go b/vendor/github.com/mongodb/mongo-go-driver/core/command/cursor.go deleted file mode 100644 index ac737c2..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/cursor.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package command - -import ( - "context" - - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -// Cursor instances iterate a stream of documents. Each document is -// decoded into the result according to the rules of the bson package. -// -// A typical usage of the Cursor interface would be: -// -// var cur Cursor -// ctx := context.Background() -// defer cur.Close(ctx) -// -// for cur.Next(ctx) { -// elem := bson.NewDocument() -// if err := cur.Decode(elem); err != nil { -// log.Fatal(err) -// } -// -// // do something with elem.... -// } -// -// if err := cur.Err(); err != nil { -// log.Fatal(err) -// } -// -type Cursor interface { - // Get the ID of the cursor. - ID() int64 - - // Get the next result from the cursor. - // Returns true if there were no errors and there is a next result. - Next(context.Context) bool - - // Decode the next document into the provided object according to the - // rules of the bson package. - Decode(interface{}) error - - // Returns the next document as a bson.Reader. The user must copy the - // bytes to retain them. - DecodeBytes() (bson.Raw, error) - - // Returns the error status of the cursor - Err() error - - // Close the cursor. - Close(context.Context) error -} - -// CursorBuilder is a type that can build a Cursor. -type CursorBuilder interface { - BuildCursor(bson.Raw, *session.Client, *session.ClusterClock, ...bsonx.Elem) (Cursor, error) -} - -type emptyCursor struct{} - -func (ec emptyCursor) ID() int64 { return -1 } -func (ec emptyCursor) Next(context.Context) bool { return false } -func (ec emptyCursor) Decode(interface{}) error { return nil } -func (ec emptyCursor) DecodeBytes() (bson.Raw, error) { return nil, nil } -func (ec emptyCursor) Err() error { return nil } -func (ec emptyCursor) Close(context.Context) error { return nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/aggregate.go b/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/aggregate.go deleted file mode 100644 index 2486415..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/aggregate.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package dispatch - -import ( - "context" - - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" - - "time" - - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" -) - -// Aggregate handles the full cycle dispatch and execution of an aggregate command against the provided -// topology. -func Aggregate( - ctx context.Context, - cmd command.Aggregate, - topo *topology.Topology, - readSelector, writeSelector description.ServerSelector, - clientID uuid.UUID, - pool *session.Pool, - registry *bsoncodec.Registry, - opts ...*options.AggregateOptions, -) (command.Cursor, error) { - - dollarOut := cmd.HasDollarOut() - - var ss *topology.SelectedServer - var err error - switch dollarOut { - case true: - ss, err = topo.SelectServer(ctx, writeSelector) - if err != nil { - return nil, err - } - case false: - ss, err = topo.SelectServer(ctx, readSelector) - if err != nil { - return nil, err - } - } - - desc := ss.Description() - conn, err := ss.Connection(ctx) - if err != nil { - return nil, err - } - - defer conn.Close() - - rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session) - if err != nil { - return nil, err - } - cmd.ReadPref = rp - - // If no explicit session and deployment supports sessions, start implicit session. - if cmd.Session == nil && topo.SupportsSessions() { - cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) - if err != nil { - return nil, err - } - } - - aggOpts := options.MergeAggregateOptions(opts...) - - if aggOpts.AllowDiskUse != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"allowDiskUse", bsonx.Boolean(*aggOpts.AllowDiskUse)}) - } - if aggOpts.BatchSize != nil { - elem := bsonx.Elem{"batchSize", bsonx.Int32(*aggOpts.BatchSize)} - cmd.Opts = append(cmd.Opts, elem) - cmd.CursorOpts = append(cmd.CursorOpts, elem) - } - if aggOpts.BypassDocumentValidation != nil && desc.WireVersion.Includes(4) { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"bypassDocumentValidation", bsonx.Boolean(*aggOpts.BypassDocumentValidation)}) - } - if aggOpts.Collation != nil { - if desc.WireVersion.Max < 5 { - return nil, ErrCollation - } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(aggOpts.Collation.ToDocument())}) - } - if aggOpts.MaxTime != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*aggOpts.MaxTime / time.Millisecond))}) - } - if aggOpts.MaxAwaitTime != nil { - // specified as maxTimeMS on getMore commands - cmd.CursorOpts = append(cmd.CursorOpts, bsonx.Elem{ - "maxTimeMS", bsonx.Int64(int64(*aggOpts.MaxAwaitTime / time.Millisecond)), - }) - } - if aggOpts.Comment != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"comment", bsonx.String(*aggOpts.Comment)}) - } - if aggOpts.Hint != nil { - hintElem, err := interfaceToElement("hint", aggOpts.Hint, registry) - if err != nil { - return nil, err - } - - cmd.Opts = append(cmd.Opts, hintElem) - } - - return cmd.RoundTrip(ctx, desc, ss, conn) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find.go b/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find.go deleted file mode 100644 index 7dfaef1..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package dispatch - -import ( - "context" - - "time" - - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -// Find handles the full cycle dispatch and execution of a find command against the provided -// topology. -func Find( - ctx context.Context, - cmd command.Find, - topo *topology.Topology, - selector description.ServerSelector, - clientID uuid.UUID, - pool *session.Pool, - registry *bsoncodec.Registry, - opts ...*options.FindOptions, -) (command.Cursor, error) { - - ss, err := topo.SelectServer(ctx, selector) - if err != nil { - return nil, err - } - - desc := ss.Description() - conn, err := ss.Connection(ctx) - if err != nil { - return nil, err - } - defer conn.Close() - - rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session) - if err != nil { - return nil, err - } - cmd.ReadPref = rp - - // If no explicit session and deployment supports sessions, start implicit session. - if cmd.Session == nil && topo.SupportsSessions() { - cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) - if err != nil { - return nil, err - } - } - - fo := options.MergeFindOptions(opts...) - if fo.AllowPartialResults != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"allowPartialResults", bsonx.Boolean(*fo.AllowPartialResults)}) - } - if fo.BatchSize != nil { - elem := bsonx.Elem{"batchSize", bsonx.Int32(*fo.BatchSize)} - cmd.Opts = append(cmd.Opts, elem) - cmd.CursorOpts = append(cmd.CursorOpts, elem) - - if fo.Limit != nil && *fo.BatchSize != 0 && *fo.Limit <= int64(*fo.BatchSize) { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"singleBatch", bsonx.Boolean(true)}) - } - } - if fo.Collation != nil { - if desc.WireVersion.Max < 5 { - return nil, ErrCollation - } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(fo.Collation.ToDocument())}) - } - if fo.Comment != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"comment", bsonx.String(*fo.Comment)}) - } - if fo.CursorType != nil { - switch *fo.CursorType { - case options.Tailable: - cmd.Opts = append(cmd.Opts, bsonx.Elem{"tailable", bsonx.Boolean(true)}) - case options.TailableAwait: - cmd.Opts = append(cmd.Opts, bsonx.Elem{"tailable", bsonx.Boolean(true)}, bsonx.Elem{"awaitData", bsonx.Boolean(true)}) - } - } - if fo.Hint != nil { - hintElem, err := interfaceToElement("hint", fo.Hint, registry) - if err != nil { - return nil, err - } - - cmd.Opts = append(cmd.Opts, hintElem) - } - if fo.Limit != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"limit", bsonx.Int64(*fo.Limit)}) - } - if fo.Max != nil { - maxElem, err := interfaceToElement("max", fo.Max, registry) - if err != nil { - return nil, err - } - - cmd.Opts = append(cmd.Opts, maxElem) - } - if fo.MaxAwaitTime != nil { - // Specified as maxTimeMS on the in the getMore command and not given in initial find command. - cmd.CursorOpts = append(cmd.CursorOpts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*fo.MaxAwaitTime / time.Millisecond))}) - } - if fo.MaxTime != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*fo.MaxTime / time.Millisecond))}) - } - if fo.Min != nil { - minElem, err := interfaceToElement("min", fo.Min, registry) - if err != nil { - return nil, err - } - - cmd.Opts = append(cmd.Opts, minElem) - } - if fo.NoCursorTimeout != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"noCursorTimeout", bsonx.Boolean(*fo.NoCursorTimeout)}) - } - if fo.OplogReplay != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"oplogReplay", bsonx.Boolean(*fo.OplogReplay)}) - } - if fo.Projection != nil { - projElem, err := interfaceToElement("projection", fo.Projection, registry) - if err != nil { - return nil, err - } - - cmd.Opts = append(cmd.Opts, projElem) - } - if fo.ReturnKey != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"returnKey", bsonx.Boolean(*fo.ReturnKey)}) - } - if fo.ShowRecordID != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"showRecordId", bsonx.Boolean(*fo.ShowRecordID)}) - } - if fo.Skip != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"skip", bsonx.Int64(*fo.Skip)}) - } - if fo.Snapshot != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"snapshot", bsonx.Boolean(*fo.Snapshot)}) - } - if fo.Sort != nil { - sortElem, err := interfaceToElement("sort", fo.Sort, registry) - if err != nil { - return nil, err - } - - cmd.Opts = append(cmd.Opts, sortElem) - } - - return cmd.RoundTrip(ctx, desc, ss, conn) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_collections.go b/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_collections.go deleted file mode 100644 index 01a6ee0..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_collections.go +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package dispatch - -import ( - "context" - - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -// ListCollections handles the full cycle dispatch and execution of a listCollections command against the provided -// topology. -func ListCollections( - ctx context.Context, - cmd command.ListCollections, - topo *topology.Topology, - selector description.ServerSelector, - clientID uuid.UUID, - pool *session.Pool, - opts ...*options.ListCollectionsOptions, -) (command.Cursor, error) { - - ss, err := topo.SelectServer(ctx, selector) - if err != nil { - return nil, err - } - - conn, err := ss.Connection(ctx) - if err != nil { - return nil, err - } - defer conn.Close() - - rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session) - if err != nil { - return nil, err - } - cmd.ReadPref = rp - - // If no explicit session and deployment supports sessions, start implicit session. - if cmd.Session == nil && topo.SupportsSessions() { - cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) - if err != nil { - return nil, err - } - } - - lc := options.MergeListCollectionsOptions(opts...) - if lc.NameOnly != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"nameOnly", bsonx.Boolean(*lc.NameOnly)}) - } - - return cmd.RoundTrip(ctx, ss.Description(), ss, conn) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_indexes.go b/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_indexes.go deleted file mode 100644 index 8e53336..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_indexes.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package dispatch - -import ( - "context" - - "time" - - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -// ListIndexes handles the full cycle dispatch and execution of a listIndexes command against the provided -// topology. -func ListIndexes( - ctx context.Context, - cmd command.ListIndexes, - topo *topology.Topology, - selector description.ServerSelector, - clientID uuid.UUID, - pool *session.Pool, - opts ...*options.ListIndexesOptions, -) (command.Cursor, error) { - - ss, err := topo.SelectServer(ctx, selector) - if err != nil { - return nil, err - } - - conn, err := ss.Connection(ctx) - if err != nil { - return nil, err - } - defer conn.Close() - - lio := options.MergeListIndexesOptions(opts...) - if lio.BatchSize != nil { - elem := bsonx.Elem{"batchSize", bsonx.Int32(*lio.BatchSize)} - cmd.Opts = append(cmd.Opts, elem) - cmd.CursorOpts = append(cmd.CursorOpts, elem) - } - if lio.MaxTime != nil { - cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*lio.MaxTime / time.Millisecond))}) - } - - // If no explicit session and deployment supports sessions, start implicit session. - if cmd.Session == nil && topo.SupportsSessions() { - cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) - if err != nil { - return nil, err - } - } - - return cmd.RoundTrip(ctx, ss.Description(), ss, conn) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/cursor.go b/vendor/github.com/mongodb/mongo-go-driver/core/topology/cursor.go deleted file mode 100644 index df143ef..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/cursor.go +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package topology - -import ( - "context" - "errors" - "fmt" - - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -type cursor struct { - clientSession *session.Client - clock *session.ClusterClock - namespace command.Namespace - current int - batch []bson.RawValue - id int64 - err error - server *Server - opts []bsonx.Elem - registry *bsoncodec.Registry -} - -func newCursor(result bson.Raw, clientSession *session.Client, clock *session.ClusterClock, server *Server, opts ...bsonx.Elem) (command.Cursor, error) { - cur, err := result.LookupErr("cursor") - if err != nil { - return nil, err - } - if cur.Type != bson.TypeEmbeddedDocument { - return nil, fmt.Errorf("cursor should be an embedded document but it is a BSON %s", cur.Type) - } - - elems, err := cur.Document().Elements() - if err != nil { - return nil, err - } - c := &cursor{ - clientSession: clientSession, - clock: clock, - current: -1, - server: server, - registry: server.cfg.registry, - opts: opts, - } - - var ok bool - for _, elem := range elems { - switch elem.Key() { - case "firstBatch": - var arr bson.Raw - arr, ok = elem.Value().ArrayOK() - if !ok { - return nil, fmt.Errorf("firstBatch should be an array but it is a BSON %s", elem.Value().Type) - } - c.batch, err = arr.Values() - if err != nil { - return nil, err - } - case "ns": - if elem.Value().Type != bson.TypeString { - return nil, fmt.Errorf("namespace should be a string but it is a BSON %s", elem.Value().Type) - } - namespace := command.ParseNamespace(elem.Value().StringValue()) - err = namespace.Validate() - if err != nil { - return nil, err - } - c.namespace = namespace - case "id": - c.id, ok = elem.Value().Int64OK() - if !ok { - return nil, fmt.Errorf("id should be an int64 but it is a BSON %s", elem.Value().Type) - } - } - } - - // close session if everything fits in first batch - if c.id == 0 { - c.closeImplicitSession() - } - return c, nil -} - -// close the associated session if it's implicit -func (c *cursor) closeImplicitSession() { - if c.clientSession != nil && c.clientSession.SessionType == session.Implicit { - c.clientSession.EndSession() - } -} - -func (c *cursor) ID() int64 { - return c.id -} - -func (c *cursor) Next(ctx context.Context) bool { - if ctx == nil { - ctx = context.Background() - } - - c.current++ - if c.current < len(c.batch) { - return true - } - - c.getMore(ctx) - - // call the getMore command in a loop until at least one document is returned in the next batch - for len(c.batch) == 0 { - if c.err != nil || (c.id == 0 && len(c.batch) == 0) { - return false - } - - c.getMore(ctx) - } - - return true -} - -func (c *cursor) Decode(v interface{}) error { - br, err := c.DecodeBytes() - if err != nil { - return err - } - - return bson.UnmarshalWithRegistry(c.registry, br, v) -} - -func (c *cursor) DecodeBytes() (bson.Raw, error) { - br := c.batch[c.current] - if br.Type != bson.TypeEmbeddedDocument { - return nil, errors.New("Non-Document in batch of documents for cursor") - } - return br.Document(), nil -} - -func (c *cursor) Err() error { - return c.err -} - -func (c *cursor) Close(ctx context.Context) error { - if ctx == nil { - ctx = context.Background() - } - - defer c.closeImplicitSession() - conn, err := c.server.Connection(ctx) - if err != nil { - return err - } - - _, err = (&command.KillCursors{ - Clock: c.clock, - NS: c.namespace, - IDs: []int64{c.id}, - }).RoundTrip(ctx, c.server.SelectedDescription(), conn) - if err != nil { - _ = conn.Close() // The command response error is more important here - return err - } - - c.id = 0 - return conn.Close() -} - -func (c *cursor) getMore(ctx context.Context) { - // clear out the batch slice so we can reuse it. - for idx := range c.batch { - c.batch[idx].Type = bsontype.Type(0) - c.batch[idx].Value = nil - } - c.batch = c.batch[:0] - c.current = 0 - - if c.id == 0 { - return - } - - conn, err := c.server.Connection(ctx) - if err != nil { - c.err = err - return - } - - response, err := (&command.GetMore{ - Clock: c.clock, - ID: c.id, - NS: c.namespace, - Opts: c.opts, - Session: c.clientSession, - }).RoundTrip(ctx, c.server.SelectedDescription(), conn) - if err != nil { - _ = conn.Close() // The command response error is more important here - c.err = err - return - } - - err = conn.Close() - if err != nil { - c.err = err - return - } - - id, err := response.LookupErr("cursor", "id") - if err != nil { - c.err = err - return - } - var ok bool - c.id, ok = id.Int64OK() - if !ok { - c.err = fmt.Errorf("BSON Type %s is not %s", id.Type, bson.TypeInt64) - return - } - - // if this is the last getMore, close the session - if c.id == 0 { - c.closeImplicitSession() - } - - batch, err := response.LookupErr("cursor", "nextBatch") - if err != nil { - c.err = err - return - } - var arr bson.Raw - arr, ok = batch.ArrayOK() - if !ok { - c.err = fmt.Errorf("BSON Type %s is not %s", batch.Type, bson.TypeArray) - return - } - c.batch, c.err = arr.Values() - - return -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/get_more.go b/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/get_more.go deleted file mode 100644 index 7b114e3..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/get_more.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package wiremessage - -// GetMore represents the OP_GET_MORE message of the MongoDB wire protocol. -type GetMore struct { - MsgHeader Header - FullCollectionName string - NumberToReturn int32 - CursorID int64 -} - -// MarshalWireMessage implements the Marshaler and WireMessage interfaces. -func (gm GetMore) MarshalWireMessage() ([]byte, error) { - panic("not implemented") -} - -// ValidateWireMessage implements the Validator and WireMessage interfaces. -func (gm GetMore) ValidateWireMessage() error { - panic("not implemented") -} - -// AppendWireMessage implements the Appender and WireMessage interfaces. -func (gm GetMore) AppendWireMessage([]byte) ([]byte, error) { - panic("not implemented") -} - -// String implements the fmt.Stringer interface. -func (gm GetMore) String() string { - panic("not implemented") -} - -// Len implements the WireMessage interface. -func (gm GetMore) Len() int { - panic("not implemented") -} - -// UnmarshalWireMessage implements the Unmarshaler interface. -func (gm *GetMore) UnmarshalWireMessage([]byte) error { - panic("not implemented") -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/kill_cursors.go b/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/kill_cursors.go deleted file mode 100644 index 7a5f011..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/kill_cursors.go +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package wiremessage - -// KillCursors represents the OP_KILL_CURSORS message of the MongoDB wire protocol. -type KillCursors struct { - MsgHeader Header - NumberOfCursorIDs int32 - CursorIDs []int64 -} - -// MarshalWireMessage implements the Marshaler and WireMessage interfaces. -func (kc KillCursors) MarshalWireMessage() ([]byte, error) { - panic("not implemented") -} - -// ValidateWireMessage implements the Validator and WireMessage interfaces. -func (kc KillCursors) ValidateWireMessage() error { - panic("not implemented") -} - -// AppendWireMessage implements the Appender and WireMessage interfaces. -func (kc KillCursors) AppendWireMessage([]byte) ([]byte, error) { - panic("not implemented") -} - -// String implements the fmt.Stringer interface. -func (kc KillCursors) String() string { - panic("not implemented") -} - -// Len implements the WireMessage interface. -func (kc KillCursors) Len() int { - panic("not implemented") -} - -// UnmarshalWireMessage implements the Unmarshaler interface. -func (kc *KillCursors) UnmarshalWireMessage([]byte) error { - panic("not implemented") -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/bulk_write.go b/vendor/github.com/mongodb/mongo-go-driver/mongo/bulk_write.go deleted file mode 100644 index cfb8a98..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/bulk_write.go +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package mongo - -import ( - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/options" -) - -// WriteModel is the interface satisfied by all models for bulk writes. -type WriteModel interface { - convertModel() dispatch.WriteModel -} - -// InsertOneModel is the write model for insert operations. -type InsertOneModel struct { - dispatch.InsertOneModel -} - -// NewInsertOneModel creates a new InsertOneModel. -func NewInsertOneModel() *InsertOneModel { - return &InsertOneModel{} -} - -// Document sets the BSON document for the InsertOneModel. -func (iom *InsertOneModel) Document(doc interface{}) *InsertOneModel { - iom.InsertOneModel.Document = doc - return iom -} - -func (iom *InsertOneModel) convertModel() dispatch.WriteModel { - return iom.InsertOneModel -} - -// DeleteOneModel is the write model for delete operations. -type DeleteOneModel struct { - dispatch.DeleteOneModel -} - -// NewDeleteOneModel creates a new DeleteOneModel. -func NewDeleteOneModel() *DeleteOneModel { - return &DeleteOneModel{} -} - -// Filter sets the filter for the DeleteOneModel. -func (dom *DeleteOneModel) Filter(filter interface{}) *DeleteOneModel { - dom.DeleteOneModel.Filter = filter - return dom -} - -// Collation sets the collation for the DeleteOneModel. -func (dom *DeleteOneModel) Collation(collation *options.Collation) *DeleteOneModel { - dom.DeleteOneModel.Collation = collation - return dom -} - -func (dom *DeleteOneModel) convertModel() dispatch.WriteModel { - return dom.DeleteOneModel -} - -// DeleteManyModel is the write model for deleteMany operations. -type DeleteManyModel struct { - dispatch.DeleteManyModel -} - -// NewDeleteManyModel creates a new DeleteManyModel. -func NewDeleteManyModel() *DeleteManyModel { - return &DeleteManyModel{} -} - -// Filter sets the filter for the DeleteManyModel. -func (dmm *DeleteManyModel) Filter(filter interface{}) *DeleteManyModel { - dmm.DeleteManyModel.Filter = filter - return dmm -} - -// Collation sets the collation for the DeleteManyModel. -func (dmm *DeleteManyModel) Collation(collation *options.Collation) *DeleteManyModel { - dmm.DeleteManyModel.Collation = collation - return dmm -} - -func (dmm *DeleteManyModel) convertModel() dispatch.WriteModel { - return dmm.DeleteManyModel -} - -// ReplaceOneModel is the write model for replace operations. -type ReplaceOneModel struct { - dispatch.ReplaceOneModel -} - -// NewReplaceOneModel creates a new ReplaceOneModel. -func NewReplaceOneModel() *ReplaceOneModel { - return &ReplaceOneModel{} -} - -// Filter sets the filter for the ReplaceOneModel. -func (rom *ReplaceOneModel) Filter(filter interface{}) *ReplaceOneModel { - rom.ReplaceOneModel.Filter = filter - return rom -} - -// Replacement sets the replacement document for the ReplaceOneModel. -func (rom *ReplaceOneModel) Replacement(rep interface{}) *ReplaceOneModel { - rom.ReplaceOneModel.Replacement = rep - return rom -} - -// Collation sets the collation for the ReplaceOneModel. -func (rom *ReplaceOneModel) Collation(collation *options.Collation) *ReplaceOneModel { - rom.ReplaceOneModel.Collation = collation - return rom -} - -// Upsert specifies if a new document should be created if no document matches the query. -func (rom *ReplaceOneModel) Upsert(upsert bool) *ReplaceOneModel { - rom.ReplaceOneModel.Upsert = upsert - rom.ReplaceOneModel.UpsertSet = true - return rom -} - -func (rom *ReplaceOneModel) convertModel() dispatch.WriteModel { - return rom.ReplaceOneModel -} - -// UpdateOneModel is the write model for update operations. -type UpdateOneModel struct { - dispatch.UpdateOneModel -} - -// NewUpdateOneModel creates a new UpdateOneModel. -func NewUpdateOneModel() *UpdateOneModel { - return &UpdateOneModel{} -} - -// Filter sets the filter for the UpdateOneModel. -func (uom *UpdateOneModel) Filter(filter interface{}) *UpdateOneModel { - uom.UpdateOneModel.Filter = filter - return uom -} - -// Update sets the update document for the UpdateOneModel. -func (uom *UpdateOneModel) Update(update interface{}) *UpdateOneModel { - uom.UpdateOneModel.Update = update - return uom -} - -// ArrayFilters specifies a set of filters specifying to which array elements an update should apply. -func (uom *UpdateOneModel) ArrayFilters(filters options.ArrayFilters) *UpdateOneModel { - uom.UpdateOneModel.ArrayFilters = filters - uom.UpdateOneModel.ArrayFiltersSet = true - return uom -} - -// Collation sets the collation for the UpdateOneModel. -func (uom *UpdateOneModel) Collation(collation *options.Collation) *UpdateOneModel { - uom.UpdateOneModel.Collation = collation - return uom -} - -// Upsert specifies if a new document should be created if no document matches the query. -func (uom *UpdateOneModel) Upsert(upsert bool) *UpdateOneModel { - uom.UpdateOneModel.Upsert = upsert - uom.UpdateOneModel.UpsertSet = true - return uom -} - -func (uom *UpdateOneModel) convertModel() dispatch.WriteModel { - return uom.UpdateOneModel -} - -// UpdateManyModel is the write model for updateMany operations. -type UpdateManyModel struct { - dispatch.UpdateManyModel -} - -// NewUpdateManyModel creates a new UpdateManyModel. -func NewUpdateManyModel() *UpdateManyModel { - return &UpdateManyModel{} -} - -// Filter sets the filter for the UpdateManyModel. -func (umm *UpdateManyModel) Filter(filter interface{}) *UpdateManyModel { - umm.UpdateManyModel.Filter = filter - return umm -} - -// Update sets the update document for the UpdateManyModel. -func (umm *UpdateManyModel) Update(update interface{}) *UpdateManyModel { - umm.UpdateManyModel.Update = update - return umm -} - -// ArrayFilters specifies a set of filters specifying to which array elements an update should apply. -func (umm *UpdateManyModel) ArrayFilters(filters options.ArrayFilters) *UpdateManyModel { - umm.UpdateManyModel.ArrayFilters = filters - umm.UpdateManyModel.ArrayFiltersSet = true - return umm -} - -// Collation sets the collation for the UpdateManyModel. -func (umm *UpdateManyModel) Collation(collation *options.Collation) *UpdateManyModel { - umm.UpdateManyModel.Collation = collation - return umm -} - -// Upsert specifies if a new document should be created if no document matches the query. -func (umm *UpdateManyModel) Upsert(upsert bool) *UpdateManyModel { - umm.UpdateManyModel.Upsert = upsert - umm.UpdateManyModel.UpsertSet = true - return umm -} - -func (umm *UpdateManyModel) convertModel() dispatch.WriteModel { - return umm.UpdateManyModel -} - -func dispatchToMongoModel(model dispatch.WriteModel) WriteModel { - switch conv := model.(type) { - case dispatch.InsertOneModel: - return &InsertOneModel{conv} - case dispatch.DeleteOneModel: - return &DeleteOneModel{conv} - case dispatch.DeleteManyModel: - return &DeleteManyModel{conv} - case dispatch.ReplaceOneModel: - return &ReplaceOneModel{conv} - case dispatch.UpdateOneModel: - return &UpdateOneModel{conv} - case dispatch.UpdateManyModel: - return &UpdateManyModel{conv} - } - - return nil -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/change_stream.go b/vendor/github.com/mongodb/mongo-go-driver/mongo/change_stream.go deleted file mode 100644 index 3225528..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/change_stream.go +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package mongo - -import ( - "context" - "errors" - - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" -) - -// ErrMissingResumeToken indicates that a change stream notification from the server did not -// contain a resume token. -var ErrMissingResumeToken = errors.New("cannot provide resume functionality when the resume token is missing") - -type changeStream struct { - pipeline bsonx.Arr - options []bsonx.Elem - coll *Collection - cursor Cursor - session *session.Client - clock *session.ClusterClock - resumeToken bsonx.Doc - err error -} - -const errorCodeNotMaster int32 = 10107 -const errorCodeCursorNotFound int32 = 43 - -func newChangeStream(ctx context.Context, coll *Collection, pipeline interface{}, - opts ...*options.ChangeStreamOptions) (*changeStream, error) { - - pipelineArr, err := transformAggregatePipeline(coll.registry, pipeline) - if err != nil { - return nil, err - } - - csOpts := options.MergeChangeStreamOptions(opts...) - sess := sessionFromContext(ctx) - - err = coll.client.ValidSession(sess) - if err != nil { - return nil, err - } - - changeStreamOptions := make(bsonx.Doc, 0) - aggOpts := options.Aggregate() - - if csOpts.BatchSize != nil { - changeStreamOptions = append(changeStreamOptions, bsonx.Elem{"batchSize", bsonx.Int32(*csOpts.BatchSize)}) - } - if csOpts.Collation != nil { - changeStreamOptions = append(changeStreamOptions, bsonx.Elem{ - "collation", bsonx.Document(csOpts.Collation.ToDocument()), - }) - } - if csOpts.FullDocument != nil { - changeStreamOptions = append(changeStreamOptions, bsonx.Elem{ - "fullDocument", bsonx.String(string(*csOpts.FullDocument)), - }) - } - if csOpts.MaxAwaitTime != nil { - aggOpts.MaxAwaitTime = csOpts.MaxAwaitTime - } - if csOpts.ResumeAfter != nil { - changeStreamOptions = append(changeStreamOptions, bsonx.Elem{"resumeAfter", bsonx.Document(csOpts.ResumeAfter)}) - } - - pipelineArr = append(pipelineArr, bsonx.Val{}) - copy(pipelineArr[1:], pipelineArr) - pipelineArr[0] = bsonx.Document(bsonx.Doc{{"$changeStream", bsonx.Document(changeStreamOptions)}}) - - cursor, err := coll.Aggregate(ctx, pipelineArr, aggOpts) - if err != nil { - return nil, err - } - - cs := &changeStream{ - pipeline: pipelineArr, - options: changeStreamOptions, - coll: coll, - cursor: cursor, - session: sess, - clock: coll.client.clock, - } - - return cs, nil -} - -func (cs *changeStream) ID() int64 { - return cs.cursor.ID() -} - -func (cs *changeStream) Next(ctx context.Context) bool { - if cs.cursor.Next(ctx) { - return true - } - - err := cs.cursor.Err() - if err == nil { - return false - } - - switch t := err.(type) { - case command.Error: - if t.Code != errorCodeNotMaster && t.Code != errorCodeCursorNotFound { - return false - } - } - - found := false - - for i, opt := range cs.options { - if opt.Key == "resumeAfter" { - cs.options[i] = bsonx.Elem{"resumeAfter", bsonx.Document(cs.resumeToken)} - found = true - break - } - } - - if !found && cs.resumeToken != nil { - cs.options = append(cs.options, bsonx.Elem{"resumeAfter", bsonx.Document(cs.resumeToken)}) - } - - oldns := cs.coll.namespace() - killCursors := command.KillCursors{ - NS: command.Namespace{DB: oldns.DB, Collection: oldns.Collection}, - IDs: []int64{cs.ID()}, - } - - ss, err := cs.coll.client.topology.SelectServer(ctx, cs.coll.readSelector) - if err != nil { - cs.err = err - return false - } - - conn, err := ss.Connection(ctx) - if err != nil { - cs.err = err - return false - } - defer conn.Close() - - _, _ = killCursors.RoundTrip(ctx, ss.Description(), conn) - - cs.pipeline[0] = bsonx.Document(bsonx.Doc{{"$changeStream", bsonx.Document(bsonx.Doc(cs.options))}}) - - oldns = cs.coll.namespace() - aggCmd := command.Aggregate{ - NS: command.Namespace{DB: oldns.DB, Collection: oldns.Collection}, - Pipeline: cs.pipeline, - Session: cs.session, - Clock: cs.coll.client.clock, - } - - cur, err := aggCmd.RoundTrip(ctx, ss.Description(), ss, conn) - cs.cursor = cur - cs.err = err - - if cs.err != nil { - return false - } - - return cs.cursor.Next(ctx) -} - -func (cs *changeStream) Decode(out interface{}) error { - br, err := cs.DecodeBytes() - if err != nil { - return err - } - - return bson.UnmarshalWithRegistry(cs.coll.registry, br, out) -} - -func (cs *changeStream) DecodeBytes() (bson.Raw, error) { - br, err := cs.cursor.DecodeBytes() - if err != nil { - return nil, err - } - - id, err := br.LookupErr("_id") - if err != nil { - _ = cs.Close(context.Background()) - return nil, ErrMissingResumeToken - } - - cs.resumeToken, err = bsonx.ReadDoc(id.Document()) - if err != nil { - _ = cs.Close(context.Background()) - return nil, ErrMissingResumeToken - } - - return br, nil -} - -func (cs *changeStream) Err() error { - if cs.err != nil { - return cs.err - } - - return cs.cursor.Err() -} - -func (cs *changeStream) Close(ctx context.Context) error { - return cs.cursor.Close(ctx) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/client.go b/vendor/github.com/mongodb/mongo-go-driver/mongo/client.go deleted file mode 100644 index abda1ec..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/client.go +++ /dev/null @@ -1,435 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package mongo - -import ( - "context" - "time" - - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/connstring" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/tag" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" -) - -const defaultLocalThreshold = 15 * time.Millisecond - -// Client performs operations on a given topology. -type Client struct { - id uuid.UUID - topologyOptions []topology.Option - topology *topology.Topology - connString connstring.ConnString - localThreshold time.Duration - retryWrites bool - clock *session.ClusterClock - readPreference *readpref.ReadPref - readConcern *readconcern.ReadConcern - writeConcern *writeconcern.WriteConcern - registry *bsoncodec.Registry - marshaller BSONAppender -} - -// Connect creates a new Client and then initializes it using the Connect method. -func Connect(ctx context.Context, uri string, opts ...*options.ClientOptions) (*Client, error) { - c, err := NewClientWithOptions(uri, opts...) - if err != nil { - return nil, err - } - err = c.Connect(ctx) - if err != nil { - return nil, err - } - return c, nil -} - -// NewClient creates a new client to connect to a cluster specified by the uri. -func NewClient(uri string) (*Client, error) { - cs, err := connstring.Parse(uri) - if err != nil { - return nil, err - } - - return newClient(cs) -} - -// NewClientWithOptions creates a new client to connect to to a cluster specified by the connection -// string and the options manually passed in. If the same option is configured in both the -// connection string and the manual options, the manual option will be ignored. -func NewClientWithOptions(uri string, opts ...*options.ClientOptions) (*Client, error) { - cs, err := connstring.Parse(uri) - if err != nil { - return nil, err - } - - return newClient(cs, opts...) -} - -// NewClientFromConnString creates a new client to connect to a cluster, with configuration -// specified by the connection string. -func NewClientFromConnString(cs connstring.ConnString) (*Client, error) { - return newClient(cs) -} - -// Connect initializes the Client by starting background monitoring goroutines. -// This method must be called before a Client can be used. -func (c *Client) Connect(ctx context.Context) error { - err := c.topology.Connect(ctx) - if err != nil { - return replaceTopologyErr(err) - } - - return nil - -} - -// Disconnect closes sockets to the topology referenced by this Client. It will -// shut down any monitoring goroutines, close the idle connection pool, and will -// wait until all the in use connections have been returned to the connection -// pool and closed before returning. If the context expires via cancellation, -// deadline, or timeout before the in use connections have returned, the in use -// connections will be closed, resulting in the failure of any in flight read -// or write operations. If this method returns with no errors, all connections -// associated with this Client have been closed. -func (c *Client) Disconnect(ctx context.Context) error { - c.endSessions(ctx) - return replaceTopologyErr(c.topology.Disconnect(ctx)) -} - -// Ping verifies that the client can connect to the topology. -// If readPreference is nil then will use the client's default read -// preference. -func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error { - if ctx == nil { - ctx = context.Background() - } - - if rp == nil { - rp = c.readPreference - } - - _, err := c.topology.SelectServer(ctx, description.ReadPrefSelector(rp)) - return replaceTopologyErr(err) -} - -// StartSession starts a new session. -func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error) { - if c.topology.SessionPool == nil { - return nil, ErrClientDisconnected - } - - sopts := options.MergeSessionOptions(opts...) - coreOpts := &session.ClientOptions{ - DefaultReadConcern: c.readConcern, - DefaultReadPreference: c.readPreference, - DefaultWriteConcern: c.writeConcern, - } - if sopts.CausalConsistency != nil { - coreOpts.CausalConsistency = sopts.CausalConsistency - } - if sopts.DefaultReadConcern != nil { - coreOpts.DefaultReadConcern = sopts.DefaultReadConcern - } - if sopts.DefaultWriteConcern != nil { - coreOpts.DefaultWriteConcern = sopts.DefaultWriteConcern - } - if sopts.DefaultReadPreference != nil { - coreOpts.DefaultReadPreference = sopts.DefaultReadPreference - } - - sess, err := session.NewClientSession(c.topology.SessionPool, c.id, session.Explicit, coreOpts) - if err != nil { - return nil, replaceTopologyErr(err) - } - - sess.RetryWrite = c.retryWrites - - return &sessionImpl{ - Client: sess, - topo: c.topology, - }, nil -} - -func (c *Client) endSessions(ctx context.Context) { - if c.topology.SessionPool == nil { - return - } - cmd := command.EndSessions{ - Clock: c.clock, - SessionIDs: c.topology.SessionPool.IDSlice(), - } - - _, _ = dispatch.EndSessions(ctx, cmd, c.topology, description.ReadPrefSelector(readpref.PrimaryPreferred())) -} - -func newClient(cs connstring.ConnString, opts ...*options.ClientOptions) (*Client, error) { - clientOpt := options.MergeClientOptions(cs, opts...) - - client := &Client{ - topologyOptions: clientOpt.TopologyOptions, - connString: clientOpt.ConnString, - localThreshold: defaultLocalThreshold, - registry: clientOpt.Registry, - } - - clientID, err := uuid.New() - if err != nil { - return nil, err - } - client.id = clientID - - topts := append( - client.topologyOptions, - topology.WithConnString(func(connstring.ConnString) connstring.ConnString { return client.connString }), - topology.WithServerOptions(func(opts ...topology.ServerOption) []topology.ServerOption { - return append(opts, topology.WithClock(func(clock *session.ClusterClock) *session.ClusterClock { - return client.clock - })) - }), - ) - topo, err := topology.New(topts...) - if err != nil { - return nil, replaceTopologyErr(err) - } - client.topology = topo - client.clock = &session.ClusterClock{} - - if client.readConcern == nil { - client.readConcern = readConcernFromConnString(&client.connString) - - if client.readConcern == nil { - // no read concern in conn string - client.readConcern = readconcern.New() - } - } - - if client.writeConcern == nil { - client.writeConcern = writeConcernFromConnString(&client.connString) - } - if client.readPreference == nil { - rp, err := readPreferenceFromConnString(&client.connString) - if err != nil { - return nil, err - } - if rp != nil { - client.readPreference = rp - } else { - client.readPreference = readpref.Primary() - } - } - - if client.registry == nil { - client.registry = bson.DefaultRegistry - } - return client, nil -} - -func readConcernFromConnString(cs *connstring.ConnString) *readconcern.ReadConcern { - if len(cs.ReadConcernLevel) == 0 { - return nil - } - - rc := &readconcern.ReadConcern{} - readconcern.Level(cs.ReadConcernLevel)(rc) - - return rc -} - -func writeConcernFromConnString(cs *connstring.ConnString) *writeconcern.WriteConcern { - var wc *writeconcern.WriteConcern - - if len(cs.WString) > 0 { - if wc == nil { - wc = writeconcern.New() - } - - writeconcern.WTagSet(cs.WString)(wc) - } else if cs.WNumberSet { - if wc == nil { - wc = writeconcern.New() - } - - writeconcern.W(cs.WNumber)(wc) - } - - if cs.JSet { - if wc == nil { - wc = writeconcern.New() - } - - writeconcern.J(cs.J)(wc) - } - - if cs.WTimeoutSet { - if wc == nil { - wc = writeconcern.New() - } - - writeconcern.WTimeout(cs.WTimeout)(wc) - } - - return wc -} - -func readPreferenceFromConnString(cs *connstring.ConnString) (*readpref.ReadPref, error) { - var rp *readpref.ReadPref - var err error - options := make([]readpref.Option, 0, 1) - - tagSets := tag.NewTagSetsFromMaps(cs.ReadPreferenceTagSets) - if len(tagSets) > 0 { - options = append(options, readpref.WithTagSets(tagSets...)) - } - - if cs.MaxStaleness != 0 { - options = append(options, readpref.WithMaxStaleness(cs.MaxStaleness)) - } - - if len(cs.ReadPreference) > 0 { - if rp == nil { - mode, _ := readpref.ModeFromString(cs.ReadPreference) - rp, err = readpref.New(mode, options...) - if err != nil { - return nil, err - } - } - } - - return rp, nil -} - -// ValidSession returns an error if the session doesn't belong to the client -func (c *Client) ValidSession(sess *session.Client) error { - if sess != nil && !uuid.Equal(sess.ClientID, c.id) { - return ErrWrongClient - } - return nil -} - -// Database returns a handle for a given database. -func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database { - return newDatabase(c, name, opts...) -} - -// ConnectionString returns the connection string of the cluster the client is connected to. -func (c *Client) ConnectionString() string { - return c.connString.Original -} - -// ListDatabases returns a ListDatabasesResult. -func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (ListDatabasesResult, error) { - if ctx == nil { - ctx = context.Background() - } - - sess := sessionFromContext(ctx) - - err := c.ValidSession(sess) - if err != nil { - return ListDatabasesResult{}, err - } - - f, err := transformDocument(c.registry, filter) - if err != nil { - return ListDatabasesResult{}, err - } - - cmd := command.ListDatabases{ - Filter: f, - Session: sess, - Clock: c.clock, - } - - res, err := dispatch.ListDatabases( - ctx, cmd, - c.topology, - description.ReadPrefSelector(readpref.Primary()), - c.id, - c.topology.SessionPool, - opts..., - ) - if err != nil { - return ListDatabasesResult{}, replaceTopologyErr(err) - } - - return (ListDatabasesResult{}).fromResult(res), nil -} - -// ListDatabaseNames returns a slice containing the names of all of the databases on the server. -func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string, error) { - opts = append(opts, options.ListDatabases().SetNameOnly(true)) - - res, err := c.ListDatabases(ctx, filter, opts...) - if err != nil { - return nil, err - } - - names := make([]string, 0) - for _, spec := range res.Databases { - names = append(names, spec.Name) - } - - return names, nil -} - -// WithSession allows a user to start a session themselves and manage -// its lifetime. The only way to provide a session to a CRUD method is -// to invoke that CRUD method with the mongo.SessionContext within the -// closure. The mongo.SessionContext can be used as a regular context, -// so methods like context.WithDeadline and context.WithTimeout are -// supported. -// -// If the context.Context already has a mongo.Session attached, that -// mongo.Session will be replaced with the one provided. -// -// Errors returned from the closure are transparently returned from -// this function. -func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error { - return fn(contextWithSession(ctx, sess)) -} - -// UseSession creates a default session, that is only valid for the -// lifetime of the closure. No cleanup outside of closing the session -// is done upon exiting the closure. This means that an outstanding -// transaction will be aborted, even if the closure returns an error. -// -// If ctx already contains a mongo.Session, that mongo.Session will be -// replaced with the newly created mongo.Session. -// -// Errors returned from the closure are transparently returned from -// this method. -func (c *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error { - return c.UseSessionWithOptions(ctx, options.Session(), fn) -} - -// UseSessionWithOptions works like UseSession but allows the caller -// to specify the options used to create the session. -func (c *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, fn func(SessionContext) error) error { - defaultSess, err := c.StartSession(opts) - if err != nil { - return err - } - - defer defaultSess.EndSession(ctx) - - sessCtx := sessionContext{ - Context: context.WithValue(ctx, sessionKey{}, defaultSess), - Session: defaultSess, - } - - return fn(sessCtx) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/cursor.go b/vendor/github.com/mongodb/mongo-go-driver/mongo/cursor.go deleted file mode 100644 index 0685923..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/cursor.go +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package mongo - -import ( - "context" - - "github.com/mongodb/mongo-go-driver/bson" -) - -// Cursor instances iterate a stream of documents. Each document is -// decoded into the result according to the rules of the bson package. -// -// A typical usage of the Cursor interface would be: -// -// var cur Cursor -// ctx := context.Background() -// defer cur.Close(ctx) -// -// for cur.Next(ctx) { -// elem := bson.NewDocument() -// if err := cur.Decode(elem); err != nil { -// log.Fatal(err) -// } -// -// // do something with elem.... -// } -// -// if err := cur.Err(); err != nil { -// log.Fatal(err) -// } -// -type Cursor interface { - // NOTE: Whenever ops.Cursor changes, this must be changed to match it. - - // Get the ID of the cursor. - ID() int64 - - // Get the next result from the cursor. - // Returns true if there were no errors and there is a next result. - Next(context.Context) bool - - Decode(interface{}) error - - DecodeBytes() (bson.Raw, error) - - // Returns the error status of the cursor - Err() error - - // Close the cursor. - Close(context.Context) error -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/doc.go b/vendor/github.com/mongodb/mongo-go-driver/mongo/doc.go deleted file mode 100644 index ffa41a8..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/doc.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -// Package mongo provides a MongoDB Driver API for Go. -// -// Basic usage of the driver starts with creating a Client from a connection -// string. To do so, call the NewClient and Connect functions: -// -// client, err := mongo.NewClient("mongodb://foo:bar@localhost:27017") -// if err != nil { log.Fatal(err) } -// err = client.Connect(context.TODO()) -// if err != nil { log.Fatal(err) } -// -// This will create a new client and start monitoring the MongoDB server on localhost. -// The Database and Collection types can be used to access the database: -// -// collection := client.Database("baz").Collection("qux") -// -// A Collection can be used to query the database or insert documents: -// -// res, err := collection.InsertOne(context.Background(), map[string]string{"hello": "world"}) -// if err != nil { log.Fatal(err) } -// id := res.InsertedID -// -// Several methods return a cursor, which can be used like this: -// -// cur, err := collection.Find(context.Background(), nil) -// if err != nil { log.Fatal(err) } -// defer cur.Close(context.Background()) -// for cur.Next(context.Background()) { -// elem := bson.NewDocument() -// err := cur.Decode(elem) -// if err != nil { log.Fatal(err) } -// // do something with elem.... -// } -// if err := cur.Err(); err != nil { -// log.Fatal(err) -// } -// -// Methods that only return a single document will return a *DocumentResult, which works -// like a *sql.Row: -// -// result := bson.NewDocument() -// filter := bson.NewDocument(bson.EC.String("hello", "world")) -// err := collection.FindOne(context.Background(), filter).Decode(result) -// if err != nil { log.Fatal(err) } -// // do something with result... -// -// Additional examples can be found under the examples directory in the driver's repository and -// on the MongoDB website. -package mongo diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/document_result.go b/vendor/github.com/mongodb/mongo-go-driver/mongo/document_result.go deleted file mode 100644 index 5647855..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/document_result.go +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package mongo - -import ( - "context" - "errors" - - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" -) - -// ErrNoDocuments is returned by Decode when an operation that returns a -// DocumentResult doesn't return any documents. -var ErrNoDocuments = errors.New("mongo: no documents in result") - -// DocumentResult represents a single document returned from an operation. If -// the operation returned an error, the Err method of DocumentResult will -// return that error. -type DocumentResult struct { - err error - cur Cursor - rdr bson.Raw - reg *bsoncodec.Registry -} - -// Decode will attempt to decode the first document into v. If there was an -// error from the operation that created this DocumentResult then the error -// will be returned. If there were no returned documents, ErrNoDocuments is -// returned. -func (dr *DocumentResult) Decode(v interface{}) error { - switch { - case dr.err != nil: - return dr.err - case dr.rdr != nil: - if v == nil { - return nil - } - return bson.UnmarshalWithRegistry(dr.reg, dr.rdr, v) - case dr.cur != nil: - defer dr.cur.Close(context.TODO()) - if !dr.cur.Next(context.TODO()) { - if err := dr.cur.Err(); err != nil { - return err - } - return ErrNoDocuments - } - if v == nil { - return nil - } - return dr.cur.Decode(v) - } - - return ErrNoDocuments -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/clientoptions.go b/vendor/github.com/mongodb/mongo-go-driver/options/clientoptions.go deleted file mode 100644 index a2b5f00..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/options/clientoptions.go +++ /dev/null @@ -1,417 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package options - -import ( - "context" - "net" - "time" - - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/connection" - "github.com/mongodb/mongo-go-driver/core/connstring" - "github.com/mongodb/mongo-go-driver/core/event" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" -) - -// ContextDialer makes new network connections -type ContextDialer interface { - DialContext(ctx context.Context, network, address string) (net.Conn, error) -} - -// SSLOpt holds client SSL options. -// -// Enabled indicates whether SSL should be enabled. -// -// ClientCertificateKeyFile specifies the file containing the client certificate and private key -// used for authentication. -// -// ClientCertificateKeyPassword provides a callback that returns a password used for decrypting the -// private key of a PEM file (if one is provided). -// -// Insecure indicates whether to skip the verification of the server certificate and hostname. -// -// CaFile specifies the file containing the certificate authority used for SSL connections. -type SSLOpt struct { - Enabled bool - ClientCertificateKeyFile string - ClientCertificateKeyPassword func() string - Insecure bool - CaFile string -} - -// Credential holds auth options. -// -// AuthMechanism indicates the mechanism to use for authentication. -// Supported values include "SCRAM-SHA-256", "SCRAM-SHA-1", "MONGODB-CR", "PLAIN", "GSSAPI", and "MONGODB-X509". -// -// AuthMechanismProperties specifies additional configuration options which may be used by certain -// authentication mechanisms. -// -// AuthSource specifies the database to authenticate against. -// -// Username specifies the username that will be authenticated. -// -// Password specifies the password used for authentication. -type Credential struct { - AuthMechanism string - AuthMechanismProperties map[string]string - AuthSource string - Username string - Password string -} - -// ClientOptions represents all possbile options to configure a client. -type ClientOptions struct { - TopologyOptions []topology.Option - ConnString connstring.ConnString - RetryWrites *bool - ReadPreference *readpref.ReadPref - ReadConcern *readconcern.ReadConcern - WriteConcern *writeconcern.WriteConcern - Registry *bsoncodec.Registry -} - -// Client creates a new ClientOptions instance. -func Client() *ClientOptions { - return &ClientOptions{ - TopologyOptions: make([]topology.Option, 0), - } -} - -// SetAppName specifies the client application name. This value is used by MongoDB when it logs -// connection information and profile information, such as slow queries. -func (c *ClientOptions) SetAppName(s string) *ClientOptions { - c.ConnString.AppName = s - - return c -} - -// SetAuth sets the authentication options. -func (c *ClientOptions) SetAuth(auth Credential) *ClientOptions { - c.ConnString.AuthMechanism = auth.AuthMechanism - c.ConnString.AuthMechanismProperties = auth.AuthMechanismProperties - c.ConnString.AuthSource = auth.AuthSource - c.ConnString.Username = auth.Username - c.ConnString.Password = auth.Password - - return c -} - -// SetConnectTimeout specifies the timeout for an initial connection to a server. -// If a custom Dialer is used, this method won't be set and the user is -// responsible for setting the ConnectTimeout for connections on the dialer -// themselves. -func (c *ClientOptions) SetConnectTimeout(d time.Duration) *ClientOptions { - c.ConnString.ConnectTimeout = d - c.ConnString.ConnectTimeoutSet = true - - return c -} - -// SetDialer specifies a custom dialer used to dial new connections to a server. -func (c *ClientOptions) SetDialer(d ContextDialer) *ClientOptions { - c.TopologyOptions = append( - c.TopologyOptions, - topology.WithServerOptions(func(opts ...topology.ServerOption) []topology.ServerOption { - return append( - opts, - topology.WithConnectionOptions(func(opts ...connection.Option) []connection.Option { - return append( - opts, - connection.WithDialer(func(connection.Dialer) connection.Dialer { - return d - }), - ) - }), - ) - }), - ) - - return c -} - -// SetMonitor specifies a command monitor used to see commands for a client. -func (c *ClientOptions) SetMonitor(m *event.CommandMonitor) *ClientOptions { - c.TopologyOptions = append( - c.TopologyOptions, - topology.WithServerOptions(func(opts ...topology.ServerOption) []topology.ServerOption { - return append( - opts, - topology.WithConnectionOptions(func(opts ...connection.Option) []connection.Option { - return append( - opts, - connection.WithMonitor(func(*event.CommandMonitor) *event.CommandMonitor { - return m - }), - ) - }), - ) - }), - ) - - return c -} - -// SetHeartbeatInterval specifies the interval to wait between server monitoring checks. -func (c *ClientOptions) SetHeartbeatInterval(d time.Duration) *ClientOptions { - c.ConnString.HeartbeatInterval = d - c.ConnString.HeartbeatIntervalSet = true - - return c -} - -// SetHosts specifies the initial list of addresses from which to discover the rest of the cluster. -func (c *ClientOptions) SetHosts(s []string) *ClientOptions { - c.ConnString.Hosts = s - - return c -} - -// SetLocalThreshold specifies how far to distribute queries, beyond the server with the fastest -// round-trip time. If a server's roundtrip time is more than LocalThreshold slower than the -// the fastest, the driver will not send queries to that server. -func (c *ClientOptions) SetLocalThreshold(d time.Duration) *ClientOptions { - c.ConnString.LocalThreshold = d - c.ConnString.LocalThresholdSet = true - - return c -} - -// SetMaxConnIdleTime specifies the maximum number of milliseconds that a connection can remain idle -// in a connection pool before being removed and closed. -func (c *ClientOptions) SetMaxConnIdleTime(d time.Duration) *ClientOptions { - c.ConnString.MaxConnIdleTime = d - c.ConnString.MaxConnIdleTimeSet = true - - return c -} - -// SetMaxConnsPerHost specifies the max size of a server's connection pool. -func (c *ClientOptions) SetMaxConnsPerHost(u uint16) *ClientOptions { - c.ConnString.MaxConnsPerHost = u - c.ConnString.MaxConnsPerHostSet = true - - return c -} - -// SetMaxIdleConnsPerHost specifies the number of connections in a server's connection pool that can -// be idle at any given time. -func (c *ClientOptions) SetMaxIdleConnsPerHost(u uint16) *ClientOptions { - c.ConnString.MaxIdleConnsPerHost = u - c.ConnString.MaxIdleConnsPerHostSet = true - - return c -} - -// SetReadConcern specifies the read concern. -func (c *ClientOptions) SetReadConcern(rc *readconcern.ReadConcern) *ClientOptions { - c.ReadConcern = rc - - return c -} - -// SetReadPreference specifies the read preference. -func (c *ClientOptions) SetReadPreference(rp *readpref.ReadPref) *ClientOptions { - c.ReadPreference = rp - - return c -} - -// SetRegistry specifies the bsoncodec.Registry. -func (c *ClientOptions) SetRegistery(registry *bsoncodec.Registry) *ClientOptions { - c.Registry = registry - - return c -} - -// SetReplicaSet specifies the name of the replica set of the cluster. -func (c *ClientOptions) SetReplicaSet(s string) *ClientOptions { - c.ConnString.ReplicaSet = s - - return c -} - -// SetRetryWrites specifies whether the client has retryable writes enabled. -func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions { - c.RetryWrites = &b - - return c -} - -// SetServerSelectionTimeout specifies a timeout in milliseconds to block for server selection. -func (c *ClientOptions) SetServerSelectionTimeout(d time.Duration) *ClientOptions { - c.ConnString.ServerSelectionTimeout = d - c.ConnString.ServerSelectionTimeoutSet = true - - return c -} - -// SetSingle specifies whether the driver should connect directly to the server instead of -// auto-discovering other servers in the cluster. -func (c *ClientOptions) SetSingle(b bool) *ClientOptions { - if b { - c.ConnString.Connect = connstring.SingleConnect - } else { - c.ConnString.Connect = connstring.AutoConnect - } - c.ConnString.ConnectSet = true - - return c -} - -// SetSocketTimeout specifies the time in milliseconds to attempt to send or receive on a socket -// before the attempt times out. -func (c *ClientOptions) SetSocketTimeout(d time.Duration) *ClientOptions { - c.ConnString.SocketTimeout = d - c.ConnString.SocketTimeoutSet = true - - return c -} - -// SetSSL sets SSL options. -func (c *ClientOptions) SetSSL(ssl *SSLOpt) *ClientOptions { - c.ConnString.SSL = ssl.Enabled - c.ConnString.SSLSet = true - - c.ConnString.SSLClientCertificateKeyFile = ssl.ClientCertificateKeyFile - c.ConnString.SSLClientCertificateKeyFileSet = true - - c.ConnString.SSLClientCertificateKeyPassword = ssl.ClientCertificateKeyPassword - c.ConnString.SSLClientCertificateKeyPasswordSet = true - - c.ConnString.SSLInsecure = ssl.Insecure - c.ConnString.SSLInsecureSet = true - - c.ConnString.SSLCaFile = ssl.CaFile - c.ConnString.SSLCaFileSet = true - - return c -} - -// SetWriteConcern sets the write concern. -func (c *ClientOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *ClientOptions { - c.WriteConcern = wc - - return c -} - -// MergeClientOptions combines the given connstring and *ClientOptions into a single *ClientOptions in a last one wins -// fashion. The given connstring will be used for the default options, which can be overwritten using the given -// *ClientOptions. -func MergeClientOptions(cs connstring.ConnString, opts ...*ClientOptions) *ClientOptions { - c := Client() - c.ConnString = cs - - for _, opt := range opts { - if opt == nil { - continue - } - c.TopologyOptions = append(c.TopologyOptions, opt.TopologyOptions...) - - if an := opt.ConnString.AppName; an != "" { - c.ConnString.AppName = an - } - if am := opt.ConnString.AuthMechanism; len(am) != 0 { - c.ConnString.AuthMechanism = am - } - if amp := opt.ConnString.AuthMechanismProperties; amp != nil { - c.ConnString.AuthMechanismProperties = amp - } - if as := opt.ConnString.AuthSource; len(as) != 0 { - c.ConnString.AuthSource = as - } - if u := opt.ConnString.Username; len(u) != 0 { - c.ConnString.Username = u - } - if p := opt.ConnString.Password; len(p) != 0 { - c.ConnString.Password = p - } - if opt.ConnString.ConnectTimeoutSet { - c.ConnString.ConnectTimeoutSet = true - c.ConnString.ConnectTimeout = opt.ConnString.ConnectTimeout - } - if opt.ConnString.HeartbeatIntervalSet { - c.ConnString.HeartbeatIntervalSet = true - c.ConnString.HeartbeatInterval = opt.ConnString.HeartbeatInterval - } - if h := opt.ConnString.Hosts; h != nil { - c.ConnString.Hosts = h - } - if opt.ConnString.LocalThresholdSet { - c.ConnString.LocalThresholdSet = true - c.ConnString.LocalThreshold = opt.ConnString.LocalThreshold - } - if opt.ConnString.MaxConnIdleTimeSet { - c.ConnString.MaxConnIdleTimeSet = true - c.ConnString.MaxConnIdleTime = opt.ConnString.MaxConnIdleTime - } - if opt.ConnString.MaxConnsPerHostSet { - c.ConnString.MaxConnsPerHostSet = true - c.ConnString.MaxConnsPerHost = opt.ConnString.MaxConnsPerHost - } - if opt.ConnString.MaxIdleConnsPerHostSet { - c.ConnString.MaxIdleConnsPerHostSet = true - c.ConnString.MaxIdleConnsPerHost = opt.ConnString.MaxIdleConnsPerHost - } - if opt.ReadConcern != nil { - c.ReadConcern = opt.ReadConcern - } - if opt.ReadPreference != nil { - c.ReadPreference = opt.ReadPreference - } - if opt.Registry != nil { - c.Registry = opt.Registry - } - if rs := opt.ConnString.ReplicaSet; rs != "" { - c.ConnString.ReplicaSet = rs - } - if opt.RetryWrites != nil { - c.RetryWrites = opt.RetryWrites - } - if opt.ConnString.ServerSelectionTimeoutSet { - c.ConnString.ServerSelectionTimeoutSet = true - c.ConnString.ServerSelectionTimeout = opt.ConnString.ServerSelectionTimeout - } - if opt.ConnString.ConnectSet { - c.ConnString.ConnectSet = true - c.ConnString.Connect = opt.ConnString.Connect - } - if opt.ConnString.SocketTimeoutSet { - c.ConnString.SocketTimeoutSet = true - c.ConnString.SocketTimeout = opt.ConnString.SocketTimeout - } - if opt.ConnString.SSLSet { - c.ConnString.SSLSet = true - c.ConnString.SSL = opt.ConnString.SSL - } - if opt.ConnString.SSLClientCertificateKeyFileSet { - c.ConnString.SSLClientCertificateKeyFileSet = true - c.ConnString.SSLClientCertificateKeyFile = opt.ConnString.SSLClientCertificateKeyFile - } - if opt.ConnString.SSLClientCertificateKeyPasswordSet { - c.ConnString.SSLClientCertificateKeyPasswordSet = true - c.ConnString.SSLClientCertificateKeyPassword = opt.ConnString.SSLClientCertificateKeyPassword - } - if opt.ConnString.SSLInsecureSet { - c.ConnString.SSLInsecureSet = true - c.ConnString.SSLInsecure = opt.ConnString.SSLInsecure - } - if opt.ConnString.SSLCaFileSet { - c.ConnString.SSLCaFileSet = true - c.ConnString.SSLCaFile = opt.ConnString.SSLCaFile - } - if opt.WriteConcern != nil { - c.WriteConcern = opt.WriteConcern - } - } - - return c -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/indexoptions.go b/vendor/github.com/mongodb/mongo-go-driver/options/indexoptions.go deleted file mode 100644 index 732670e..0000000 --- a/vendor/github.com/mongodb/mongo-go-driver/options/indexoptions.go +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2017-present. -// -// Licensed under the Apache License, Version 2.0 (the "License"); you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 - -package options - -import "time" - -// CreateIndexesOptions represents all possible options for the create() function. -type CreateIndexesOptions struct { - MaxTime *time.Duration // The maximum amount of time to allow the query to run. -} - -// CreateIndexes creates a new CreateIndexesOptions instance. -func CreateIndexes() *CreateIndexesOptions { - return &CreateIndexesOptions{} -} - -// SetMaxTime specifies the maximum amount of time to allow the query to run. -func (c *CreateIndexesOptions) SetMaxTime(d time.Duration) *CreateIndexesOptions { - c.MaxTime = &d - return c -} - -// MergeCreateIndexesOptions combines the given *CreateIndexesOptions into a single *CreateIndexesOptions in a last one -// wins fashion. -func MergeCreateIndexesOptions(opts ...*CreateIndexesOptions) *CreateIndexesOptions { - c := CreateIndexes() - for _, opt := range opts { - if opt == nil { - continue - } - if opt.MaxTime != nil { - c.MaxTime = opt.MaxTime - } - } - - return c -} - -// DropIndexesOptions represents all possible options for the create() function. -type DropIndexesOptions struct { - MaxTime *time.Duration -} - -// DropIndexes creates a new DropIndexesOptions instance. -func DropIndexes() *DropIndexesOptions { - return &DropIndexesOptions{} -} - -// SetMaxTime specifies the maximum amount of time to allow the query to run. -func (d *DropIndexesOptions) SetMaxTime(duration time.Duration) *DropIndexesOptions { - d.MaxTime = &duration - return d -} - -// MergeDropIndexesOptions combines the given *DropIndexesOptions into a single *DropIndexesOptions in a last one -// wins fashion. -func MergeDropIndexesOptions(opts ...*DropIndexesOptions) *DropIndexesOptions { - c := DropIndexes() - for _, opt := range opts { - if opt == nil { - continue - } - if opt.MaxTime != nil { - c.MaxTime = opt.MaxTime - } - } - - return c -} - -// ListIndexesOptions represents all possible options for the create() function. -type ListIndexesOptions struct { - BatchSize *int32 - MaxTime *time.Duration -} - -// ListIndexes creates a new ListIndexesOptions instance. -func ListIndexes() *ListIndexesOptions { - return &ListIndexesOptions{} -} - -// BatchSize specifies the number of documents to return in every batch. -func (l *ListIndexesOptions) SetBatchSize(i int32) *ListIndexesOptions { - l.BatchSize = &i - return l -} - -// SetMaxTime specifies the maximum amount of time to allow the query to run. -func (l *ListIndexesOptions) SetMaxTime(d time.Duration) *ListIndexesOptions { - l.MaxTime = &d - return l -} - -// MergeListIndexesOptions combines the given *ListIndexesOptions into a single *ListIndexesOptions in a last one -// wins fashion. -func MergeListIndexesOptions(opts ...*ListIndexesOptions) *ListIndexesOptions { - c := ListIndexes() - for _, opt := range opts { - if opt == nil { - continue - } - if opt.MaxTime != nil { - c.MaxTime = opt.MaxTime - } - } - - return c -} diff --git a/vendor/github.com/xdg/stringprep/.travis.yml b/vendor/github.com/xdg/stringprep/.travis.yml index 376c53a..f391327 100644 --- a/vendor/github.com/xdg/stringprep/.travis.yml +++ b/vendor/github.com/xdg/stringprep/.travis.yml @@ -1,9 +1,10 @@ language: go sudo: false go: - - 1.7 - - 1.8 - - 1.9 + - "1.7" + - "1.8" + - "1.9" + - "1.10" - master matrix: allow_failures: diff --git a/vendor/github.com/mongodb/mongo-go-driver/LICENSE b/vendor/go.mongodb.org/mongo-driver/LICENSE similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/LICENSE rename to vendor/go.mongodb.org/mongo-driver/LICENSE diff --git a/vendor/github.com/mongodb/mongo-go-driver/THIRD-PARTY-NOTICES b/vendor/go.mongodb.org/mongo-driver/THIRD-PARTY-NOTICES similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/THIRD-PARTY-NOTICES rename to vendor/go.mongodb.org/mongo-driver/THIRD-PARTY-NOTICES diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bson.go b/vendor/go.mongodb.org/mongo-driver/bson/bson.go new file mode 100644 index 0000000..37bf981 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/bson.go @@ -0,0 +1,60 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 +// +// Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer +// See THIRD-PARTY-NOTICES for original license terms. + +// +build go1.9 + +package bson // import "go.mongodb.org/mongo-driver/bson" + +import ( + "go.mongodb.org/mongo-driver/bson/primitive" +) + +// Zeroer allows custom struct types to implement a report of zero +// state. All struct types that don't implement Zeroer or where IsZero +// returns false are considered to be not zero. +type Zeroer interface { + IsZero() bool +} + +// D represents a BSON Document. This type can be used to represent BSON in a concise and readable +// manner. It should generally be used when serializing to BSON. For deserializing, the Raw or +// Document types should be used. +// +// Example usage: +// +// bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}} +// +// This type should be used in situations where order matters, such as MongoDB commands. If the +// order is not important, a map is more comfortable and concise. +type D = primitive.D + +// E represents a BSON element for a D. It is usually used inside a D. +type E = primitive.E + +// M is an unordered, concise representation of a BSON Document. It should generally be used to +// serialize BSON when the order of the elements of a BSON document do not matter. If the element +// order matters, use a D instead. +// +// Example usage: +// +// bson.M{"foo": "bar", "hello": "world", "pi": 3.14159} +// +// This type is handled in the encoders as a regular map[string]interface{}. The elements will be +// serialized in an undefined, random order, and the order will be different each time. +type M = primitive.M + +// An A represents a BSON array. This type can be used to represent a BSON array in a concise and +// readable manner. It should generally be used when serializing to BSON. For deserializing, the +// RawArray or Array types should be used. +// +// Example usage: +// +// bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}} +// +type A = primitive.A diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bson.go b/vendor/go.mongodb.org/mongo-driver/bson/bson_1_8.go similarity index 88% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bson.go rename to vendor/go.mongodb.org/mongo-driver/bson/bson_1_8.go index c6664db..caf5f50 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bson.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bson_1_8.go @@ -3,11 +3,10 @@ // Licensed under the Apache License, Version 2.0 (the "License"); you may // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -// -// Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer -// See THIRD-PARTY-NOTICES for original license terms. -package bson +// +build !go1.9 + +package bson // import "go.mongodb.org/mongo-driver/bson" import ( "math" @@ -28,7 +27,7 @@ type Zeroer interface { // // Example usage: // -// bson.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}} +// primitive.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}} // // This type should be used in situations where order matters, such as MongoDB commands. If the // order is not important, a map is more comfortable and concise. @@ -55,7 +54,7 @@ type E struct { // // Example usage: // -// bson.M{"foo": "bar", "hello": "world", "pi": 3.14159} +// primitive.M{"foo": "bar", "hello": "world", "pi": 3.14159} // // This type is handled in the encoders as a regular map[string]interface{}. The elements will be // serialized in an undefined, random order, and the order will be different each time. @@ -67,7 +66,7 @@ type M map[string]interface{} // // Example usage: // -// bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}} +// primitive.A{"bar", "world", 3.14159, primitive.D{{"qux", 12345}}} // type A []interface{} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/bsoncodec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go similarity index 57% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/bsoncodec.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go index 73a9da7..0ebc9a1 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/bsoncodec.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/bsoncodec.go @@ -4,14 +4,15 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package bsoncodec +package bsoncodec // import "go.mongodb.org/mongo-driver/bson/bsoncodec" import ( "fmt" + "reflect" "strings" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" ) // Marshaler is an interface implemented by types that can marshal themselves @@ -45,36 +46,60 @@ type ValueUnmarshaler interface { UnmarshalBSONValue(bsontype.Type, []byte) error } -// ValueEncoderError is an error returned from a ValueEncoder when the provided -// value can't be encoded by the ValueEncoder. +// ValueEncoderError is an error returned from a ValueEncoder when the provided value can't be +// encoded by the ValueEncoder. type ValueEncoderError struct { Name string - Types []interface{} - Received interface{} + Types []reflect.Type + Kinds []reflect.Kind + Received reflect.Value } func (vee ValueEncoderError) Error() string { - types := make([]string, 0, len(vee.Types)) + typeKinds := make([]string, 0, len(vee.Types)+len(vee.Kinds)) for _, t := range vee.Types { - types = append(types, fmt.Sprintf("%T", t)) + typeKinds = append(typeKinds, t.String()) } - return fmt.Sprintf("%s can only process %s, but got a %T", vee.Name, strings.Join(types, ", "), vee.Received) + for _, k := range vee.Kinds { + if k == reflect.Map { + typeKinds = append(typeKinds, "map[string]*") + continue + } + typeKinds = append(typeKinds, k.String()) + } + received := vee.Received.Kind().String() + if vee.Received.IsValid() { + received = vee.Received.Type().String() + } + return fmt.Sprintf("%s can only encode valid %s, but got %s", vee.Name, strings.Join(typeKinds, ", "), received) } -// ValueDecoderError is an error returned from a ValueDecoder when the provided -// value can't be decoded by the ValueDecoder. +// ValueDecoderError is an error returned from a ValueDecoder when the provided value can't be +// decoded by the ValueDecoder. type ValueDecoderError struct { Name string - Types []interface{} - Received interface{} + Types []reflect.Type + Kinds []reflect.Kind + Received reflect.Value } func (vde ValueDecoderError) Error() string { - types := make([]string, 0, len(vde.Types)) + typeKinds := make([]string, 0, len(vde.Types)+len(vde.Kinds)) for _, t := range vde.Types { - types = append(types, fmt.Sprintf("%T", t)) + typeKinds = append(typeKinds, t.String()) + } + for _, k := range vde.Kinds { + if k == reflect.Map { + typeKinds = append(typeKinds, "map[string]*") + continue + } + typeKinds = append(typeKinds, k.String()) + } + received := vde.Received.Kind().String() + if vde.Received.IsValid() { + received = vde.Received.Type().String() } - return fmt.Sprintf("%s can only process %s, but got a %T", vde.Name, strings.Join(types, ", "), vde.Received) + return fmt.Sprintf("%s can only decode valid and settable %s, but got %s", vde.Name, strings.Join(typeKinds, ", "), received) } // EncodeContext is the contextual information required for a Codec to encode a @@ -89,6 +114,11 @@ type EncodeContext struct { type DecodeContext struct { *Registry Truncate bool + // Ancestor is the type of a containing document. This is mainly used to determine what type + // should be used when decoding an embedded document into an empty interface. For example, if + // Ancestor is a bson.M, BSON embedded document values being decoded into an empty interface + // will be decoded into a bson.M. + Ancestor reflect.Type } // ValueCodec is the interface that groups the methods to encode and decode @@ -98,36 +128,31 @@ type ValueCodec interface { ValueDecoder } -// ValueEncoder is the interface implemented by types that can handle the -// encoding of a value. Implementations must handle both values and -// pointers to values. +// ValueEncoder is the interface implemented by types that can handle the encoding of a value. type ValueEncoder interface { - EncodeValue(EncodeContext, bsonrw.ValueWriter, interface{}) error + EncodeValue(EncodeContext, bsonrw.ValueWriter, reflect.Value) error } -// ValueEncoderFunc is an adapter function that allows a function with the -// correct signature to be used as a ValueEncoder. -type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, interface{}) error +// ValueEncoderFunc is an adapter function that allows a function with the correct signature to be +// used as a ValueEncoder. +type ValueEncoderFunc func(EncodeContext, bsonrw.ValueWriter, reflect.Value) error // EncodeValue implements the ValueEncoder interface. -func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val interface{}) error { +func (fn ValueEncoderFunc) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { return fn(ec, vw, val) } -// ValueDecoder is the interface implemented by types that can handle the -// decoding of a value. Implementations must handle pointers to values, -// including pointers to pointer values. The implementation may create a new -// value and assign it to the pointer if necessary. +// ValueDecoder is the interface implemented by types that can handle the decoding of a value. type ValueDecoder interface { - DecodeValue(DecodeContext, bsonrw.ValueReader, interface{}) error + DecodeValue(DecodeContext, bsonrw.ValueReader, reflect.Value) error } -// ValueDecoderFunc is an adapter function that allows a function with the -// correct signature to be used as a ValueDecoder. -type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, interface{}) error +// ValueDecoderFunc is an adapter function that allows a function with the correct signature to be +// used as a ValueDecoder. +type ValueDecoderFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) error // DecodeValue implements the ValueDecoder interface. -func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val interface{}) error { +func (fn ValueDecoderFunc) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { return fn(dc, vr, val) } diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go new file mode 100644 index 0000000..65cd1c0 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_decoders.go @@ -0,0 +1,1014 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package bsoncodec + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "net/url" + "reflect" + "strconv" + "time" + + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" +) + +var defaultValueDecoders DefaultValueDecoders + +// DefaultValueDecoders is a namespace type for the default ValueDecoders used +// when creating a registry. +type DefaultValueDecoders struct{} + +// RegisterDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with +// the provided RegistryBuilder. +// +// There is no support for decoding map[string]interface{} becuase there is no decoder for +// interface{}, so users must either register this decoder themselves or use the +// EmptyInterfaceDecoder avaialble in the bson package. +func (dvd DefaultValueDecoders) RegisterDefaultDecoders(rb *RegistryBuilder) { + if rb == nil { + panic(errors.New("argument to RegisterDefaultDecoders must not be nil")) + } + + rb. + RegisterDecoder(tBinary, ValueDecoderFunc(dvd.BinaryDecodeValue)). + RegisterDecoder(tUndefined, ValueDecoderFunc(dvd.UndefinedDecodeValue)). + RegisterDecoder(tDateTime, ValueDecoderFunc(dvd.DateTimeDecodeValue)). + RegisterDecoder(tNull, ValueDecoderFunc(dvd.NullDecodeValue)). + RegisterDecoder(tRegex, ValueDecoderFunc(dvd.RegexDecodeValue)). + RegisterDecoder(tDBPointer, ValueDecoderFunc(dvd.DBPointerDecodeValue)). + RegisterDecoder(tTimestamp, ValueDecoderFunc(dvd.TimestampDecodeValue)). + RegisterDecoder(tMinKey, ValueDecoderFunc(dvd.MinKeyDecodeValue)). + RegisterDecoder(tMaxKey, ValueDecoderFunc(dvd.MaxKeyDecodeValue)). + RegisterDecoder(tJavaScript, ValueDecoderFunc(dvd.JavaScriptDecodeValue)). + RegisterDecoder(tSymbol, ValueDecoderFunc(dvd.SymbolDecodeValue)). + RegisterDecoder(tByteSlice, ValueDecoderFunc(dvd.ByteSliceDecodeValue)). + RegisterDecoder(tTime, ValueDecoderFunc(dvd.TimeDecodeValue)). + RegisterDecoder(tEmpty, ValueDecoderFunc(dvd.EmptyInterfaceDecodeValue)). + RegisterDecoder(tOID, ValueDecoderFunc(dvd.ObjectIDDecodeValue)). + RegisterDecoder(tDecimal, ValueDecoderFunc(dvd.Decimal128DecodeValue)). + RegisterDecoder(tJSONNumber, ValueDecoderFunc(dvd.JSONNumberDecodeValue)). + RegisterDecoder(tURL, ValueDecoderFunc(dvd.URLDecodeValue)). + RegisterDecoder(tValueUnmarshaler, ValueDecoderFunc(dvd.ValueUnmarshalerDecodeValue)). + RegisterDecoder(tUnmarshaler, ValueDecoderFunc(dvd.UnmarshalerDecodeValue)). + RegisterDecoder(tCoreDocument, ValueDecoderFunc(dvd.CoreDocumentDecodeValue)). + RegisterDecoder(tCodeWithScope, ValueDecoderFunc(dvd.CodeWithScopeDecodeValue)). + RegisterDefaultDecoder(reflect.Bool, ValueDecoderFunc(dvd.BooleanDecodeValue)). + RegisterDefaultDecoder(reflect.Int, ValueDecoderFunc(dvd.IntDecodeValue)). + RegisterDefaultDecoder(reflect.Int8, ValueDecoderFunc(dvd.IntDecodeValue)). + RegisterDefaultDecoder(reflect.Int16, ValueDecoderFunc(dvd.IntDecodeValue)). + RegisterDefaultDecoder(reflect.Int32, ValueDecoderFunc(dvd.IntDecodeValue)). + RegisterDefaultDecoder(reflect.Int64, ValueDecoderFunc(dvd.IntDecodeValue)). + RegisterDefaultDecoder(reflect.Uint, ValueDecoderFunc(dvd.UintDecodeValue)). + RegisterDefaultDecoder(reflect.Uint8, ValueDecoderFunc(dvd.UintDecodeValue)). + RegisterDefaultDecoder(reflect.Uint16, ValueDecoderFunc(dvd.UintDecodeValue)). + RegisterDefaultDecoder(reflect.Uint32, ValueDecoderFunc(dvd.UintDecodeValue)). + RegisterDefaultDecoder(reflect.Uint64, ValueDecoderFunc(dvd.UintDecodeValue)). + RegisterDefaultDecoder(reflect.Float32, ValueDecoderFunc(dvd.FloatDecodeValue)). + RegisterDefaultDecoder(reflect.Float64, ValueDecoderFunc(dvd.FloatDecodeValue)). + RegisterDefaultDecoder(reflect.Array, ValueDecoderFunc(dvd.ArrayDecodeValue)). + RegisterDefaultDecoder(reflect.Map, ValueDecoderFunc(dvd.MapDecodeValue)). + RegisterDefaultDecoder(reflect.Slice, ValueDecoderFunc(dvd.SliceDecodeValue)). + RegisterDefaultDecoder(reflect.String, ValueDecoderFunc(dvd.StringDecodeValue)). + RegisterDefaultDecoder(reflect.Struct, &StructCodec{cache: make(map[reflect.Type]*structDescription), parser: DefaultStructTagParser}). + RegisterDefaultDecoder(reflect.Ptr, NewPointerCodec()). + RegisterTypeMapEntry(bsontype.Double, tFloat64). + RegisterTypeMapEntry(bsontype.String, tString). + RegisterTypeMapEntry(bsontype.Array, tA). + RegisterTypeMapEntry(bsontype.Binary, tBinary). + RegisterTypeMapEntry(bsontype.Undefined, tUndefined). + RegisterTypeMapEntry(bsontype.ObjectID, tOID). + RegisterTypeMapEntry(bsontype.Boolean, tBool). + RegisterTypeMapEntry(bsontype.DateTime, tDateTime). + RegisterTypeMapEntry(bsontype.Regex, tRegex). + RegisterTypeMapEntry(bsontype.DBPointer, tDBPointer). + RegisterTypeMapEntry(bsontype.JavaScript, tJavaScript). + RegisterTypeMapEntry(bsontype.Symbol, tSymbol). + RegisterTypeMapEntry(bsontype.CodeWithScope, tCodeWithScope). + RegisterTypeMapEntry(bsontype.Int32, tInt32). + RegisterTypeMapEntry(bsontype.Int64, tInt64). + RegisterTypeMapEntry(bsontype.Timestamp, tTimestamp). + RegisterTypeMapEntry(bsontype.Decimal128, tDecimal). + RegisterTypeMapEntry(bsontype.MinKey, tMinKey). + RegisterTypeMapEntry(bsontype.MaxKey, tMaxKey). + RegisterTypeMapEntry(bsontype.Type(0), tD) +} + +// BooleanDecodeValue is the ValueDecoderFunc for bool types. +func (dvd DefaultValueDecoders) BooleanDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if vr.Type() != bsontype.Boolean { + return fmt.Errorf("cannot decode %v into a boolean", vr.Type()) + } + if !val.IsValid() || !val.CanSet() || val.Kind() != reflect.Bool { + return ValueDecoderError{Name: "BooleanDecodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val} + } + + b, err := vr.ReadBoolean() + val.SetBool(b) + return err +} + +// IntDecodeValue is the ValueDecoderFunc for bool types. +func (dvd DefaultValueDecoders) IntDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + var i64 int64 + var err error + switch vr.Type() { + case bsontype.Int32: + i32, err := vr.ReadInt32() + if err != nil { + return err + } + i64 = int64(i32) + case bsontype.Int64: + i64, err = vr.ReadInt64() + if err != nil { + return err + } + case bsontype.Double: + f64, err := vr.ReadDouble() + if err != nil { + return err + } + if !dc.Truncate && math.Floor(f64) != f64 { + return errors.New("IntDecodeValue can only truncate float64 to an integer type when truncation is enabled") + } + if f64 > float64(math.MaxInt64) { + return fmt.Errorf("%g overflows int64", f64) + } + i64 = int64(f64) + default: + return fmt.Errorf("cannot decode %v into an integer type", vr.Type()) + } + + if !val.CanSet() { + return ValueDecoderError{ + Name: "IntDecodeValue", + Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, + Received: val, + } + } + + switch val.Kind() { + case reflect.Int8: + if i64 < math.MinInt8 || i64 > math.MaxInt8 { + return fmt.Errorf("%d overflows int8", i64) + } + case reflect.Int16: + if i64 < math.MinInt16 || i64 > math.MaxInt16 { + return fmt.Errorf("%d overflows int16", i64) + } + case reflect.Int32: + if i64 < math.MinInt32 || i64 > math.MaxInt32 { + return fmt.Errorf("%d overflows int32", i64) + } + case reflect.Int64: + case reflect.Int: + if int64(int(i64)) != i64 { // Can we fit this inside of an int + return fmt.Errorf("%d overflows int", i64) + } + default: + return ValueDecoderError{ + Name: "IntDecodeValue", + Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, + Received: val, + } + } + + val.SetInt(i64) + return nil +} + +// UintDecodeValue is the ValueDecoderFunc for uint types. +func (dvd DefaultValueDecoders) UintDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + var i64 int64 + var err error + switch vr.Type() { + case bsontype.Int32: + i32, err := vr.ReadInt32() + if err != nil { + return err + } + i64 = int64(i32) + case bsontype.Int64: + i64, err = vr.ReadInt64() + if err != nil { + return err + } + case bsontype.Double: + f64, err := vr.ReadDouble() + if err != nil { + return err + } + if !dc.Truncate && math.Floor(f64) != f64 { + return errors.New("UintDecodeValue can only truncate float64 to an integer type when truncation is enabled") + } + if f64 > float64(math.MaxInt64) { + return fmt.Errorf("%g overflows int64", f64) + } + i64 = int64(f64) + default: + return fmt.Errorf("cannot decode %v into an integer type", vr.Type()) + } + + if !val.CanSet() { + return ValueDecoderError{ + Name: "UintDecodeValue", + Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, + Received: val, + } + } + + switch val.Kind() { + case reflect.Uint8: + if i64 < 0 || i64 > math.MaxUint8 { + return fmt.Errorf("%d overflows uint8", i64) + } + case reflect.Uint16: + if i64 < 0 || i64 > math.MaxUint16 { + return fmt.Errorf("%d overflows uint16", i64) + } + case reflect.Uint32: + if i64 < 0 || i64 > math.MaxUint32 { + return fmt.Errorf("%d overflows uint32", i64) + } + case reflect.Uint64: + if i64 < 0 { + return fmt.Errorf("%d overflows uint64", i64) + } + case reflect.Uint: + if i64 < 0 || int64(uint(i64)) != i64 { // Can we fit this inside of an uint + return fmt.Errorf("%d overflows uint", i64) + } + default: + return ValueDecoderError{ + Name: "UintDecodeValue", + Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, + Received: val, + } + } + + val.SetUint(uint64(i64)) + return nil +} + +// FloatDecodeValue is the ValueDecoderFunc for float types. +func (dvd DefaultValueDecoders) FloatDecodeValue(ec DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + var f float64 + var err error + switch vr.Type() { + case bsontype.Int32: + i32, err := vr.ReadInt32() + if err != nil { + return err + } + f = float64(i32) + case bsontype.Int64: + i64, err := vr.ReadInt64() + if err != nil { + return err + } + f = float64(i64) + case bsontype.Double: + f, err = vr.ReadDouble() + if err != nil { + return err + } + default: + return fmt.Errorf("cannot decode %v into a float32 or float64 type", vr.Type()) + } + + if !val.CanSet() { + return ValueDecoderError{Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: val} + } + + switch val.Kind() { + case reflect.Float32: + if !ec.Truncate && float64(float32(f)) != f { + return errors.New("FloatDecodeValue can only convert float64 to float32 when truncation is allowed") + } + case reflect.Float64: + default: + return ValueDecoderError{Name: "FloatDecodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: val} + } + + val.SetFloat(f) + return nil +} + +// StringDecodeValue is the ValueDecoderFunc for string types. +func (dvd DefaultValueDecoders) StringDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + var str string + var err error + switch vr.Type() { + // TODO(GODRIVER-577): Handle JavaScript and Symbol BSON types when allowed. + case bsontype.String: + str, err = vr.ReadString() + if err != nil { + return err + } + default: + return fmt.Errorf("cannot decode %v into a string type", vr.Type()) + } + if !val.CanSet() || val.Kind() != reflect.String { + return ValueDecoderError{Name: "StringDecodeValue", Kinds: []reflect.Kind{reflect.String}, Received: val} + } + + val.SetString(str) + return nil +} + +// JavaScriptDecodeValue is the ValueDecoderFunc for the primitive.JavaScript type. +func (DefaultValueDecoders) JavaScriptDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tJavaScript { + return ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tJavaScript}, Received: val} + } + + if vr.Type() != bsontype.JavaScript { + return fmt.Errorf("cannot decode %v into a primitive.JavaScript", vr.Type()) + } + + js, err := vr.ReadJavascript() + if err != nil { + return err + } + + val.SetString(js) + return nil +} + +// SymbolDecodeValue is the ValueDecoderFunc for the primitive.Symbol type. +func (DefaultValueDecoders) SymbolDecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tSymbol { + return ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tSymbol}, Received: val} + } + + if vr.Type() != bsontype.Symbol { + return fmt.Errorf("cannot decode %v into a primitive.Symbol", vr.Type()) + } + + symbol, err := vr.ReadSymbol() + if err != nil { + return err + } + + val.SetString(symbol) + return nil +} + +// BinaryDecodeValue is the ValueDecoderFunc for Binary. +func (DefaultValueDecoders) BinaryDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tBinary { + return ValueDecoderError{Name: "BinaryDecodeValue", Types: []reflect.Type{tBinary}, Received: val} + } + + if vr.Type() != bsontype.Binary { + return fmt.Errorf("cannot decode %v into a Binary", vr.Type()) + } + + data, subtype, err := vr.ReadBinary() + if err != nil { + return err + } + + val.Set(reflect.ValueOf(primitive.Binary{Subtype: subtype, Data: data})) + return nil +} + +// UndefinedDecodeValue is the ValueDecoderFunc for Undefined. +func (DefaultValueDecoders) UndefinedDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tUndefined { + return ValueDecoderError{Name: "UndefinedDecodeValue", Types: []reflect.Type{tUndefined}, Received: val} + } + + if vr.Type() != bsontype.Undefined { + return fmt.Errorf("cannot decode %v into an Undefined", vr.Type()) + } + + val.Set(reflect.ValueOf(primitive.Undefined{})) + return vr.ReadUndefined() +} + +// ObjectIDDecodeValue is the ValueDecoderFunc for primitive.ObjectID. +func (dvd DefaultValueDecoders) ObjectIDDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tOID { + return ValueDecoderError{Name: "ObjectIDDecodeValue", Types: []reflect.Type{tOID}, Received: val} + } + + if vr.Type() != bsontype.ObjectID { + return fmt.Errorf("cannot decode %v into an ObjectID", vr.Type()) + } + oid, err := vr.ReadObjectID() + val.Set(reflect.ValueOf(oid)) + return err +} + +// DateTimeDecodeValue is the ValueDecoderFunc for DateTime. +func (DefaultValueDecoders) DateTimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tDateTime { + return ValueDecoderError{Name: "DateTimeDecodeValue", Types: []reflect.Type{tDateTime}, Received: val} + } + + if vr.Type() != bsontype.DateTime { + return fmt.Errorf("cannot decode %v into a DateTime", vr.Type()) + } + + dt, err := vr.ReadDateTime() + if err != nil { + return err + } + + val.Set(reflect.ValueOf(primitive.DateTime(dt))) + return nil +} + +// NullDecodeValue is the ValueDecoderFunc for Null. +func (DefaultValueDecoders) NullDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tNull { + return ValueDecoderError{Name: "NullDecodeValue", Types: []reflect.Type{tNull}, Received: val} + } + + if vr.Type() != bsontype.Null { + return fmt.Errorf("cannot decode %v into a Null", vr.Type()) + } + + val.Set(reflect.ValueOf(primitive.Null{})) + return vr.ReadNull() +} + +// RegexDecodeValue is the ValueDecoderFunc for Regex. +func (DefaultValueDecoders) RegexDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tRegex { + return ValueDecoderError{Name: "RegexDecodeValue", Types: []reflect.Type{tRegex}, Received: val} + } + + if vr.Type() != bsontype.Regex { + return fmt.Errorf("cannot decode %v into a Regex", vr.Type()) + } + + pattern, options, err := vr.ReadRegex() + if err != nil { + return err + } + + val.Set(reflect.ValueOf(primitive.Regex{Pattern: pattern, Options: options})) + return nil +} + +// DBPointerDecodeValue is the ValueDecoderFunc for DBPointer. +func (DefaultValueDecoders) DBPointerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tDBPointer { + return ValueDecoderError{Name: "DBPointerDecodeValue", Types: []reflect.Type{tDBPointer}, Received: val} + } + + if vr.Type() != bsontype.DBPointer { + return fmt.Errorf("cannot decode %v into a DBPointer", vr.Type()) + } + + ns, pointer, err := vr.ReadDBPointer() + if err != nil { + return err + } + + val.Set(reflect.ValueOf(primitive.DBPointer{DB: ns, Pointer: pointer})) + return nil +} + +// TimestampDecodeValue is the ValueDecoderFunc for Timestamp. +func (DefaultValueDecoders) TimestampDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tTimestamp { + return ValueDecoderError{Name: "TimestampDecodeValue", Types: []reflect.Type{tTimestamp}, Received: val} + } + + if vr.Type() != bsontype.Timestamp { + return fmt.Errorf("cannot decode %v into a Timestamp", vr.Type()) + } + + t, incr, err := vr.ReadTimestamp() + if err != nil { + return err + } + + val.Set(reflect.ValueOf(primitive.Timestamp{T: t, I: incr})) + return nil +} + +// MinKeyDecodeValue is the ValueDecoderFunc for MinKey. +func (DefaultValueDecoders) MinKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tMinKey { + return ValueDecoderError{Name: "MinKeyDecodeValue", Types: []reflect.Type{tMinKey}, Received: val} + } + + if vr.Type() != bsontype.MinKey { + return fmt.Errorf("cannot decode %v into a MinKey", vr.Type()) + } + + val.Set(reflect.ValueOf(primitive.MinKey{})) + return vr.ReadMinKey() +} + +// MaxKeyDecodeValue is the ValueDecoderFunc for MaxKey. +func (DefaultValueDecoders) MaxKeyDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tMaxKey { + return ValueDecoderError{Name: "MaxKeyDecodeValue", Types: []reflect.Type{tMaxKey}, Received: val} + } + + if vr.Type() != bsontype.MaxKey { + return fmt.Errorf("cannot decode %v into a MaxKey", vr.Type()) + } + + val.Set(reflect.ValueOf(primitive.MaxKey{})) + return vr.ReadMaxKey() +} + +// Decimal128DecodeValue is the ValueDecoderFunc for primitive.Decimal128. +func (dvd DefaultValueDecoders) Decimal128DecodeValue(dctx DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if vr.Type() != bsontype.Decimal128 { + return fmt.Errorf("cannot decode %v into a primitive.Decimal128", vr.Type()) + } + + if !val.CanSet() || val.Type() != tDecimal { + return ValueDecoderError{Name: "Decimal128DecodeValue", Types: []reflect.Type{tDecimal}, Received: val} + } + d128, err := vr.ReadDecimal128() + val.Set(reflect.ValueOf(d128)) + return err +} + +// JSONNumberDecodeValue is the ValueDecoderFunc for json.Number. +func (dvd DefaultValueDecoders) JSONNumberDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tJSONNumber { + return ValueDecoderError{Name: "JSONNumberDecodeValue", Types: []reflect.Type{tJSONNumber}, Received: val} + } + + switch vr.Type() { + case bsontype.Double: + f64, err := vr.ReadDouble() + if err != nil { + return err + } + val.Set(reflect.ValueOf(json.Number(strconv.FormatFloat(f64, 'g', -1, 64)))) + case bsontype.Int32: + i32, err := vr.ReadInt32() + if err != nil { + return err + } + val.Set(reflect.ValueOf(json.Number(strconv.FormatInt(int64(i32), 10)))) + case bsontype.Int64: + i64, err := vr.ReadInt64() + if err != nil { + return err + } + val.Set(reflect.ValueOf(json.Number(strconv.FormatInt(i64, 10)))) + default: + return fmt.Errorf("cannot decode %v into a json.Number", vr.Type()) + } + + return nil +} + +// URLDecodeValue is the ValueDecoderFunc for url.URL. +func (dvd DefaultValueDecoders) URLDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if vr.Type() != bsontype.String { + return fmt.Errorf("cannot decode %v into a *url.URL", vr.Type()) + } + + str, err := vr.ReadString() + if err != nil { + return err + } + + u, err := url.Parse(str) + if err != nil { + return err + } + + if !val.CanSet() || val.Type() != tURL { + return ValueDecoderError{Name: "URLDecodeValue", Types: []reflect.Type{tURL}, Received: val} + } + + val.Set(reflect.ValueOf(u).Elem()) + return nil +} + +// TimeDecodeValue is the ValueDecoderFunc for time.Time. +func (dvd DefaultValueDecoders) TimeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if vr.Type() != bsontype.DateTime { + return fmt.Errorf("cannot decode %v into a time.Time", vr.Type()) + } + + dt, err := vr.ReadDateTime() + if err != nil { + return err + } + + if !val.CanSet() || val.Type() != tTime { + return ValueDecoderError{Name: "TimeDecodeValue", Types: []reflect.Type{tTime}, Received: val} + } + + val.Set(reflect.ValueOf(time.Unix(dt/1000, dt%1000*1000000).UTC())) + return nil +} + +// ByteSliceDecodeValue is the ValueDecoderFunc for []byte. +func (dvd DefaultValueDecoders) ByteSliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if vr.Type() != bsontype.Binary && vr.Type() != bsontype.Null { + return fmt.Errorf("cannot decode %v into a []byte", vr.Type()) + } + + if !val.CanSet() || val.Type() != tByteSlice { + return ValueDecoderError{Name: "ByteSliceDecodeValue", Types: []reflect.Type{tByteSlice}, Received: val} + } + + if vr.Type() == bsontype.Null { + val.Set(reflect.Zero(val.Type())) + return vr.ReadNull() + } + + data, subtype, err := vr.ReadBinary() + if err != nil { + return err + } + if subtype != 0x00 { + return fmt.Errorf("ByteSliceDecodeValue can only be used to decode subtype 0x00 for %s, got %v", bsontype.Binary, subtype) + } + + val.Set(reflect.ValueOf(data)) + return nil +} + +// MapDecodeValue is the ValueDecoderFunc for map[string]* types. +func (dvd DefaultValueDecoders) MapDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { + return ValueDecoderError{Name: "MapDecodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} + } + + switch vr.Type() { + case bsontype.Type(0), bsontype.EmbeddedDocument: + case bsontype.Null: + val.Set(reflect.Zero(val.Type())) + return vr.ReadNull() + default: + return fmt.Errorf("cannot decode %v into a %s", vr.Type(), val.Type()) + } + + dr, err := vr.ReadDocument() + if err != nil { + return err + } + + if val.IsNil() { + val.Set(reflect.MakeMap(val.Type())) + } + + eType := val.Type().Elem() + decoder, err := dc.LookupDecoder(eType) + if err != nil { + return err + } + + if eType == tEmpty { + dc.Ancestor = val.Type() + } + + keyType := val.Type().Key() + for { + key, vr, err := dr.ReadElement() + if err == bsonrw.ErrEOD { + break + } + if err != nil { + return err + } + + elem := reflect.New(eType).Elem() + + err = decoder.DecodeValue(dc, vr, elem) + if err != nil { + return err + } + + val.SetMapIndex(reflect.ValueOf(key).Convert(keyType), elem) + } + return nil +} + +// ArrayDecodeValue is the ValueDecoderFunc for array types. +func (dvd DefaultValueDecoders) ArrayDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.IsValid() || val.Kind() != reflect.Array { + return ValueDecoderError{Name: "ArrayDecodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val} + } + + switch vr.Type() { + case bsontype.Array: + case bsontype.Type(0), bsontype.EmbeddedDocument: + if val.Type().Elem() != tE { + return fmt.Errorf("cannot decode document into %s", val.Type()) + } + default: + return fmt.Errorf("cannot decode %v into an array", vr.Type()) + } + + var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error) + switch val.Type().Elem() { + case tE: + elemsFunc = dvd.decodeD + default: + elemsFunc = dvd.decodeDefault + } + + elems, err := elemsFunc(dc, vr, val) + if err != nil { + return err + } + + if len(elems) > val.Len() { + return fmt.Errorf("more elements returned in array than can fit inside %s", val.Type()) + } + + for idx, elem := range elems { + val.Index(idx).Set(elem) + } + + return nil +} + +// SliceDecodeValue is the ValueDecoderFunc for slice types. +func (dvd DefaultValueDecoders) SliceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Kind() != reflect.Slice { + return ValueDecoderError{Name: "SliceDecodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} + } + + switch vr.Type() { + case bsontype.Array: + case bsontype.Null: + val.Set(reflect.Zero(val.Type())) + return vr.ReadNull() + case bsontype.Type(0), bsontype.EmbeddedDocument: + if val.Type().Elem() != tE { + return fmt.Errorf("cannot decode document into %s", val.Type()) + } + default: + return fmt.Errorf("cannot decode %v into a slice", vr.Type()) + } + + var elemsFunc func(DecodeContext, bsonrw.ValueReader, reflect.Value) ([]reflect.Value, error) + switch val.Type().Elem() { + case tE: + dc.Ancestor = val.Type() + elemsFunc = dvd.decodeD + default: + elemsFunc = dvd.decodeDefault + } + + elems, err := elemsFunc(dc, vr, val) + if err != nil { + return err + } + + if val.IsNil() { + val.Set(reflect.MakeSlice(val.Type(), 0, len(elems))) + } + + val.SetLen(0) + val.Set(reflect.Append(val, elems...)) + + return nil +} + +// ValueUnmarshalerDecodeValue is the ValueDecoderFunc for ValueUnmarshaler implementations. +func (dvd DefaultValueDecoders) ValueUnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.IsValid() || (!val.Type().Implements(tValueUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tValueUnmarshaler)) { + return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} + } + + if val.Kind() == reflect.Ptr && val.IsNil() { + if !val.CanSet() { + return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} + } + val.Set(reflect.New(val.Type().Elem())) + } + + if !val.Type().Implements(tValueUnmarshaler) { + if !val.CanAddr() { + return ValueDecoderError{Name: "ValueUnmarshalerDecodeValue", Types: []reflect.Type{tValueUnmarshaler}, Received: val} + } + val = val.Addr() // If they type doesn't implement the interface, a pointer to it must. + } + + t, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) + if err != nil { + return err + } + + fn := val.Convert(tValueUnmarshaler).MethodByName("UnmarshalBSONValue") + errVal := fn.Call([]reflect.Value{reflect.ValueOf(t), reflect.ValueOf(src)})[0] + if !errVal.IsNil() { + return errVal.Interface().(error) + } + return nil +} + +// UnmarshalerDecodeValue is the ValueDecoderFunc for Unmarshaler implementations. +func (dvd DefaultValueDecoders) UnmarshalerDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.IsValid() || (!val.Type().Implements(tUnmarshaler) && !reflect.PtrTo(val.Type()).Implements(tUnmarshaler)) { + return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} + } + + if val.Kind() == reflect.Ptr && val.IsNil() { + if !val.CanSet() { + return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} + } + val.Set(reflect.New(val.Type().Elem())) + } + + if !val.Type().Implements(tUnmarshaler) { + if !val.CanAddr() { + return ValueDecoderError{Name: "UnmarshalerDecodeValue", Types: []reflect.Type{tUnmarshaler}, Received: val} + } + val = val.Addr() // If they type doesn't implement the interface, a pointer to it must. + } + + _, src, err := bsonrw.Copier{}.CopyValueToBytes(vr) + if err != nil { + return err + } + + fn := val.Convert(tUnmarshaler).MethodByName("UnmarshalBSON") + errVal := fn.Call([]reflect.Value{reflect.ValueOf(src)})[0] + if !errVal.IsNil() { + return errVal.Interface().(error) + } + return nil +} + +// EmptyInterfaceDecodeValue is the ValueDecoderFunc for interface{}. +func (dvd DefaultValueDecoders) EmptyInterfaceDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tEmpty { + return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val} + } + + rtype, err := dc.LookupTypeMapEntry(vr.Type()) + if err != nil { + switch vr.Type() { + case bsontype.EmbeddedDocument: + if dc.Ancestor != nil { + rtype = dc.Ancestor + break + } + rtype = tD + case bsontype.Null: + val.Set(reflect.Zero(val.Type())) + return vr.ReadNull() + default: + return err + } + } + + decoder, err := dc.LookupDecoder(rtype) + if err != nil { + return err + } + + elem := reflect.New(rtype).Elem() + err = decoder.DecodeValue(dc, vr, elem) + if err != nil { + return err + } + + val.Set(elem) + return nil +} + +// CoreDocumentDecodeValue is the ValueDecoderFunc for bsoncore.Document. +func (DefaultValueDecoders) CoreDocumentDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tCoreDocument { + return ValueDecoderError{Name: "CoreDocumentDecodeValue", Types: []reflect.Type{tCoreDocument}, Received: val} + } + + if val.IsNil() { + val.Set(reflect.MakeSlice(val.Type(), 0, 0)) + } + + val.SetLen(0) + + cdoc, err := bsonrw.Copier{}.AppendDocumentBytes(val.Interface().(bsoncore.Document), vr) + val.Set(reflect.ValueOf(cdoc)) + return err +} + +func (dvd DefaultValueDecoders) decodeDefault(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) ([]reflect.Value, error) { + elems := make([]reflect.Value, 0) + + ar, err := vr.ReadArray() + if err != nil { + return nil, err + } + + eType := val.Type().Elem() + + decoder, err := dc.LookupDecoder(eType) + if err != nil { + return nil, err + } + + for { + vr, err := ar.ReadValue() + if err == bsonrw.ErrEOA { + break + } + if err != nil { + return nil, err + } + + elem := reflect.New(eType).Elem() + + err = decoder.DecodeValue(dc, vr, elem) + if err != nil { + return nil, err + } + elems = append(elems, elem) + } + + return elems, nil +} + +// CodeWithScopeDecodeValue is the ValueDecoderFunc for CodeWithScope. +func (dvd DefaultValueDecoders) CodeWithScopeDecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tCodeWithScope { + return ValueDecoderError{Name: "CodeWithScopeDecodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val} + } + + if vr.Type() != bsontype.CodeWithScope { + return fmt.Errorf("cannot decode %v into a primitive.CodeWithScope", vr.Type()) + } + + code, dr, err := vr.ReadCodeWithScope() + if err != nil { + return err + } + + scope := reflect.New(tD).Elem() + + elems, err := dvd.decodeElemsFromDocumentReader(dc, dr) + if err != nil { + return err + } + + scope.Set(reflect.MakeSlice(tD, 0, len(elems))) + scope.Set(reflect.Append(scope, elems...)) + + val.Set(reflect.ValueOf(primitive.CodeWithScope{Code: primitive.JavaScript(code), Scope: scope.Interface().(primitive.D)})) + return nil +} + +func (dvd DefaultValueDecoders) decodeD(dc DecodeContext, vr bsonrw.ValueReader, _ reflect.Value) ([]reflect.Value, error) { + switch vr.Type() { + case bsontype.Type(0), bsontype.EmbeddedDocument: + default: + return nil, fmt.Errorf("cannot decode %v into a D", vr.Type()) + } + + dr, err := vr.ReadDocument() + if err != nil { + return nil, err + } + + return dvd.decodeElemsFromDocumentReader(dc, dr) +} + +func (DefaultValueDecoders) decodeElemsFromDocumentReader(dc DecodeContext, dr bsonrw.DocumentReader) ([]reflect.Value, error) { + decoder, err := dc.LookupDecoder(tEmpty) + if err != nil { + return nil, err + } + + elems := make([]reflect.Value, 0) + for { + key, vr, err := dr.ReadElement() + if err == bsonrw.ErrEOD { + break + } + if err != nil { + return nil, err + } + + val := reflect.New(tEmpty).Elem() + err = decoder.DecodeValue(dc, vr, val) + if err != nil { + return nil, err + } + + elems = append(elems, reflect.ValueOf(primitive.E{Key: key, Value: val.Interface()})) + } + + return elems, nil +} diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go new file mode 100644 index 0000000..39ebfc7 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/default_value_encoders.go @@ -0,0 +1,648 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package bsoncodec + +import ( + "encoding/json" + "errors" + "fmt" + "math" + "net/url" + "reflect" + "sync" + "time" + + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" +) + +var defaultValueEncoders DefaultValueEncoders + +var bvwPool = bsonrw.NewBSONValueWriterPool() + +var sliceWriterPool = sync.Pool{ + New: func() interface{} { + sw := make(bsonrw.SliceWriter, 0, 0) + return &sw + }, +} + +func encodeElement(ec EncodeContext, dw bsonrw.DocumentWriter, e primitive.E) error { + vw, err := dw.WriteDocumentElement(e.Key) + if err != nil { + return err + } + + if e.Value == nil { + return vw.WriteNull() + } + encoder, err := ec.LookupEncoder(reflect.TypeOf(e.Value)) + if err != nil { + return err + } + + err = encoder.EncodeValue(ec, vw, reflect.ValueOf(e.Value)) + if err != nil { + return err + } + return nil +} + +// DefaultValueEncoders is a namespace type for the default ValueEncoders used +// when creating a registry. +type DefaultValueEncoders struct{} + +// RegisterDefaultEncoders will register the encoder methods attached to DefaultValueEncoders with +// the provided RegistryBuilder. +func (dve DefaultValueEncoders) RegisterDefaultEncoders(rb *RegistryBuilder) { + if rb == nil { + panic(errors.New("argument to RegisterDefaultEncoders must not be nil")) + } + rb. + RegisterEncoder(tByteSlice, ValueEncoderFunc(dve.ByteSliceEncodeValue)). + RegisterEncoder(tTime, ValueEncoderFunc(dve.TimeEncodeValue)). + RegisterEncoder(tEmpty, ValueEncoderFunc(dve.EmptyInterfaceEncodeValue)). + RegisterEncoder(tOID, ValueEncoderFunc(dve.ObjectIDEncodeValue)). + RegisterEncoder(tDecimal, ValueEncoderFunc(dve.Decimal128EncodeValue)). + RegisterEncoder(tJSONNumber, ValueEncoderFunc(dve.JSONNumberEncodeValue)). + RegisterEncoder(tURL, ValueEncoderFunc(dve.URLEncodeValue)). + RegisterEncoder(tValueMarshaler, ValueEncoderFunc(dve.ValueMarshalerEncodeValue)). + RegisterEncoder(tMarshaler, ValueEncoderFunc(dve.MarshalerEncodeValue)). + RegisterEncoder(tProxy, ValueEncoderFunc(dve.ProxyEncodeValue)). + RegisterEncoder(tJavaScript, ValueEncoderFunc(dve.JavaScriptEncodeValue)). + RegisterEncoder(tSymbol, ValueEncoderFunc(dve.SymbolEncodeValue)). + RegisterEncoder(tBinary, ValueEncoderFunc(dve.BinaryEncodeValue)). + RegisterEncoder(tUndefined, ValueEncoderFunc(dve.UndefinedEncodeValue)). + RegisterEncoder(tDateTime, ValueEncoderFunc(dve.DateTimeEncodeValue)). + RegisterEncoder(tNull, ValueEncoderFunc(dve.NullEncodeValue)). + RegisterEncoder(tRegex, ValueEncoderFunc(dve.RegexEncodeValue)). + RegisterEncoder(tDBPointer, ValueEncoderFunc(dve.DBPointerEncodeValue)). + RegisterEncoder(tTimestamp, ValueEncoderFunc(dve.TimestampEncodeValue)). + RegisterEncoder(tMinKey, ValueEncoderFunc(dve.MinKeyEncodeValue)). + RegisterEncoder(tMaxKey, ValueEncoderFunc(dve.MaxKeyEncodeValue)). + RegisterEncoder(tCoreDocument, ValueEncoderFunc(dve.CoreDocumentEncodeValue)). + RegisterEncoder(tCodeWithScope, ValueEncoderFunc(dve.CodeWithScopeEncodeValue)). + RegisterDefaultEncoder(reflect.Bool, ValueEncoderFunc(dve.BooleanEncodeValue)). + RegisterDefaultEncoder(reflect.Int, ValueEncoderFunc(dve.IntEncodeValue)). + RegisterDefaultEncoder(reflect.Int8, ValueEncoderFunc(dve.IntEncodeValue)). + RegisterDefaultEncoder(reflect.Int16, ValueEncoderFunc(dve.IntEncodeValue)). + RegisterDefaultEncoder(reflect.Int32, ValueEncoderFunc(dve.IntEncodeValue)). + RegisterDefaultEncoder(reflect.Int64, ValueEncoderFunc(dve.IntEncodeValue)). + RegisterDefaultEncoder(reflect.Uint, ValueEncoderFunc(dve.UintEncodeValue)). + RegisterDefaultEncoder(reflect.Uint8, ValueEncoderFunc(dve.UintEncodeValue)). + RegisterDefaultEncoder(reflect.Uint16, ValueEncoderFunc(dve.UintEncodeValue)). + RegisterDefaultEncoder(reflect.Uint32, ValueEncoderFunc(dve.UintEncodeValue)). + RegisterDefaultEncoder(reflect.Uint64, ValueEncoderFunc(dve.UintEncodeValue)). + RegisterDefaultEncoder(reflect.Float32, ValueEncoderFunc(dve.FloatEncodeValue)). + RegisterDefaultEncoder(reflect.Float64, ValueEncoderFunc(dve.FloatEncodeValue)). + RegisterDefaultEncoder(reflect.Array, ValueEncoderFunc(dve.ArrayEncodeValue)). + RegisterDefaultEncoder(reflect.Map, ValueEncoderFunc(dve.MapEncodeValue)). + RegisterDefaultEncoder(reflect.Slice, ValueEncoderFunc(dve.SliceEncodeValue)). + RegisterDefaultEncoder(reflect.String, ValueEncoderFunc(dve.StringEncodeValue)). + RegisterDefaultEncoder(reflect.Struct, &StructCodec{cache: make(map[reflect.Type]*structDescription), parser: DefaultStructTagParser}). + RegisterDefaultEncoder(reflect.Ptr, NewPointerCodec()) +} + +// BooleanEncodeValue is the ValueEncoderFunc for bool types. +func (dve DefaultValueEncoders) BooleanEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Kind() != reflect.Bool { + return ValueEncoderError{Name: "BooleanEncodeValue", Kinds: []reflect.Kind{reflect.Bool}, Received: val} + } + return vw.WriteBoolean(val.Bool()) +} + +func fitsIn32Bits(i int64) bool { + return math.MinInt32 <= i && i <= math.MaxInt32 +} + +// IntEncodeValue is the ValueEncoderFunc for int types. +func (dve DefaultValueEncoders) IntEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + switch val.Kind() { + case reflect.Int8, reflect.Int16, reflect.Int32: + return vw.WriteInt32(int32(val.Int())) + case reflect.Int: + i64 := val.Int() + if fitsIn32Bits(i64) { + return vw.WriteInt32(int32(i64)) + } + return vw.WriteInt64(i64) + case reflect.Int64: + i64 := val.Int() + if ec.MinSize && fitsIn32Bits(i64) { + return vw.WriteInt32(int32(i64)) + } + return vw.WriteInt64(i64) + } + + return ValueEncoderError{ + Name: "IntEncodeValue", + Kinds: []reflect.Kind{reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int}, + Received: val, + } +} + +// UintEncodeValue is the ValueEncoderFunc for uint types. +func (dve DefaultValueEncoders) UintEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + switch val.Kind() { + case reflect.Uint8, reflect.Uint16: + return vw.WriteInt32(int32(val.Uint())) + case reflect.Uint, reflect.Uint32, reflect.Uint64: + u64 := val.Uint() + if ec.MinSize && u64 <= math.MaxInt32 { + return vw.WriteInt32(int32(u64)) + } + if u64 > math.MaxInt64 { + return fmt.Errorf("%d overflows int64", u64) + } + return vw.WriteInt64(int64(u64)) + } + + return ValueEncoderError{ + Name: "UintEncodeValue", + Kinds: []reflect.Kind{reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint}, + Received: val, + } +} + +// FloatEncodeValue is the ValueEncoderFunc for float types. +func (dve DefaultValueEncoders) FloatEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + switch val.Kind() { + case reflect.Float32, reflect.Float64: + return vw.WriteDouble(val.Float()) + } + + return ValueEncoderError{Name: "FloatEncodeValue", Kinds: []reflect.Kind{reflect.Float32, reflect.Float64}, Received: val} +} + +// StringEncodeValue is the ValueEncoderFunc for string types. +func (dve DefaultValueEncoders) StringEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if val.Kind() != reflect.String { + return ValueEncoderError{ + Name: "StringEncodeValue", + Kinds: []reflect.Kind{reflect.String}, + Received: val, + } + } + + return vw.WriteString(val.String()) +} + +// ObjectIDEncodeValue is the ValueEncoderFunc for primitive.ObjectID. +func (dve DefaultValueEncoders) ObjectIDEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tOID { + return ValueEncoderError{Name: "ObjectIDEncodeValue", Types: []reflect.Type{tOID}, Received: val} + } + return vw.WriteObjectID(val.Interface().(primitive.ObjectID)) +} + +// Decimal128EncodeValue is the ValueEncoderFunc for primitive.Decimal128. +func (dve DefaultValueEncoders) Decimal128EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tDecimal { + return ValueEncoderError{Name: "Decimal128EncodeValue", Types: []reflect.Type{tDecimal}, Received: val} + } + return vw.WriteDecimal128(val.Interface().(primitive.Decimal128)) +} + +// JSONNumberEncodeValue is the ValueEncoderFunc for json.Number. +func (dve DefaultValueEncoders) JSONNumberEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tJSONNumber { + return ValueEncoderError{Name: "JSONNumberEncodeValue", Types: []reflect.Type{tJSONNumber}, Received: val} + } + jsnum := val.Interface().(json.Number) + + // Attempt int first, then float64 + if i64, err := jsnum.Int64(); err == nil { + return dve.IntEncodeValue(ec, vw, reflect.ValueOf(i64)) + } + + f64, err := jsnum.Float64() + if err != nil { + return err + } + + return dve.FloatEncodeValue(ec, vw, reflect.ValueOf(f64)) +} + +// URLEncodeValue is the ValueEncoderFunc for url.URL. +func (dve DefaultValueEncoders) URLEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tURL { + return ValueEncoderError{Name: "URLEncodeValue", Types: []reflect.Type{tURL}, Received: val} + } + u := val.Interface().(url.URL) + return vw.WriteString(u.String()) +} + +// TimeEncodeValue is the ValueEncoderFunc for time.TIme. +func (dve DefaultValueEncoders) TimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tTime { + return ValueEncoderError{Name: "TimeEncodeValue", Types: []reflect.Type{tTime}, Received: val} + } + tt := val.Interface().(time.Time) + return vw.WriteDateTime(tt.Unix()*1000 + int64(tt.Nanosecond()/1e6)) +} + +// ByteSliceEncodeValue is the ValueEncoderFunc for []byte. +func (dve DefaultValueEncoders) ByteSliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tByteSlice { + return ValueEncoderError{Name: "ByteSliceEncodeValue", Types: []reflect.Type{tByteSlice}, Received: val} + } + if val.IsNil() { + return vw.WriteNull() + } + return vw.WriteBinary(val.Interface().([]byte)) +} + +// MapEncodeValue is the ValueEncoderFunc for map[string]* types. +func (dve DefaultValueEncoders) MapEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Kind() != reflect.Map || val.Type().Key().Kind() != reflect.String { + return ValueEncoderError{Name: "MapEncodeValue", Kinds: []reflect.Kind{reflect.Map}, Received: val} + } + + if val.IsNil() { + // If we have a nill map but we can't WriteNull, that means we're probably trying to encode + // to a TopLevel document. We can't currently tell if this is what actually happened, but if + // there's a deeper underlying problem, the error will also be returned from WriteDocument, + // so just continue. The operations on a map reflection value are valid, so we can call + // MapKeys within mapEncodeValue without a problem. + err := vw.WriteNull() + if err == nil { + return nil + } + } + + dw, err := vw.WriteDocument() + if err != nil { + return err + } + + return dve.mapEncodeValue(ec, dw, val, nil) +} + +// mapEncodeValue handles encoding of the values of a map. The collisionFn returns +// true if the provided key exists, this is mainly used for inline maps in the +// struct codec. +func (dve DefaultValueEncoders) mapEncodeValue(ec EncodeContext, dw bsonrw.DocumentWriter, val reflect.Value, collisionFn func(string) bool) error { + + encoder, err := ec.LookupEncoder(val.Type().Elem()) + if err != nil { + return err + } + + keys := val.MapKeys() + for _, key := range keys { + if collisionFn != nil && collisionFn(key.String()) { + return fmt.Errorf("Key %s of inlined map conflicts with a struct field name", key) + } + vw, err := dw.WriteDocumentElement(key.String()) + if err != nil { + return err + } + + if enc, ok := encoder.(ValueEncoder); ok { + err = enc.EncodeValue(ec, vw, val.MapIndex(key)) + if err != nil { + return err + } + continue + } + err = encoder.EncodeValue(ec, vw, val.MapIndex(key)) + if err != nil { + return err + } + } + + return dw.WriteDocumentEnd() +} + +// ArrayEncodeValue is the ValueEncoderFunc for array types. +func (dve DefaultValueEncoders) ArrayEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Kind() != reflect.Array { + return ValueEncoderError{Name: "ArrayEncodeValue", Kinds: []reflect.Kind{reflect.Array}, Received: val} + } + + // If we have a []primitive.E we want to treat it as a document instead of as an array. + if val.Type().Elem() == tE { + dw, err := vw.WriteDocument() + if err != nil { + return err + } + + for idx := 0; idx < val.Len(); idx++ { + e := val.Index(idx).Interface().(primitive.E) + err = encodeElement(ec, dw, e) + if err != nil { + return err + } + } + + return dw.WriteDocumentEnd() + } + + aw, err := vw.WriteArray() + if err != nil { + return err + } + + encoder, err := ec.LookupEncoder(val.Type().Elem()) + if err != nil { + return err + } + + for idx := 0; idx < val.Len(); idx++ { + vw, err := aw.WriteArrayElement() + if err != nil { + return err + } + + err = encoder.EncodeValue(ec, vw, val.Index(idx)) + if err != nil { + return err + } + } + return aw.WriteArrayEnd() +} + +// SliceEncodeValue is the ValueEncoderFunc for slice types. +func (dve DefaultValueEncoders) SliceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Kind() != reflect.Slice { + return ValueEncoderError{Name: "SliceEncodeValue", Kinds: []reflect.Kind{reflect.Slice}, Received: val} + } + + if val.IsNil() { + return vw.WriteNull() + } + + // If we have a []primitive.E we want to treat it as a document instead of as an array. + if val.Type().ConvertibleTo(tD) { + d := val.Convert(tD).Interface().(primitive.D) + + dw, err := vw.WriteDocument() + if err != nil { + return err + } + + for _, e := range d { + err = encodeElement(ec, dw, e) + if err != nil { + return err + } + } + + return dw.WriteDocumentEnd() + } + + aw, err := vw.WriteArray() + if err != nil { + return err + } + + encoder, err := ec.LookupEncoder(val.Type().Elem()) + if err != nil { + return err + } + + for idx := 0; idx < val.Len(); idx++ { + vw, err := aw.WriteArrayElement() + if err != nil { + return err + } + + err = encoder.EncodeValue(ec, vw, val.Index(idx)) + if err != nil { + return err + } + } + return aw.WriteArrayEnd() +} + +// EmptyInterfaceEncodeValue is the ValueEncoderFunc for interface{}. +func (dve DefaultValueEncoders) EmptyInterfaceEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tEmpty { + return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val} + } + + if val.IsNil() { + return vw.WriteNull() + } + encoder, err := ec.LookupEncoder(val.Elem().Type()) + if err != nil { + return err + } + + return encoder.EncodeValue(ec, vw, val.Elem()) +} + +// ValueMarshalerEncodeValue is the ValueEncoderFunc for ValueMarshaler implementations. +func (dve DefaultValueEncoders) ValueMarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || !val.Type().Implements(tValueMarshaler) { + return ValueEncoderError{Name: "ValueMarshalerEncodeValue", Types: []reflect.Type{tValueMarshaler}, Received: val} + } + + fn := val.Convert(tValueMarshaler).MethodByName("MarshalBSONValue") + returns := fn.Call(nil) + if !returns[2].IsNil() { + return returns[2].Interface().(error) + } + t, data := returns[0].Interface().(bsontype.Type), returns[1].Interface().([]byte) + return bsonrw.Copier{}.CopyValueFromBytes(vw, t, data) +} + +// MarshalerEncodeValue is the ValueEncoderFunc for Marshaler implementations. +func (dve DefaultValueEncoders) MarshalerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || !val.Type().Implements(tMarshaler) { + return ValueEncoderError{Name: "MarshalerEncodeValue", Types: []reflect.Type{tMarshaler}, Received: val} + } + + fn := val.Convert(tMarshaler).MethodByName("MarshalBSON") + returns := fn.Call(nil) + if !returns[1].IsNil() { + return returns[1].Interface().(error) + } + data := returns[0].Interface().([]byte) + return bsonrw.Copier{}.CopyValueFromBytes(vw, bsontype.EmbeddedDocument, data) +} + +// ProxyEncodeValue is the ValueEncoderFunc for Proxy implementations. +func (dve DefaultValueEncoders) ProxyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || !val.Type().Implements(tProxy) { + return ValueEncoderError{Name: "ProxyEncodeValue", Types: []reflect.Type{tProxy}, Received: val} + } + + fn := val.Convert(tProxy).MethodByName("ProxyBSON") + returns := fn.Call(nil) + if !returns[1].IsNil() { + return returns[1].Interface().(error) + } + data := returns[0] + var encoder ValueEncoder + var err error + if data.Elem().IsValid() { + encoder, err = ec.LookupEncoder(data.Elem().Type()) + } else { + encoder, err = ec.LookupEncoder(nil) + } + if err != nil { + return err + } + return encoder.EncodeValue(ec, vw, data.Elem()) +} + +// JavaScriptEncodeValue is the ValueEncoderFunc for the primitive.JavaScript type. +func (DefaultValueEncoders) JavaScriptEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tJavaScript { + return ValueEncoderError{Name: "JavaScriptEncodeValue", Types: []reflect.Type{tJavaScript}, Received: val} + } + + return vw.WriteJavascript(val.String()) +} + +// SymbolEncodeValue is the ValueEncoderFunc for the primitive.Symbol type. +func (DefaultValueEncoders) SymbolEncodeValue(ectx EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tSymbol { + return ValueEncoderError{Name: "SymbolEncodeValue", Types: []reflect.Type{tSymbol}, Received: val} + } + + return vw.WriteSymbol(val.String()) +} + +// BinaryEncodeValue is the ValueEncoderFunc for Binary. +func (DefaultValueEncoders) BinaryEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tBinary { + return ValueEncoderError{Name: "BinaryEncodeValue", Types: []reflect.Type{tBinary}, Received: val} + } + b := val.Interface().(primitive.Binary) + + return vw.WriteBinaryWithSubtype(b.Data, b.Subtype) +} + +// UndefinedEncodeValue is the ValueEncoderFunc for Undefined. +func (DefaultValueEncoders) UndefinedEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tUndefined { + return ValueEncoderError{Name: "UndefinedEncodeValue", Types: []reflect.Type{tUndefined}, Received: val} + } + + return vw.WriteUndefined() +} + +// DateTimeEncodeValue is the ValueEncoderFunc for DateTime. +func (DefaultValueEncoders) DateTimeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tDateTime { + return ValueEncoderError{Name: "DateTimeEncodeValue", Types: []reflect.Type{tDateTime}, Received: val} + } + + return vw.WriteDateTime(val.Int()) +} + +// NullEncodeValue is the ValueEncoderFunc for Null. +func (DefaultValueEncoders) NullEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tNull { + return ValueEncoderError{Name: "NullEncodeValue", Types: []reflect.Type{tNull}, Received: val} + } + + return vw.WriteNull() +} + +// RegexEncodeValue is the ValueEncoderFunc for Regex. +func (DefaultValueEncoders) RegexEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tRegex { + return ValueEncoderError{Name: "RegexEncodeValue", Types: []reflect.Type{tRegex}, Received: val} + } + + regex := val.Interface().(primitive.Regex) + + return vw.WriteRegex(regex.Pattern, regex.Options) +} + +// DBPointerEncodeValue is the ValueEncoderFunc for DBPointer. +func (DefaultValueEncoders) DBPointerEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tDBPointer { + return ValueEncoderError{Name: "DBPointerEncodeValue", Types: []reflect.Type{tDBPointer}, Received: val} + } + + dbp := val.Interface().(primitive.DBPointer) + + return vw.WriteDBPointer(dbp.DB, dbp.Pointer) +} + +// TimestampEncodeValue is the ValueEncoderFunc for Timestamp. +func (DefaultValueEncoders) TimestampEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tTimestamp { + return ValueEncoderError{Name: "TimestampEncodeValue", Types: []reflect.Type{tTimestamp}, Received: val} + } + + ts := val.Interface().(primitive.Timestamp) + + return vw.WriteTimestamp(ts.T, ts.I) +} + +// MinKeyEncodeValue is the ValueEncoderFunc for MinKey. +func (DefaultValueEncoders) MinKeyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tMinKey { + return ValueEncoderError{Name: "MinKeyEncodeValue", Types: []reflect.Type{tMinKey}, Received: val} + } + + return vw.WriteMinKey() +} + +// MaxKeyEncodeValue is the ValueEncoderFunc for MaxKey. +func (DefaultValueEncoders) MaxKeyEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tMaxKey { + return ValueEncoderError{Name: "MaxKeyEncodeValue", Types: []reflect.Type{tMaxKey}, Received: val} + } + + return vw.WriteMaxKey() +} + +// CoreDocumentEncodeValue is the ValueEncoderFunc for bsoncore.Document. +func (DefaultValueEncoders) CoreDocumentEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tCoreDocument { + return ValueEncoderError{Name: "CoreDocumentEncodeValue", Types: []reflect.Type{tCoreDocument}, Received: val} + } + + cdoc := val.Interface().(bsoncore.Document) + + return bsonrw.Copier{}.CopyDocumentFromBytes(vw, cdoc) +} + +// CodeWithScopeEncodeValue is the ValueEncoderFunc for CodeWithScope. +func (dve DefaultValueEncoders) CodeWithScopeEncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tCodeWithScope { + return ValueEncoderError{Name: "CodeWithScopeEncodeValue", Types: []reflect.Type{tCodeWithScope}, Received: val} + } + + cws := val.Interface().(primitive.CodeWithScope) + + dw, err := vw.WriteCodeWithScope(string(cws.Code)) + if err != nil { + return err + } + + sw := sliceWriterPool.Get().(*bsonrw.SliceWriter) + defer sliceWriterPool.Put(sw) + *sw = (*sw)[:0] + + scopeVW := bvwPool.Get(sw) + defer bvwPool.Put(scopeVW) + + encoder, err := ec.LookupEncoder(reflect.TypeOf(cws.Scope)) + if err != nil { + return err + } + + err = encoder.EncodeValue(ec, scopeVW, reflect.ValueOf(cws.Scope)) + if err != nil { + return err + } + + err = bsonrw.Copier{}.CopyBytesToDocumentWriter(dw, *sw) + if err != nil { + return err + } + return dw.WriteDocumentEnd() +} diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go new file mode 100644 index 0000000..978511c --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/doc.go @@ -0,0 +1,61 @@ +// Package bsoncodec provides a system for encoding values to BSON representations and decoding +// values from BSON representations. This package considers both binary BSON and ExtendedJSON as +// BSON representations. The types in this package enable a flexible system for handling this +// encoding and decoding. +// +// The codec system is composed of two parts: +// +// 1) ValueEncoders and ValueDecoders that handle encoding and decoding Go values to and from BSON +// representations. +// +// 2) A Registry that holds these ValueEncoders and ValueDecoders and provides methods for +// retrieving them. +// +// ValueEncoders and ValueDecoders +// +// The ValueEncoder interface is implemented by types that can encode a provided Go type to BSON. +// The value to encode is provided as a reflect.Value and a bsonrw.ValueWriter is used within the +// EncodeValue method to actually create the BSON representation. For convenience, ValueEncoderFunc +// is provided to allow use of a function with the correct signature as a ValueEncoder. An +// EncodeContext instance is provided to allow implementations to lookup further ValueEncoders and +// to provide configuration information. +// +// The ValueDecoder interface is the inverse of the ValueEncoder. Implementations should ensure that +// the value they receive is settable. Similar to ValueEncoderFunc, ValueDecoderFunc is provided to +// allow the use of a function with the correct signature as a ValueDecoder. A DecodeContext +// instance is provided and serves similar functionality to the EncodeContext. +// +// Registry and RegistryBuilder +// +// A Registry is an immutable store for ValueEncoders, ValueDecoders, and a type map. For looking up +// ValueEncoders and Decoders the Registry first attempts to find a ValueEncoder or ValueDecoder for +// the type provided; if one cannot be found it then checks to see if a registered ValueEncoder or +// ValueDecoder exists for an interface the type implements. Finally, the reflect.Kind of the type +// is used to lookup a default ValueEncoder or ValueDecoder for that kind. If no ValueEncoder or +// ValueDecoder can be found, an error is returned. +// +// The Registry also holds a type map. This allows users to retrieve the Go type that should be used +// when decoding a BSON value into an empty interface. This is primarily only used for the empty +// interface ValueDecoder. +// +// A RegistryBuilder is used to construct a Registry. The Register methods are used to associate +// either a reflect.Type or a reflect.Kind with a ValueEncoder or ValueDecoder. A RegistryBuilder +// returned from NewRegistryBuilder contains no registered ValueEncoders nor ValueDecoders and +// contains an empty type map. +// +// The RegisterTypeMapEntry method handles associating a BSON type with a Go type. For example, if +// you want to decode BSON int64 and int32 values into Go int instances, you would do the following: +// +// var regbuilder *RegistryBuilder = ... intType := reflect.TypeOf(int(0)) +// regbuilder.RegisterTypeMapEntry(bsontype.Int64, intType).RegisterTypeMapEntry(bsontype.Int32, +// intType) +// +// DefaultValueEncoders and DefaultValueDecoders +// +// The DefaultValueEncoders and DefaultValueDecoders types provide a full set of ValueEncoders and +// ValueDecoders for handling a wide range of Go types, including all of the types within the +// primitive package. To make registering these codecs easier, a helper method on each type is +// provided. For the DefaultValueEncoders type the method is called RegisterDefaultEncoders and for +// the DefaultValueDecoders type the method is called RegisterDefaultDecoders, this method also +// handles registering type map entries for each BSON type. +package bsoncodec diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/mode.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/mode.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/mode.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/mode.go diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go new file mode 100644 index 0000000..0d9502f --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/pointer_codec.go @@ -0,0 +1,110 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package bsoncodec + +import ( + "reflect" + "sync" + + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" +) + +var defaultPointerCodec = &PointerCodec{ + ecache: make(map[reflect.Type]ValueEncoder), + dcache: make(map[reflect.Type]ValueDecoder), +} + +var _ ValueEncoder = &PointerCodec{} +var _ ValueDecoder = &PointerCodec{} + +// PointerCodec is the Codec used for pointers. +type PointerCodec struct { + ecache map[reflect.Type]ValueEncoder + dcache map[reflect.Type]ValueDecoder + l sync.RWMutex +} + +// NewPointerCodec returns a PointerCodec that has been initialized. +func NewPointerCodec() *PointerCodec { + return &PointerCodec{ + ecache: make(map[reflect.Type]ValueEncoder), + dcache: make(map[reflect.Type]ValueDecoder), + } +} + +// EncodeValue handles encoding a pointer by either encoding it to BSON Null if the pointer is nil +// or looking up an encoder for the type of value the pointer points to. +func (pc *PointerCodec) EncodeValue(ec EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if val.Kind() != reflect.Ptr { + if !val.IsValid() { + return vw.WriteNull() + } + return ValueEncoderError{Name: "PointerCodec.EncodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: val} + } + + if val.IsNil() { + return vw.WriteNull() + } + + pc.l.RLock() + enc, ok := pc.ecache[val.Type()] + pc.l.RUnlock() + if ok { + if enc == nil { + return ErrNoEncoder{Type: val.Type()} + } + return enc.EncodeValue(ec, vw, val.Elem()) + } + + enc, err := ec.LookupEncoder(val.Type().Elem()) + pc.l.Lock() + pc.ecache[val.Type()] = enc + pc.l.Unlock() + if err != nil { + return err + } + + return enc.EncodeValue(ec, vw, val.Elem()) +} + +// DecodeValue handles decoding a pointer by looking up a decoder for the type it points to and +// using that to decode. If the BSON value is Null, this method will set the pointer to nil. +func (pc *PointerCodec) DecodeValue(dc DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Kind() != reflect.Ptr { + return ValueDecoderError{Name: "PointerCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Ptr}, Received: val} + } + + if vr.Type() == bsontype.Null { + val.Set(reflect.Zero(val.Type())) + return vr.ReadNull() + } + + if val.IsNil() { + val.Set(reflect.New(val.Type().Elem())) + } + + pc.l.RLock() + dec, ok := pc.dcache[val.Type()] + pc.l.RUnlock() + if ok { + if dec == nil { + return ErrNoDecoder{Type: val.Type()} + } + return dec.DecodeValue(dc, vr, val.Elem()) + } + + dec, err := dc.LookupDecoder(val.Type().Elem()) + pc.l.Lock() + pc.dcache[val.Type()] = dec + pc.l.Unlock() + if err != nil { + return err + } + + return dec.DecodeValue(dc, vr, val.Elem()) +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/proxy.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/proxy.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/proxy.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/proxy.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/registry.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go similarity index 76% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/registry.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go index e719dfe..42e362b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/registry.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/registry.go @@ -10,10 +10,15 @@ import ( "errors" "reflect" "sync" + + "go.mongodb.org/mongo-driver/bson/bsontype" ) // ErrNilType is returned when nil is passed to either LookupEncoder or LookupDecoder. -var ErrNilType = errors.New("cannot perform an encoder or decoder lookup on ") +var ErrNilType = errors.New("cannot perform a decoder lookup on ") + +// ErrNotPointer is returned when a non-pointer type is provided to LookupDecoder. +var ErrNotPointer = errors.New("non-pointer provided to LookupDecoder") // ErrNoEncoder is returned when there wasn't an encoder available for a type. type ErrNoEncoder struct { @@ -21,6 +26,9 @@ type ErrNoEncoder struct { } func (ene ErrNoEncoder) Error() string { + if ene.Type == nil { + return "no encoder found for " + } return "no encoder found for " + ene.Type.String() } @@ -33,6 +41,15 @@ func (end ErrNoDecoder) Error() string { return "no decoder found for " + end.Type.String() } +// ErrNoTypeMapEntry is returned when there wasn't a type available for the provided BSON type. +type ErrNoTypeMapEntry struct { + Type bsontype.Type +} + +func (entme ErrNoTypeMapEntry) Error() string { + return "no type map entry found for " + entme.Type.String() +} + // ErrNotInterface is returned when the provided type is not an interface. var ErrNotInterface = errors.New("The provided type is not an interface") @@ -52,6 +69,8 @@ type RegistryBuilder struct { typeDecoders map[reflect.Type]ValueDecoder interfaceDecoders []interfaceValueDecoder kindDecoders map[reflect.Kind]ValueDecoder + + typeMap map[bsontype.Type]reflect.Type } // A Registry is used to store and retrieve codecs for types and interfaces. This type is the main @@ -66,6 +85,8 @@ type Registry struct { kindEncoders map[reflect.Kind]ValueEncoder kindDecoders map[reflect.Kind]ValueDecoder + typeMap map[bsontype.Type]reflect.Type + mu sync.RWMutex } @@ -80,6 +101,8 @@ func NewRegistryBuilder() *RegistryBuilder { kindEncoders: make(map[reflect.Kind]ValueEncoder), kindDecoders: make(map[reflect.Kind]ValueDecoder), + + typeMap: make(map[bsontype.Type]reflect.Type), } } @@ -98,7 +121,14 @@ func (rb *RegistryBuilder) RegisterCodec(t reflect.Type, codec ValueCodec) *Regi } // RegisterEncoder will register the provided ValueEncoder to the provided type. +// +// The type registered will be used directly, so an encoder can be registered for a type and a +// different encoder can be registered for a pointer to that type. func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *RegistryBuilder { + if t == tEmpty { + rb.typeEncoders[t] = enc + return rb + } switch t.Kind() { case reflect.Interface: for idx, ir := range rb.interfaceEncoders { @@ -110,16 +140,24 @@ func (rb *RegistryBuilder) RegisterEncoder(t reflect.Type, enc ValueEncoder) *Re rb.interfaceEncoders = append(rb.interfaceEncoders, interfaceValueEncoder{i: t, ve: enc}) default: - if t.Kind() != reflect.Ptr { - t = reflect.PtrTo(t) - } rb.typeEncoders[t] = enc } return rb } // RegisterDecoder will register the provided ValueDecoder to the provided type. +// +// The type registered will be used directly, so a decoder can be registered for a type and a +// different decoder can be registered for a pointer to that type. func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *RegistryBuilder { + if t == nil { + rb.typeDecoders[nil] = dec + return rb + } + if t == tEmpty { + rb.typeDecoders[t] = dec + return rb + } switch t.Kind() { case reflect.Interface: for idx, ir := range rb.interfaceDecoders { @@ -131,9 +169,6 @@ func (rb *RegistryBuilder) RegisterDecoder(t reflect.Type, dec ValueDecoder) *Re rb.interfaceDecoders = append(rb.interfaceDecoders, interfaceValueDecoder{i: t, vd: dec}) default: - if t.Kind() != reflect.Ptr { - t = reflect.PtrTo(t) - } rb.typeDecoders[t] = dec } return rb @@ -153,6 +188,20 @@ func (rb *RegistryBuilder) RegisterDefaultDecoder(kind reflect.Kind, dec ValueDe return rb } +// RegisterTypeMapEntry will register the provided type to the BSON type. The primary usage for this +// mapping is decoding situations where an empty interface is used and a default type needs to be +// created and decoded into. +// +// NOTE: It is unlikely that registering a type for BSON Embedded Document is actually desired. By +// registering a type map entry for BSON Embedded Document the type registered will be used in any +// case where a BSON Embedded Document will be decoded into an empty interface. For example, if you +// register primitive.M, the EmptyInterface decoder will always use primitive.M, even if an ancestor +// was a primitive.D. +func (rb *RegistryBuilder) RegisterTypeMapEntry(bt bsontype.Type, rt reflect.Type) *RegistryBuilder { + rb.typeMap[bt] = rt + return rb +} + // Build creates a Registry from the current state of this RegistryBuilder. func (rb *RegistryBuilder) Build() *Registry { registry := new(Registry) @@ -183,6 +232,11 @@ func (rb *RegistryBuilder) Build() *Registry { registry.kindDecoders[kind] = dec } + registry.typeMap = make(map[bsontype.Type]reflect.Type) + for bt, rt := range rb.typeMap { + registry.typeMap[bt] = rt + } + return registry } @@ -192,9 +246,6 @@ func (rb *RegistryBuilder) Build() *Registry { // which takes precedence over an encoder for the reflect.Kind of the value. If // no encoder can be found, an error is returned. func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) { - if t == nil { - return nil, ErrNilType - } encodererr := ErrNoEncoder{Type: t} r.mu.RLock() enc, found := r.lookupTypeEncoder(t) @@ -209,25 +260,18 @@ func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) { enc, found = r.lookupInterfaceEncoder(t) if found { r.mu.Lock() - if t.Kind() != reflect.Ptr { - t = reflect.PtrTo(t) - } r.typeEncoders[t] = enc r.mu.Unlock() return enc, nil } - if t.Kind() == reflect.Map && t.Key().Kind() != reflect.String { + if t == nil { r.mu.Lock() r.typeEncoders[t] = nil r.mu.Unlock() return nil, encodererr } - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - enc, found = r.kindEncoders[t.Kind()] if !found { r.mu.Lock() @@ -243,15 +287,14 @@ func (r *Registry) LookupEncoder(t reflect.Type) (ValueEncoder, error) { } func (r *Registry) lookupTypeEncoder(t reflect.Type) (ValueEncoder, bool) { - if t.Kind() != reflect.Ptr { - t = reflect.PtrTo(t) - } - enc, found := r.typeEncoders[t] return enc, found } func (r *Registry) lookupInterfaceEncoder(t reflect.Type) (ValueEncoder, bool) { + if t == nil { + return nil, false + } for _, ienc := range r.interfaceEncoders { if !t.Implements(ienc.i) { continue @@ -285,25 +328,11 @@ func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error) { dec, found = r.lookupInterfaceDecoder(t) if found { r.mu.Lock() - if t.Kind() != reflect.Ptr { - t = reflect.PtrTo(t) - } r.typeDecoders[t] = dec r.mu.Unlock() return dec, nil } - if t.Kind() == reflect.Map && t.Key().Kind() != reflect.String { - r.mu.Lock() - r.typeDecoders[t] = nil - r.mu.Unlock() - return nil, decodererr - } - - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - dec, found = r.kindDecoders[t.Kind()] if !found { r.mu.Lock() @@ -319,17 +348,13 @@ func (r *Registry) LookupDecoder(t reflect.Type) (ValueDecoder, error) { } func (r *Registry) lookupTypeDecoder(t reflect.Type) (ValueDecoder, bool) { - if t.Kind() != reflect.Ptr { - t = reflect.PtrTo(t) - } - dec, found := r.typeDecoders[t] return dec, found } func (r *Registry) lookupInterfaceDecoder(t reflect.Type) (ValueDecoder, bool) { for _, idec := range r.interfaceDecoders { - if !t.Implements(idec.i) { + if !t.Implements(idec.i) && !reflect.PtrTo(t).Implements(idec.i) { continue } @@ -338,6 +363,16 @@ func (r *Registry) lookupInterfaceDecoder(t reflect.Type) (ValueDecoder, bool) { return nil, false } +// LookupTypeMapEntry inspects the registry's type map for a Go type for the corresponding BSON +// type. If no type is found, ErrNoTypeMapEntry is returned. +func (r *Registry) LookupTypeMapEntry(bt bsontype.Type) (reflect.Type, error) { + t, ok := r.typeMap[bt] + if !ok || t == nil { + return nil, ErrNoTypeMapEntry{Type: bt} + } + return t, nil +} + type interfaceValueEncoder struct { i reflect.Type ve ValueEncoder diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/struct_codec.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/struct_codec.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go index 47eec0a..fe90272 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/struct_codec.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_codec.go @@ -12,7 +12,8 @@ import ( "reflect" "sync" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" ) var defaultStructCodec = &StructCodec{ @@ -50,19 +51,9 @@ func NewStructCodec(p StructTagParser) (*StructCodec, error) { } // EncodeValue handles encoding generic struct types. -func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - val := reflect.ValueOf(i) - for { - if val.Kind() == reflect.Ptr { - val = val.Elem() - continue - } - - break - } - - if val.Kind() != reflect.Struct { - return fmt.Errorf("%T can only process structs, but got a %T", sc, val) +func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Kind() != reflect.Struct { + return ValueEncoderError{Name: "StructCodec.EncodeValue", Kinds: []reflect.Kind{reflect.Struct}, Received: val} } sd, err := sc.describeStruct(r.Registry, val.Type()) @@ -103,7 +94,7 @@ func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, i int } ectx := EncodeContext{Registry: r.Registry, MinSize: desc.minSize} - err = encoder.EncodeValue(ectx, vw2, rv.Interface()) + err = encoder.EncodeValue(ectx, vw2, rv) if err != nil { return err } @@ -123,22 +114,17 @@ func (sc *StructCodec) EncodeValue(r EncodeContext, vw bsonrw.ValueWriter, i int } // DecodeValue implements the Codec interface. -func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - val := reflect.ValueOf(i) - if val.Kind() == reflect.Ptr { - if val.IsNil() { - val = reflect.New(val.Type().Elem()) - } - val = val.Elem() - if val.Kind() == reflect.Ptr { - if val.IsNil() && val.CanSet() { - val.Set(reflect.New(val.Type().Elem())) - } - val = val.Elem() - } +// By default, map types in val will not be cleared. If a map has existing key/value pairs, it will be extended with the new ones from vr. +// For slices, the decoder will set the length of the slice to zero and append all elements. The underlying array will not be cleared. +func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Kind() != reflect.Struct { + return ValueDecoderError{Name: "StructCodec.DecodeValue", Kinds: []reflect.Kind{reflect.Struct}, Received: val} } - if val.Kind() != reflect.Struct || !val.CanAddr() { - return fmt.Errorf("%T can only processes addressable structs, but got %T (addressable: %t)", sc, i, val.CanAddr()) + + switch vr.Type() { + case bsontype.Type(0), bsontype.EmbeddedDocument: + default: + return fmt.Errorf("cannot decode %v into a %s", vr.Type(), val.Type()) } sd, err := sc.describeStruct(r.Registry, val.Type()) @@ -185,12 +171,12 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, i int continue } - ptr := reflect.New(inlineMap.Type().Elem()) - err = decoder.DecodeValue(r, vr, ptr.Interface()) + elem := reflect.New(inlineMap.Type().Elem()).Elem() + err = decoder.DecodeValue(r, vr, elem) if err != nil { return err } - inlineMap.SetMapIndex(reflect.ValueOf(name), ptr.Elem()) + inlineMap.SetMapIndex(reflect.ValueOf(name), elem) continue } @@ -205,7 +191,7 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, i int return fmt.Errorf("cannot decode element '%s' into field %v; it is not settable", name, field) } if field.Kind() == reflect.Ptr && field.IsNil() { - field.Set(reflect.New(field.Type()).Elem()) + field.Set(reflect.New(field.Type().Elem())) } field = field.Addr() @@ -214,7 +200,14 @@ func (sc *StructCodec) DecodeValue(r DecodeContext, vr bsonrw.ValueReader, i int return ErrNoDecoder{Type: field.Elem().Type()} } - err = fd.decoder.DecodeValue(dctx, vr, field.Interface()) + if decoder, ok := fd.decoder.(ValueDecoder); ok { + err = decoder.DecodeValue(dctx, vr, field.Elem()) + if err != nil { + return err + } + continue + } + err = fd.decoder.DecodeValue(dctx, vr, field) if err != nil { return err } @@ -231,7 +224,7 @@ func (sc *StructCodec) isZero(i interface{}) bool { return true } - if z, ok := v.Interface().(Zeroer); ok { + if z, ok := v.Interface().(Zeroer); ok && (v.Kind() != reflect.Ptr || !v.IsNil()) { return z.IsZero() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/struct_tag_parser.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/struct_tag_parser.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/struct_tag_parser.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/types.go b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/types.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go index b6a02cc..7726487 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsoncodec/types.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsoncodec/types.go @@ -12,8 +12,8 @@ import ( "reflect" "time" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) var ptBool = reflect.TypeOf((*bool)(nil)) @@ -32,7 +32,6 @@ var ptFloat64 = reflect.TypeOf((*float64)(nil)) var ptString = reflect.TypeOf((*string)(nil)) var tBool = reflect.TypeOf(false) -var tDecimal = reflect.TypeOf(decimal.Decimal128{}) var tFloat32 = reflect.TypeOf(float32(0)) var tFloat64 = reflect.TypeOf(float64(0)) var tInt = reflect.TypeOf(int(0)) @@ -40,7 +39,6 @@ var tInt8 = reflect.TypeOf(int8(0)) var tInt16 = reflect.TypeOf(int16(0)) var tInt32 = reflect.TypeOf(int32(0)) var tInt64 = reflect.TypeOf(int64(0)) -var tOID = reflect.TypeOf(objectid.ObjectID{}) var tString = reflect.TypeOf("") var tTime = reflect.TypeOf(time.Time{}) var tUint = reflect.TypeOf(uint(0)) @@ -57,4 +55,26 @@ var tJSONNumber = reflect.TypeOf(json.Number("")) var tValueMarshaler = reflect.TypeOf((*ValueMarshaler)(nil)).Elem() var tValueUnmarshaler = reflect.TypeOf((*ValueUnmarshaler)(nil)).Elem() +var tMarshaler = reflect.TypeOf((*Marshaler)(nil)).Elem() +var tUnmarshaler = reflect.TypeOf((*Unmarshaler)(nil)).Elem() var tProxy = reflect.TypeOf((*Proxy)(nil)).Elem() + +var tBinary = reflect.TypeOf(primitive.Binary{}) +var tUndefined = reflect.TypeOf(primitive.Undefined{}) +var tOID = reflect.TypeOf(primitive.ObjectID{}) +var tDateTime = reflect.TypeOf(primitive.DateTime(0)) +var tNull = reflect.TypeOf(primitive.Null{}) +var tRegex = reflect.TypeOf(primitive.Regex{}) +var tCodeWithScope = reflect.TypeOf(primitive.CodeWithScope{}) +var tDBPointer = reflect.TypeOf(primitive.DBPointer{}) +var tJavaScript = reflect.TypeOf(primitive.JavaScript("")) +var tSymbol = reflect.TypeOf(primitive.Symbol("")) +var tTimestamp = reflect.TypeOf(primitive.Timestamp{}) +var tDecimal = reflect.TypeOf(primitive.Decimal128{}) +var tMinKey = reflect.TypeOf(primitive.MinKey{}) +var tMaxKey = reflect.TypeOf(primitive.MaxKey{}) +var tD = reflect.TypeOf(primitive.D{}) +var tA = reflect.TypeOf(primitive.A{}) +var tE = reflect.TypeOf(primitive.E{}) + +var tCoreDocument = reflect.TypeOf(bsoncore.Document{}) diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/copier.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/copier.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go index 0c06c9b..02e3a7e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/copier.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/copier.go @@ -10,10 +10,9 @@ import ( "fmt" "io" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // Copier is a type that allows copying between ValueReaders, ValueWriters, and @@ -54,6 +53,17 @@ func (c Copier) CopyDocumentFromBytes(dst ValueWriter, src []byte) error { return err } + err = c.CopyBytesToDocumentWriter(dw, src) + if err != nil { + return err + } + + return dw.WriteDocumentEnd() +} + +// CopyBytesToDocumentWriter copies the values from a BSON document represented as a []byte to a +// DocumentWriter. +func (c Copier) CopyBytesToDocumentWriter(dst DocumentWriter, src []byte) error { // TODO(skriptble): Create errors types here. Anything thats a tag should be a property. length, rem, ok := bsoncore.ReadLength(src) if !ok { @@ -83,7 +93,7 @@ func (c Copier) CopyDocumentFromBytes(dst ValueWriter, src []byte) error { if !ok { return fmt.Errorf("invalid key found. remaining bytes=%v", rem) } - dvw, err := dw.WriteDocumentElement(key) + dvw, err := dst.WriteDocumentElement(key) if err != nil { return err } @@ -96,8 +106,7 @@ func (c Copier) CopyDocumentFromBytes(dst ValueWriter, src []byte) error { return err } } - - return dw.WriteDocumentEnd() + return nil } // CopyDocumentToBytes copies an entire document from the ValueReader and @@ -109,15 +118,9 @@ func (c Copier) CopyDocumentToBytes(src ValueReader) ([]byte, error) { // AppendDocumentBytes functions the same as CopyDocumentToBytes, but will // append the result to dst. func (c Copier) AppendDocumentBytes(dst []byte, src ValueReader) ([]byte, error) { - if vr, ok := src.(*valueReader); ok { - length, err := vr.peakLength() - if err != nil { - return dst, err - } - dst = append(dst, vr.d[vr.offset:vr.offset+int64(length)]...) - vr.offset += int64(length) - vr.pop() - return dst, nil + if br, ok := src.(BytesReader); ok { + _, dst, err := br.ReadValueBytes(dst) + return dst, err } vw := vwPool.Get().(*valueWriter) @@ -211,7 +214,7 @@ func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error { } err = dst.WriteUndefined() case bsontype.ObjectID: - var oid objectid.ObjectID + var oid primitive.ObjectID oid, err = src.ReadObjectID() if err != nil { break @@ -246,7 +249,7 @@ func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error { err = dst.WriteRegex(pattern, options) case bsontype.DBPointer: var ns string - var pointer objectid.ObjectID + var pointer primitive.ObjectID ns, pointer, err = src.ReadDBPointer() if err != nil { break @@ -302,7 +305,7 @@ func (c Copier) CopyValue(dst ValueWriter, src ValueReader) error { } err = dst.WriteInt64(i64) case bsontype.Decimal128: - var d128 decimal.Decimal128 + var d128 primitive.Decimal128 d128, err = src.ReadDecimal128() if err != nil { break diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/doc.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/doc.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/doc.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/doc.go index 21f24b0..750b0d2 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/doc.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/doc.go @@ -6,4 +6,4 @@ // Package bsonrw contains abstractions for reading and writing // BSON and BSON like types from sources. -package bsonrw +package bsonrw // import "go.mongodb.org/mongo-driver/bson/bsonrw" diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_parser.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_parser.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go index b21aed9..9e223ed 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_parser.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_parser.go @@ -11,7 +11,7 @@ import ( "fmt" "io" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsontype" ) const maxNestingDepth = 200 @@ -64,6 +64,8 @@ type extJSONParser struct { canonical bool depth int maxDepth int + + emptyObject bool } // newExtJSONParser returns a new extended JSON parser, ready to to begin @@ -107,6 +109,7 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { switch ejp.s { case jpsSawEndObject: // empty embedded document t = bsontype.EmbeddedDocument + ejp.emptyObject = true case jpsInvalidState: err = ejp.err case jpsSawKey: @@ -143,6 +146,11 @@ func (ejp *extJSONParser) peekType() (bsontype.Type, error) { // readKey parses the next key and its type and returns them func (ejp *extJSONParser) readKey() (string, bsontype.Type, error) { + if ejp.emptyObject { + ejp.emptyObject = false + return "", 0, ErrEOD + } + // advance to key (or return with error) switch ejp.s { case jpsStartState: @@ -155,10 +163,12 @@ func (ejp *extJSONParser) readKey() (string, bsontype.Type, error) { case jpsSawValue, jpsSawEndObject, jpsSawEndArray: ejp.advanceState() switch ejp.s { - case jpsSawComma: + case jpsSawBeginObject, jpsSawComma: ejp.advanceState() - case jpsSawEndObject, jpsDoneState: + case jpsSawEndObject: return "", 0, ErrEOD + case jpsDoneState: + return "", 0, io.EOF case jpsInvalidState: return "", 0, ejp.err default: @@ -254,8 +264,51 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { return nil, err } + ejp.advanceState() + if t == bsontype.Binary && ejp.s == jpsSawValue { + // convert legacy $binary format + base64 := ejp.v + + ejp.advanceState() + if ejp.s != jpsSawComma { + return nil, invalidJSONErrorForType(",", bsontype.Binary) + } + + ejp.advanceState() + key, t, err := ejp.readKey() + if err != nil { + return nil, err + } + if key != "$type" { + return nil, invalidJSONErrorForType("$type", bsontype.Binary) + } + + subType, err := ejp.readValue(t) + if err != nil { + return nil, err + } + + ejp.advanceState() + if ejp.s != jpsSawEndObject { + return nil, invalidJSONErrorForType("2 key-value pairs and then }", bsontype.Binary) + } + + v = &extJSONValue{ + t: bsontype.EmbeddedDocument, + v: &extJSONObject{ + keys: []string{"base64", "subType"}, + values: []*extJSONValue{base64, subType}, + }, + } + break + } + // read KV pairs - keys, vals, err := ejp.readObject(2, false) + if ejp.s != jpsSawBeginObject { + return nil, invalidJSONErrorForType("{", t) + } + + keys, vals, err := ejp.readObject(2, true) if err != nil { return nil, err } @@ -266,6 +319,7 @@ func (ejp *extJSONParser) readValue(t bsontype.Type) (*extJSONValue, error) { } v = &extJSONValue{t: bsontype.EmbeddedDocument, v: &extJSONObject{keys: keys, values: vals}} + case bsontype.DateTime: switch ejp.s { case jpsSawValue: @@ -458,7 +512,14 @@ func (ejp *extJSONParser) advanceState() { } case jttString: switch ejp.s { - case jpsSawBeginObject, jpsSawComma: + case jpsSawComma: + if ejp.peekMode() == jpmArrayMode { + ejp.s = jpsSawValue + ejp.v = extendJSONToken(jt) + return + } + fallthrough + case jpsSawBeginObject: ejp.s = jpsSawKey ejp.k = jt.v.(string) return @@ -544,6 +605,12 @@ var jpsValidTransitionTokens = map[jsonParseState]map[jsonTokenType]bool{ func (ejp *extJSONParser) validateToken(jtt jsonTokenType) bool { switch ejp.s { + case jpsSawEndObject: + // if we are at depth zero and the next token is a '{', + // we can consider it valid only if we are not in array mode. + if jtt == jttBeginObject && ejp.depth == 0 { + return ejp.peekMode() != jpmArrayMode + } case jpsSawComma: switch ejp.peekMode() { // the only valid next token after a comma inside a document is a string (a key) @@ -552,13 +619,10 @@ func (ejp *extJSONParser) validateToken(jtt jsonTokenType) bool { case jpmInvalidMode: return false } - - // fallthrough for commas in arrays - fallthrough - default: - _, ok := jpsValidTransitionTokens[ejp.s][jtt] - return ok } + + _, ok := jpsValidTransitionTokens[ejp.s][jtt] + return ok } // ensureExtValueType returns true if the current value has the expected diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_reader.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go similarity index 77% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_reader.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go index ebadb3f..dd560c9 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_reader.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_reader.go @@ -11,9 +11,8 @@ import ( "io" "sync" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // ExtJSONValueReaderPool is a pool for ValueReaders that read ExtJSON. @@ -33,10 +32,9 @@ func NewExtJSONValueReaderPool() *ExtJSONValueReaderPool { } // Get retrieves a ValueReader from the pool and uses src as the underlying ExtJSON. -func (bvrp *ExtJSONValueReaderPool) Get(r io.Reader, canonical bool) ValueReader { +func (bvrp *ExtJSONValueReaderPool) Get(r io.Reader, canonical bool) (ValueReader, error) { vr := bvrp.pool.Get().(*extJSONValueReader) - vr = vr.reset(r, canonical) - return vr + return vr.reset(r, canonical) } // Put inserts a ValueReader into the pool. If the ValueReader is not a ExtJSON ValueReader nothing @@ -47,7 +45,7 @@ func (bvrp *ExtJSONValueReaderPool) Put(vr ValueReader) (ok bool) { return false } - bvr = bvr.reset(nil, false) + bvr, _ = bvr.reset(nil, false) bvrp.pool.Put(bvr) return true } @@ -69,22 +67,21 @@ type extJSONValueReader struct { // NewExtJSONValueReader creates a new ValueReader from a given io.Reader // It will interpret the JSON of r as canonical or relaxed according to the // given canonical flag -func NewExtJSONValueReader(r io.Reader, canonical bool) ValueReader { +func NewExtJSONValueReader(r io.Reader, canonical bool) (ValueReader, error) { return newExtJSONValueReader(r, canonical) } -func newExtJSONValueReader(r io.Reader, canonical bool) *extJSONValueReader { +func newExtJSONValueReader(r io.Reader, canonical bool) (*extJSONValueReader, error) { ejvr := new(extJSONValueReader) return ejvr.reset(r, canonical) } -func (ejvr *extJSONValueReader) reset(r io.Reader, canonical bool) *extJSONValueReader { +func (ejvr *extJSONValueReader) reset(r io.Reader, canonical bool) (*extJSONValueReader, error) { p := newExtJSONParser(r, canonical) typ, err := p.peekType() if err != nil { - // TODO: invalid JSON--return error message? - return nil + return nil, ErrInvalidJSON } var m mode @@ -105,7 +102,7 @@ func (ejvr *extJSONValueReader) reset(r io.Reader, canonical bool) *extJSONValue return &extJSONValueReader{ p: p, stack: stack, - } + }, nil } func (ejvr *extJSONValueReader) advanceFrame() { @@ -187,10 +184,13 @@ func (ejvr *extJSONValueReader) skipArray() error { return err } -func (ejvr *extJSONValueReader) invalidTransitionErr(destination mode) error { +func (ejvr *extJSONValueReader) invalidTransitionErr(destination mode, name string, modes []mode) error { te := TransitionError{ + name: name, current: ejvr.stack[ejvr.frame].mode, destination: destination, + modes: modes, + action: "read", } if ejvr.frame != 0 { te.parent = ejvr.stack[ejvr.frame-1].mode @@ -202,14 +202,18 @@ func (ejvr *extJSONValueReader) typeError(t bsontype.Type) error { return fmt.Errorf("positioned on %s, but attempted to read %s", ejvr.stack[ejvr.frame].vType, t) } -func (ejvr *extJSONValueReader) ensureElementValue(t bsontype.Type, destination mode) error { +func (ejvr *extJSONValueReader) ensureElementValue(t bsontype.Type, destination mode, callerName string, addModes ...mode) error { switch ejvr.stack[ejvr.frame].mode { case mElement, mValue: if ejvr.stack[ejvr.frame].vType != t { return ejvr.typeError(t) } default: - return ejvr.invalidTransitionErr(destination) + modes := []mode{mElement, mValue} + if addModes != nil { + modes = append(modes, addModes...) + } + return ejvr.invalidTransitionErr(destination, callerName, modes) } return nil @@ -223,7 +227,7 @@ func (ejvr *extJSONValueReader) Skip() error { switch ejvr.stack[ejvr.frame].mode { case mElement, mValue: default: - return ejvr.invalidTransitionErr(0) + return ejvr.invalidTransitionErr(0, "Skip", []mode{mElement, mValue}) } defer ejvr.pop() @@ -270,7 +274,7 @@ func (ejvr *extJSONValueReader) ReadArray() (ArrayReader, error) { case mArray: return ejvr, nil default: - if err := ejvr.ensureElementValue(bsontype.Array, mArray); err != nil { + if err := ejvr.ensureElementValue(bsontype.Array, mArray, "ReadArray", mTopLevel, mArray); err != nil { return nil, err } } @@ -281,7 +285,7 @@ func (ejvr *extJSONValueReader) ReadArray() (ArrayReader, error) { } func (ejvr *extJSONValueReader) ReadBinary() (b []byte, btype byte, err error) { - if err := ejvr.ensureElementValue(bsontype.Binary, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Binary, 0, "ReadBinary"); err != nil { return nil, 0, err } @@ -297,7 +301,7 @@ func (ejvr *extJSONValueReader) ReadBinary() (b []byte, btype byte, err error) { } func (ejvr *extJSONValueReader) ReadBoolean() (bool, error) { - if err := ejvr.ensureElementValue(bsontype.Boolean, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Boolean, 0, "ReadBoolean"); err != nil { return false, err } @@ -326,12 +330,12 @@ func (ejvr *extJSONValueReader) ReadDocument() (DocumentReader, error) { ejvr.pushDocument() return ejvr, nil default: - return nil, ejvr.invalidTransitionErr(mDocument) + return nil, ejvr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue}) } } func (ejvr *extJSONValueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) { - if err = ejvr.ensureElementValue(bsontype.CodeWithScope, 0); err != nil { + if err = ejvr.ensureElementValue(bsontype.CodeWithScope, 0, "ReadCodeWithScope"); err != nil { return "", nil, err } @@ -346,14 +350,14 @@ func (ejvr *extJSONValueReader) ReadCodeWithScope() (code string, dr DocumentRea return code, ejvr, err } -func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid objectid.ObjectID, err error) { - if err = ejvr.ensureElementValue(bsontype.DBPointer, 0); err != nil { - return "", objectid.NilObjectID, err +func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) { + if err = ejvr.ensureElementValue(bsontype.DBPointer, 0, "ReadDBPointer"); err != nil { + return "", primitive.NilObjectID, err } v, err := ejvr.p.readValue(bsontype.DBPointer) if err != nil { - return "", objectid.NilObjectID, err + return "", primitive.NilObjectID, err } ns, oid, err = v.parseDBPointer() @@ -363,7 +367,7 @@ func (ejvr *extJSONValueReader) ReadDBPointer() (ns string, oid objectid.ObjectI } func (ejvr *extJSONValueReader) ReadDateTime() (int64, error) { - if err := ejvr.ensureElementValue(bsontype.DateTime, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.DateTime, 0, "ReadDateTime"); err != nil { return 0, err } @@ -378,14 +382,14 @@ func (ejvr *extJSONValueReader) ReadDateTime() (int64, error) { return d, err } -func (ejvr *extJSONValueReader) ReadDecimal128() (decimal.Decimal128, error) { - if err := ejvr.ensureElementValue(bsontype.Decimal128, 0); err != nil { - return decimal.Decimal128{}, err +func (ejvr *extJSONValueReader) ReadDecimal128() (primitive.Decimal128, error) { + if err := ejvr.ensureElementValue(bsontype.Decimal128, 0, "ReadDecimal128"); err != nil { + return primitive.Decimal128{}, err } v, err := ejvr.p.readValue(bsontype.Decimal128) if err != nil { - return decimal.Decimal128{}, err + return primitive.Decimal128{}, err } d, err := v.parseDecimal128() @@ -395,7 +399,7 @@ func (ejvr *extJSONValueReader) ReadDecimal128() (decimal.Decimal128, error) { } func (ejvr *extJSONValueReader) ReadDouble() (float64, error) { - if err := ejvr.ensureElementValue(bsontype.Double, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Double, 0, "ReadDouble"); err != nil { return 0, err } @@ -411,7 +415,7 @@ func (ejvr *extJSONValueReader) ReadDouble() (float64, error) { } func (ejvr *extJSONValueReader) ReadInt32() (int32, error) { - if err := ejvr.ensureElementValue(bsontype.Int32, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Int32, 0, "ReadInt32"); err != nil { return 0, err } @@ -427,7 +431,7 @@ func (ejvr *extJSONValueReader) ReadInt32() (int32, error) { } func (ejvr *extJSONValueReader) ReadInt64() (int64, error) { - if err := ejvr.ensureElementValue(bsontype.Int64, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Int64, 0, "ReadInt64"); err != nil { return 0, err } @@ -443,7 +447,7 @@ func (ejvr *extJSONValueReader) ReadInt64() (int64, error) { } func (ejvr *extJSONValueReader) ReadJavascript() (code string, err error) { - if err = ejvr.ensureElementValue(bsontype.JavaScript, 0); err != nil { + if err = ejvr.ensureElementValue(bsontype.JavaScript, 0, "ReadJavascript"); err != nil { return "", err } @@ -459,7 +463,7 @@ func (ejvr *extJSONValueReader) ReadJavascript() (code string, err error) { } func (ejvr *extJSONValueReader) ReadMaxKey() error { - if err := ejvr.ensureElementValue(bsontype.MaxKey, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.MaxKey, 0, "ReadMaxKey"); err != nil { return err } @@ -475,7 +479,7 @@ func (ejvr *extJSONValueReader) ReadMaxKey() error { } func (ejvr *extJSONValueReader) ReadMinKey() error { - if err := ejvr.ensureElementValue(bsontype.MinKey, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.MinKey, 0, "ReadMinKey"); err != nil { return err } @@ -491,7 +495,7 @@ func (ejvr *extJSONValueReader) ReadMinKey() error { } func (ejvr *extJSONValueReader) ReadNull() error { - if err := ejvr.ensureElementValue(bsontype.Null, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Null, 0, "ReadNull"); err != nil { return err } @@ -508,14 +512,14 @@ func (ejvr *extJSONValueReader) ReadNull() error { return nil } -func (ejvr *extJSONValueReader) ReadObjectID() (objectid.ObjectID, error) { - if err := ejvr.ensureElementValue(bsontype.ObjectID, 0); err != nil { - return objectid.ObjectID{}, err +func (ejvr *extJSONValueReader) ReadObjectID() (primitive.ObjectID, error) { + if err := ejvr.ensureElementValue(bsontype.ObjectID, 0, "ReadObjectID"); err != nil { + return primitive.ObjectID{}, err } v, err := ejvr.p.readValue(bsontype.ObjectID) if err != nil { - return objectid.ObjectID{}, err + return primitive.ObjectID{}, err } oid, err := v.parseObjectID() @@ -525,7 +529,7 @@ func (ejvr *extJSONValueReader) ReadObjectID() (objectid.ObjectID, error) { } func (ejvr *extJSONValueReader) ReadRegex() (pattern string, options string, err error) { - if err = ejvr.ensureElementValue(bsontype.Regex, 0); err != nil { + if err = ejvr.ensureElementValue(bsontype.Regex, 0, "ReadRegex"); err != nil { return "", "", err } @@ -541,7 +545,7 @@ func (ejvr *extJSONValueReader) ReadRegex() (pattern string, options string, err } func (ejvr *extJSONValueReader) ReadString() (string, error) { - if err := ejvr.ensureElementValue(bsontype.String, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.String, 0, "ReadString"); err != nil { return "", err } @@ -559,7 +563,7 @@ func (ejvr *extJSONValueReader) ReadString() (string, error) { } func (ejvr *extJSONValueReader) ReadSymbol() (symbol string, err error) { - if err = ejvr.ensureElementValue(bsontype.Symbol, 0); err != nil { + if err = ejvr.ensureElementValue(bsontype.Symbol, 0, "ReadSymbol"); err != nil { return "", err } @@ -575,7 +579,7 @@ func (ejvr *extJSONValueReader) ReadSymbol() (symbol string, err error) { } func (ejvr *extJSONValueReader) ReadTimestamp() (t uint32, i uint32, err error) { - if err = ejvr.ensureElementValue(bsontype.Timestamp, 0); err != nil { + if err = ejvr.ensureElementValue(bsontype.Timestamp, 0, "ReadTimestamp"); err != nil { return 0, 0, err } @@ -591,7 +595,7 @@ func (ejvr *extJSONValueReader) ReadTimestamp() (t uint32, i uint32, err error) } func (ejvr *extJSONValueReader) ReadUndefined() error { - if err := ejvr.ensureElementValue(bsontype.Undefined, 0); err != nil { + if err := ejvr.ensureElementValue(bsontype.Undefined, 0, "ReadUndefined"); err != nil { return err } @@ -610,7 +614,7 @@ func (ejvr *extJSONValueReader) ReadElement() (string, ValueReader, error) { switch ejvr.stack[ejvr.frame].mode { case mTopLevel, mDocument, mCodeWithScope: default: - return "", nil, ejvr.invalidTransitionErr(mElement) + return "", nil, ejvr.invalidTransitionErr(mElement, "ReadElement", []mode{mTopLevel, mDocument, mCodeWithScope}) } name, t, err := ejvr.p.readKey() @@ -638,7 +642,7 @@ func (ejvr *extJSONValueReader) ReadValue() (ValueReader, error) { switch ejvr.stack[ejvr.frame].mode { case mArray: default: - return nil, ejvr.invalidTransitionErr(mValue) + return nil, ejvr.invalidTransitionErr(mValue, "ReadValue", []mode{mArray}) } t, err := ejvr.p.peekType() diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_tables.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_tables.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_tables.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_tables.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_wrappers.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_wrappers.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_wrappers.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_wrappers.go index cfe68a6..98135d9 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_wrappers.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_wrappers.go @@ -14,9 +14,8 @@ import ( "strconv" "time" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) func wrapperKeyBSONType(key string) bsontype.Type { @@ -126,9 +125,9 @@ func (ejv *extJSONValue) parseBinary() (b []byte, subType byte, err error) { return b, subType, nil } -func (ejv *extJSONValue) parseDBPointer() (ns string, oid objectid.ObjectID, err error) { +func (ejv *extJSONValue) parseDBPointer() (ns string, oid primitive.ObjectID, err error) { if ejv.t != bsontype.EmbeddedDocument { - return "", objectid.NilObjectID, fmt.Errorf("$dbPointer value should be object, but instead is %s", ejv.t) + return "", primitive.NilObjectID, fmt.Errorf("$dbPointer value should be object, but instead is %s", ejv.t) } dbpObj := ejv.v.(*extJSONObject) @@ -141,32 +140,32 @@ func (ejv *extJSONValue) parseDBPointer() (ns string, oid objectid.ObjectID, err switch key { case "$ref": if nsFound { - return "", objectid.NilObjectID, errors.New("duplicate $ref key in $dbPointer") + return "", primitive.NilObjectID, errors.New("duplicate $ref key in $dbPointer") } if val.t != bsontype.String { - return "", objectid.NilObjectID, fmt.Errorf("$dbPointer $ref value should be string, but instead is %s", val.t) + return "", primitive.NilObjectID, fmt.Errorf("$dbPointer $ref value should be string, but instead is %s", val.t) } ns = val.v.(string) nsFound = true case "$id": if oidFound { - return "", objectid.NilObjectID, errors.New("duplicate $id key in $dbPointer") + return "", primitive.NilObjectID, errors.New("duplicate $id key in $dbPointer") } if val.t != bsontype.String { - return "", objectid.NilObjectID, fmt.Errorf("$dbPointer $id value should be string, but instead is %s", val.t) + return "", primitive.NilObjectID, fmt.Errorf("$dbPointer $id value should be string, but instead is %s", val.t) } - oid, err = objectid.FromHex(val.v.(string)) + oid, err = primitive.ObjectIDFromHex(val.v.(string)) if err != nil { - return "", objectid.NilObjectID, err + return "", primitive.NilObjectID, err } oidFound = true default: - return "", objectid.NilObjectID, fmt.Errorf("invalid key in $dbPointer object: %s", key) + return "", primitive.NilObjectID, fmt.Errorf("invalid key in $dbPointer object: %s", key) } } @@ -185,6 +184,10 @@ const rfc3339Milli = "2006-01-02T15:04:05.999Z07:00" func (ejv *extJSONValue) parseDateTime() (int64, error) { switch ejv.t { + case bsontype.Int32: + return int64(ejv.v.(int32)), nil + case bsontype.Int64: + return ejv.v.(int64), nil case bsontype.String: return parseDatetimeString(ejv.v.(string)) case bsontype.EmbeddedDocument: @@ -236,14 +239,14 @@ func parseDatetimeObject(data *extJSONObject) (d int64, err error) { return d, nil } -func (ejv *extJSONValue) parseDecimal128() (decimal.Decimal128, error) { +func (ejv *extJSONValue) parseDecimal128() (primitive.Decimal128, error) { if ejv.t != bsontype.String { - return decimal.Decimal128{}, fmt.Errorf("$numberDecimal value should be string, but instead is %s", ejv.t) + return primitive.Decimal128{}, fmt.Errorf("$numberDecimal value should be string, but instead is %s", ejv.t) } - d, err := decimal.ParseDecimal128(ejv.v.(string)) + d, err := primitive.ParseDecimal128(ejv.v.(string)) if err != nil { - return decimal.Decimal128{}, fmt.Errorf("$invalid $numberDecimal string: %s", ejv.v.(string)) + return primitive.Decimal128{}, fmt.Errorf("$invalid $numberDecimal string: %s", ejv.v.(string)) } return d, nil @@ -333,12 +336,12 @@ func (ejv *extJSONValue) parseMinMaxKey(minmax string) error { return nil } -func (ejv *extJSONValue) parseObjectID() (objectid.ObjectID, error) { +func (ejv *extJSONValue) parseObjectID() (primitive.ObjectID, error) { if ejv.t != bsontype.String { - return objectid.NilObjectID, fmt.Errorf("$oid value should be string, but instead is %s", ejv.t) + return primitive.NilObjectID, fmt.Errorf("$oid value should be string, but instead is %s", ejv.t) } - return objectid.FromHex(ejv.v.(string)) + return primitive.ObjectIDFromHex(ejv.v.(string)) } func (ejv *extJSONValue) parseRegex() (pattern, options string, err error) { diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_writer.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_writer.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_writer.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_writer.go index 0939355..b34b937 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/extjson_writer.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/extjson_writer.go @@ -10,6 +10,7 @@ import ( "bytes" "encoding/base64" "fmt" + "go.mongodb.org/mongo-driver/bson/primitive" "io" "math" "sort" @@ -18,9 +19,6 @@ import ( "sync" "time" "unicode/utf8" - - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" ) var ejvwPool = sync.Pool{ @@ -111,6 +109,18 @@ func newExtJSONWriter(w io.Writer, canonical, escapeHTML bool) *extJSONValueWrit } } +func newExtJSONWriterFromSlice(buf []byte, canonical, escapeHTML bool) *extJSONValueWriter { + stack := make([]ejvwState, 1, 5) + stack[0] = ejvwState{mode: mTopLevel} + + return &extJSONValueWriter{ + buf: buf, + stack: stack, + canonical: canonical, + escapeHTML: escapeHTML, + } +} + func (ejvw *extJSONValueWriter) reset(buf []byte, canonical, escapeHTML bool) { if ejvw.stack == nil { ejvw.stack = make([]ejvwState, 1, 5) @@ -154,10 +164,13 @@ func (ejvw *extJSONValueWriter) pop() { } } -func (ejvw *extJSONValueWriter) invalidTransitionErr(destination mode) error { +func (ejvw *extJSONValueWriter) invalidTransitionErr(destination mode, name string, modes []mode) error { te := TransitionError{ + name: name, current: ejvw.stack[ejvw.frame].mode, destination: destination, + modes: modes, + action: "write", } if ejvw.frame != 0 { te.parent = ejvw.stack[ejvw.frame-1].mode @@ -165,11 +178,15 @@ func (ejvw *extJSONValueWriter) invalidTransitionErr(destination mode) error { return te } -func (ejvw *extJSONValueWriter) ensureElementValue(destination mode) error { +func (ejvw *extJSONValueWriter) ensureElementValue(destination mode, callerName string, addmodes ...mode) error { switch ejvw.stack[ejvw.frame].mode { case mElement, mValue: default: - return ejvw.invalidTransitionErr(destination) + modes := []mode{mElement, mValue} + if addmodes != nil { + modes = append(modes, addmodes...) + } + return ejvw.invalidTransitionErr(destination, callerName, modes) } return nil @@ -187,7 +204,7 @@ func (ejvw *extJSONValueWriter) writeExtendedSingleValue(key string, value strin } func (ejvw *extJSONValueWriter) WriteArray() (ArrayWriter, error) { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mArray, "WriteArray"); err != nil { return nil, err } @@ -202,7 +219,7 @@ func (ejvw *extJSONValueWriter) WriteBinary(b []byte) error { } func (ejvw *extJSONValueWriter) WriteBinaryWithSubtype(b []byte, btype byte) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteBinaryWithSubtype"); err != nil { return err } @@ -218,7 +235,7 @@ func (ejvw *extJSONValueWriter) WriteBinaryWithSubtype(b []byte, btype byte) err } func (ejvw *extJSONValueWriter) WriteBoolean(b bool) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteBoolean"); err != nil { return err } @@ -230,7 +247,7 @@ func (ejvw *extJSONValueWriter) WriteBoolean(b bool) error { } func (ejvw *extJSONValueWriter) WriteCodeWithScope(code string) (DocumentWriter, error) { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mCodeWithScope, "WriteCodeWithScope"); err != nil { return nil, err } @@ -245,8 +262,8 @@ func (ejvw *extJSONValueWriter) WriteCodeWithScope(code string) (DocumentWriter, return ejvw, nil } -func (ejvw *extJSONValueWriter) WriteDBPointer(ns string, oid objectid.ObjectID) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { +func (ejvw *extJSONValueWriter) WriteDBPointer(ns string, oid primitive.ObjectID) error { + if err := ejvw.ensureElementValue(mode(0), "WriteDBPointer"); err != nil { return err } @@ -264,7 +281,7 @@ func (ejvw *extJSONValueWriter) WriteDBPointer(ns string, oid objectid.ObjectID) } func (ejvw *extJSONValueWriter) WriteDateTime(dt int64) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteDateTime"); err != nil { return err } @@ -283,8 +300,8 @@ func (ejvw *extJSONValueWriter) WriteDateTime(dt int64) error { return nil } -func (ejvw *extJSONValueWriter) WriteDecimal128(d decimal.Decimal128) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { +func (ejvw *extJSONValueWriter) WriteDecimal128(d primitive.Decimal128) error { + if err := ejvw.ensureElementValue(mode(0), "WriteDecimal128"); err != nil { return err } @@ -301,7 +318,7 @@ func (ejvw *extJSONValueWriter) WriteDocument() (DocumentWriter, error) { return ejvw, nil } - if err := ejvw.ensureElementValue(mDocument); err != nil { + if err := ejvw.ensureElementValue(mDocument, "WriteDocument", mTopLevel); err != nil { return nil, err } @@ -311,7 +328,7 @@ func (ejvw *extJSONValueWriter) WriteDocument() (DocumentWriter, error) { } func (ejvw *extJSONValueWriter) WriteDouble(f float64) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteDouble"); err != nil { return err } @@ -338,7 +355,7 @@ func (ejvw *extJSONValueWriter) WriteDouble(f float64) error { } func (ejvw *extJSONValueWriter) WriteInt32(i int32) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteInt32"); err != nil { return err } @@ -357,7 +374,7 @@ func (ejvw *extJSONValueWriter) WriteInt32(i int32) error { } func (ejvw *extJSONValueWriter) WriteInt64(i int64) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteInt64"); err != nil { return err } @@ -376,7 +393,7 @@ func (ejvw *extJSONValueWriter) WriteInt64(i int64) error { } func (ejvw *extJSONValueWriter) WriteJavascript(code string) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteJavascript"); err != nil { return err } @@ -391,7 +408,7 @@ func (ejvw *extJSONValueWriter) WriteJavascript(code string) error { } func (ejvw *extJSONValueWriter) WriteMaxKey() error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteMaxKey"); err != nil { return err } @@ -403,7 +420,7 @@ func (ejvw *extJSONValueWriter) WriteMaxKey() error { } func (ejvw *extJSONValueWriter) WriteMinKey() error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteMinKey"); err != nil { return err } @@ -415,7 +432,7 @@ func (ejvw *extJSONValueWriter) WriteMinKey() error { } func (ejvw *extJSONValueWriter) WriteNull() error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteNull"); err != nil { return err } @@ -426,8 +443,8 @@ func (ejvw *extJSONValueWriter) WriteNull() error { return nil } -func (ejvw *extJSONValueWriter) WriteObjectID(oid objectid.ObjectID) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { +func (ejvw *extJSONValueWriter) WriteObjectID(oid primitive.ObjectID) error { + if err := ejvw.ensureElementValue(mode(0), "WriteObjectID"); err != nil { return err } @@ -439,7 +456,7 @@ func (ejvw *extJSONValueWriter) WriteObjectID(oid objectid.ObjectID) error { } func (ejvw *extJSONValueWriter) WriteRegex(pattern string, options string) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteRegex"); err != nil { return err } @@ -457,7 +474,7 @@ func (ejvw *extJSONValueWriter) WriteRegex(pattern string, options string) error } func (ejvw *extJSONValueWriter) WriteString(s string) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteString"); err != nil { return err } @@ -472,7 +489,7 @@ func (ejvw *extJSONValueWriter) WriteString(s string) error { } func (ejvw *extJSONValueWriter) WriteSymbol(symbol string) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteSymbol"); err != nil { return err } @@ -487,7 +504,7 @@ func (ejvw *extJSONValueWriter) WriteSymbol(symbol string) error { } func (ejvw *extJSONValueWriter) WriteTimestamp(t uint32, i uint32) error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteTimestamp"); err != nil { return err } @@ -505,7 +522,7 @@ func (ejvw *extJSONValueWriter) WriteTimestamp(t uint32, i uint32) error { } func (ejvw *extJSONValueWriter) WriteUndefined() error { - if err := ejvw.ensureElementValue(mode(0)); err != nil { + if err := ejvw.ensureElementValue(mode(0), "WriteUndefined"); err != nil { return err } @@ -522,7 +539,7 @@ func (ejvw *extJSONValueWriter) WriteDocumentElement(key string) (ValueWriter, e ejvw.buf = append(ejvw.buf, []byte(fmt.Sprintf(`"%s":`, key))...) ejvw.push(mElement) default: - return nil, ejvw.invalidTransitionErr(mElement) + return nil, ejvw.invalidTransitionErr(mElement, "WriteDocumentElement", []mode{mDocument, mTopLevel, mCodeWithScope}) } return ejvw, nil @@ -566,7 +583,7 @@ func (ejvw *extJSONValueWriter) WriteArrayElement() (ValueWriter, error) { case mArray: ejvw.push(mValue) default: - return nil, ejvw.invalidTransitionErr(mValue) + return nil, ejvw.invalidTransitionErr(mValue, "WriteArrayElement", []mode{mArray}) } return ejvw, nil @@ -586,7 +603,7 @@ func (ejvw *extJSONValueWriter) WriteArrayEnd() error { ejvw.pop() default: - return fmt.Errorf("incorret mode to end array: %s", ejvw.stack[ejvw.frame].mode) + return fmt.Errorf("incorrect mode to end array: %s", ejvw.stack[ejvw.frame].mode) } return nil @@ -604,7 +621,7 @@ func formatDouble(f float64) string { // Print exactly one decimalType place for integers; otherwise, print as many are necessary to // perfectly represent it. s = strconv.FormatFloat(f, 'G', -1, 64) - if !strings.ContainsRune(s, '.') { + if !strings.ContainsRune(s, 'E') && !strings.ContainsRune(s, '.') { s += ".0" } } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/json_scanner.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/json_scanner.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/json_scanner.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/json_scanner.go index dba7aaf..03aabf5 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/json_scanner.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/json_scanner.go @@ -42,9 +42,10 @@ type jsonToken struct { } type jsonScanner struct { - r io.Reader - buf []byte - pos int + r io.Reader + buf []byte + pos int + lastReadErr error } // nextToken returns the next JSON token if one exists. A token is a character @@ -126,11 +127,23 @@ func (js *jsonScanner) readNNextBytes(dst []byte, n, offset int) error { // readIntoBuf reads up to 512 bytes from the scanner's io.Reader into the buffer func (js *jsonScanner) readIntoBuf() error { + if js.lastReadErr != nil { + js.buf = js.buf[:0] + js.pos = 0 + return js.lastReadErr + } + if cap(js.buf) == 0 { js.buf = make([]byte, 0, 512) } n, err := js.r.Read(js.buf[:cap(js.buf)]) + if err != nil { + js.lastReadErr = err + if n > 0 { + err = nil + } + } js.buf = js.buf[:n] js.pos = 0 @@ -404,25 +417,23 @@ func (js *jsonScanner) scanNumber(first byte) (*jsonToken, error) { return nil, fmt.Errorf("invalid JSON number. Position: %d", start) case nssDone: js.pos = int(math.Max(0, float64(js.pos-1))) - if t == jttDouble { - v, err := strconv.ParseFloat(b.String(), 64) - if err != nil { - return nil, err + if t != jttDouble { + v, err := strconv.ParseInt(b.String(), 10, 64) + if err == nil { + if v < math.MinInt32 || v > math.MaxInt32 { + return &jsonToken{t: jttInt64, v: v, p: start}, nil + } + + return &jsonToken{t: jttInt32, v: int32(v), p: start}, nil } - - return &jsonToken{t: t, v: v, p: start}, nil } - v, err := strconv.ParseInt(b.String(), 10, 64) + v, err := strconv.ParseFloat(b.String(), 64) if err != nil { return nil, err } - if v < math.MinInt32 || v > math.MaxInt32 { - return &jsonToken{t: t, v: v, p: start}, nil - } - - return &jsonToken{t: jttInt32, v: int32(v), p: start}, nil + return &jsonToken{t: jttDouble, v: v, p: start}, nil } } } diff --git a/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/mode.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/mode.go new file mode 100644 index 0000000..617b5e2 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/mode.go @@ -0,0 +1,108 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package bsonrw + +import ( + "fmt" +) + +type mode int + +const ( + _ mode = iota + mTopLevel + mDocument + mArray + mValue + mElement + mCodeWithScope + mSpacer +) + +func (m mode) String() string { + var str string + + switch m { + case mTopLevel: + str = "TopLevel" + case mDocument: + str = "DocumentMode" + case mArray: + str = "ArrayMode" + case mValue: + str = "ValueMode" + case mElement: + str = "ElementMode" + case mCodeWithScope: + str = "CodeWithScopeMode" + case mSpacer: + str = "CodeWithScopeSpacerFrame" + default: + str = "UnknownMode" + } + + return str +} + +func (m mode) TypeString() string { + var str string + + switch m { + case mTopLevel: + str = "TopLevel" + case mDocument: + str = "Document" + case mArray: + str = "Array" + case mValue: + str = "Value" + case mElement: + str = "Element" + case mCodeWithScope: + str = "CodeWithScope" + case mSpacer: + str = "CodeWithScopeSpacer" + default: + str = "Unknown" + } + + return str +} + +// TransitionError is an error returned when an invalid progressing a +// ValueReader or ValueWriter state machine occurs. +// If read is false, the error is for writing +type TransitionError struct { + name string + parent mode + current mode + destination mode + modes []mode + action string +} + +func (te TransitionError) Error() string { + errString := fmt.Sprintf("%s can only %s", te.name, te.action) + if te.destination != mode(0) { + errString = fmt.Sprintf("%s a %s", errString, te.destination.TypeString()) + } + errString = fmt.Sprintf("%s while positioned on a", errString) + for ind, m := range te.modes { + if ind != 0 && len(te.modes) > 2 { + errString = fmt.Sprintf("%s,", errString) + } + if ind == len(te.modes)-1 && len(te.modes) > 1 { + errString = fmt.Sprintf("%s or", errString) + } + errString = fmt.Sprintf("%s %s", errString, m.TypeString()) + } + errString = fmt.Sprintf("%s but is positioned on a %s", errString, te.current.TypeString()) + if te.parent != mode(0) { + errString = fmt.Sprintf("%s with parent %s", errString, te.parent.TypeString()) + } + return errString +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/reader.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/reader.go similarity index 86% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/reader.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/reader.go index cb96722..0b8fa28 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/reader.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/reader.go @@ -7,9 +7,8 @@ package bsonrw import ( - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // ArrayReader is implemented by types that allow reading values from a BSON @@ -36,9 +35,9 @@ type ValueReader interface { ReadBoolean() (bool, error) ReadDocument() (DocumentReader, error) ReadCodeWithScope() (code string, dr DocumentReader, err error) - ReadDBPointer() (ns string, oid objectid.ObjectID, err error) + ReadDBPointer() (ns string, oid primitive.ObjectID, err error) ReadDateTime() (int64, error) - ReadDecimal128() (decimal.Decimal128, error) + ReadDecimal128() (primitive.Decimal128, error) ReadDouble() (float64, error) ReadInt32() (int32, error) ReadInt64() (int64, error) @@ -46,7 +45,7 @@ type ValueReader interface { ReadMaxKey() error ReadMinKey() error ReadNull() error - ReadObjectID() (objectid.ObjectID, error) + ReadObjectID() (primitive.ObjectID, error) ReadRegex() (pattern, options string, err error) ReadString() (string, error) ReadSymbol() (symbol string, err error) diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/value_reader.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/value_reader.go similarity index 81% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/value_reader.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/value_reader.go index ecc79bf..fad47ba 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/value_reader.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/value_reader.go @@ -16,9 +16,8 @@ import ( "sync" "unicode" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) var _ ValueReader = (*valueReader)(nil) @@ -217,10 +216,13 @@ func (vr *valueReader) pop() { } } -func (vr *valueReader) invalidTransitionErr(destination mode) error { +func (vr *valueReader) invalidTransitionErr(destination mode, name string, modes []mode) error { te := TransitionError{ + name: name, current: vr.stack[vr.frame].mode, destination: destination, + modes: modes, + action: "read", } if vr.frame != 0 { te.parent = vr.stack[vr.frame-1].mode @@ -236,14 +238,14 @@ func (vr *valueReader) invalidDocumentLengthError() error { return fmt.Errorf("document is invalid, end byte is at %d, but null byte found at %d", vr.stack[vr.frame].end, vr.offset) } -func (vr *valueReader) ensureElementValue(t bsontype.Type, destination mode) error { +func (vr *valueReader) ensureElementValue(t bsontype.Type, destination mode, callerName string) error { switch vr.stack[vr.frame].mode { case mElement, mValue: if vr.stack[vr.frame].vType != t { return vr.typeError(t) } default: - return vr.invalidTransitionErr(destination) + return vr.invalidTransitionErr(destination, callerName, []mode{mElement, mValue}) } return nil @@ -258,14 +260,14 @@ func (vr *valueReader) nextElementLength() (int32, error) { var err error switch vr.stack[vr.frame].vType { case bsontype.Array, bsontype.EmbeddedDocument, bsontype.CodeWithScope: - length, err = vr.peakLength() + length, err = vr.peekLength() case bsontype.Binary: - length, err = vr.peakLength() + length, err = vr.peekLength() length += 4 + 1 // binary length + subtype byte case bsontype.Boolean: length = 1 case bsontype.DBPointer: - length, err = vr.peakLength() + length, err = vr.peekLength() length += 4 + 12 // string length + ObjectID length case bsontype.DateTime, bsontype.Double, bsontype.Int64, bsontype.Timestamp: length = 8 @@ -274,7 +276,7 @@ func (vr *valueReader) nextElementLength() (int32, error) { case bsontype.Int32: length = 4 case bsontype.JavaScript, bsontype.String, bsontype.Symbol: - length, err = vr.peakLength() + length, err = vr.peekLength() length += 4 case bsontype.MaxKey, bsontype.MinKey, bsontype.Null, bsontype.Undefined: length = 0 @@ -286,12 +288,12 @@ func (vr *valueReader) nextElementLength() (int32, error) { err = io.EOF break } - pattern := bytes.IndexByte(vr.d[regex+1:], 0x00) + pattern := bytes.IndexByte(vr.d[vr.offset+int64(regex)+1:], 0x00) if pattern < 0 { err = io.EOF break } - length = int32(int64(regex) + 1 + int64(pattern) + 1 - vr.offset) + length = int32(int64(regex) + 1 + int64(pattern) + 1) default: return 0, fmt.Errorf("attempted to read bytes of unknown BSON type %v", vr.stack[vr.frame].vType) } @@ -301,27 +303,36 @@ func (vr *valueReader) nextElementLength() (int32, error) { func (vr *valueReader) ReadValueBytes(dst []byte) (bsontype.Type, []byte, error) { switch vr.stack[vr.frame].mode { + case mTopLevel: + length, err := vr.peekLength() + if err != nil { + return bsontype.Type(0), nil, err + } + dst, err = vr.appendBytes(dst, length) + if err != nil { + return bsontype.Type(0), nil, err + } + return bsontype.Type(0), dst, nil case mElement, mValue: - default: - return bsontype.Type(0), nil, vr.invalidTransitionErr(0) - } + length, err := vr.nextElementLength() + if err != nil { + return bsontype.Type(0), dst, err + } - length, err := vr.nextElementLength() - if err != nil { - return bsontype.Type(0), dst, err + dst, err = vr.appendBytes(dst, length) + t := vr.stack[vr.frame].vType + vr.pop() + return t, dst, err + default: + return bsontype.Type(0), nil, vr.invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue}) } - - dst, err = vr.appendBytes(dst, length) - t := vr.stack[vr.frame].vType - vr.pop() - return t, dst, err } func (vr *valueReader) Skip() error { switch vr.stack[vr.frame].mode { case mElement, mValue: default: - return vr.invalidTransitionErr(0) + return vr.invalidTransitionErr(0, "Skip", []mode{mElement, mValue}) } length, err := vr.nextElementLength() @@ -335,7 +346,7 @@ func (vr *valueReader) Skip() error { } func (vr *valueReader) ReadArray() (ArrayReader, error) { - if err := vr.ensureElementValue(bsontype.Array, mArray); err != nil { + if err := vr.ensureElementValue(bsontype.Array, mArray, "ReadArray"); err != nil { return nil, err } @@ -348,7 +359,7 @@ func (vr *valueReader) ReadArray() (ArrayReader, error) { } func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { - if err := vr.ensureElementValue(bsontype.Binary, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Binary, 0, "ReadBinary"); err != nil { return nil, 0, err } @@ -379,7 +390,7 @@ func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { } func (vr *valueReader) ReadBoolean() (bool, error) { - if err := vr.ensureElementValue(bsontype.Boolean, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Boolean, 0, "ReadBoolean"); err != nil { return false, err } @@ -414,7 +425,7 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { return nil, vr.typeError(bsontype.EmbeddedDocument) } default: - return nil, vr.invalidTransitionErr(mDocument) + return nil, vr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue}) } err := vr.pushDocument() @@ -426,7 +437,7 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { } func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) { - if err := vr.ensureElementValue(bsontype.CodeWithScope, 0); err != nil { + if err := vr.ensureElementValue(bsontype.CodeWithScope, 0, "ReadCodeWithScope"); err != nil { return "", nil, err } @@ -461,8 +472,8 @@ func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err return code, vr, nil } -func (vr *valueReader) ReadDBPointer() (ns string, oid objectid.ObjectID, err error) { - if err := vr.ensureElementValue(bsontype.DBPointer, 0); err != nil { +func (vr *valueReader) ReadDBPointer() (ns string, oid primitive.ObjectID, err error) { + if err := vr.ensureElementValue(bsontype.DBPointer, 0, "ReadDBPointer"); err != nil { return "", oid, err } @@ -483,7 +494,7 @@ func (vr *valueReader) ReadDBPointer() (ns string, oid objectid.ObjectID, err er } func (vr *valueReader) ReadDateTime() (int64, error) { - if err := vr.ensureElementValue(bsontype.DateTime, 0); err != nil { + if err := vr.ensureElementValue(bsontype.DateTime, 0, "ReadDateTime"); err != nil { return 0, err } @@ -496,25 +507,25 @@ func (vr *valueReader) ReadDateTime() (int64, error) { return i, nil } -func (vr *valueReader) ReadDecimal128() (decimal.Decimal128, error) { - if err := vr.ensureElementValue(bsontype.Decimal128, 0); err != nil { - return decimal.Decimal128{}, err +func (vr *valueReader) ReadDecimal128() (primitive.Decimal128, error) { + if err := vr.ensureElementValue(bsontype.Decimal128, 0, "ReadDecimal128"); err != nil { + return primitive.Decimal128{}, err } b, err := vr.readBytes(16) if err != nil { - return decimal.Decimal128{}, err + return primitive.Decimal128{}, err } l := binary.LittleEndian.Uint64(b[0:8]) h := binary.LittleEndian.Uint64(b[8:16]) vr.pop() - return decimal.NewDecimal128(h, l), nil + return primitive.NewDecimal128(h, l), nil } func (vr *valueReader) ReadDouble() (float64, error) { - if err := vr.ensureElementValue(bsontype.Double, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Double, 0, "ReadDouble"); err != nil { return 0, err } @@ -528,7 +539,7 @@ func (vr *valueReader) ReadDouble() (float64, error) { } func (vr *valueReader) ReadInt32() (int32, error) { - if err := vr.ensureElementValue(bsontype.Int32, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Int32, 0, "ReadInt32"); err != nil { return 0, err } @@ -537,7 +548,7 @@ func (vr *valueReader) ReadInt32() (int32, error) { } func (vr *valueReader) ReadInt64() (int64, error) { - if err := vr.ensureElementValue(bsontype.Int64, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Int64, 0, "ReadInt64"); err != nil { return 0, err } @@ -546,7 +557,7 @@ func (vr *valueReader) ReadInt64() (int64, error) { } func (vr *valueReader) ReadJavascript() (code string, err error) { - if err := vr.ensureElementValue(bsontype.JavaScript, 0); err != nil { + if err := vr.ensureElementValue(bsontype.JavaScript, 0, "ReadJavascript"); err != nil { return "", err } @@ -555,7 +566,7 @@ func (vr *valueReader) ReadJavascript() (code string, err error) { } func (vr *valueReader) ReadMaxKey() error { - if err := vr.ensureElementValue(bsontype.MaxKey, 0); err != nil { + if err := vr.ensureElementValue(bsontype.MaxKey, 0, "ReadMaxKey"); err != nil { return err } @@ -564,7 +575,7 @@ func (vr *valueReader) ReadMaxKey() error { } func (vr *valueReader) ReadMinKey() error { - if err := vr.ensureElementValue(bsontype.MinKey, 0); err != nil { + if err := vr.ensureElementValue(bsontype.MinKey, 0, "ReadMinKey"); err != nil { return err } @@ -573,7 +584,7 @@ func (vr *valueReader) ReadMinKey() error { } func (vr *valueReader) ReadNull() error { - if err := vr.ensureElementValue(bsontype.Null, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Null, 0, "ReadNull"); err != nil { return err } @@ -581,17 +592,17 @@ func (vr *valueReader) ReadNull() error { return nil } -func (vr *valueReader) ReadObjectID() (objectid.ObjectID, error) { - if err := vr.ensureElementValue(bsontype.ObjectID, 0); err != nil { - return objectid.ObjectID{}, err +func (vr *valueReader) ReadObjectID() (primitive.ObjectID, error) { + if err := vr.ensureElementValue(bsontype.ObjectID, 0, "ReadObjectID"); err != nil { + return primitive.ObjectID{}, err } oidbytes, err := vr.readBytes(12) if err != nil { - return objectid.ObjectID{}, err + return primitive.ObjectID{}, err } - var oid objectid.ObjectID + var oid primitive.ObjectID copy(oid[:], oidbytes) vr.pop() @@ -599,7 +610,7 @@ func (vr *valueReader) ReadObjectID() (objectid.ObjectID, error) { } func (vr *valueReader) ReadRegex() (string, string, error) { - if err := vr.ensureElementValue(bsontype.Regex, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Regex, 0, "ReadRegex"); err != nil { return "", "", err } @@ -618,7 +629,7 @@ func (vr *valueReader) ReadRegex() (string, string, error) { } func (vr *valueReader) ReadString() (string, error) { - if err := vr.ensureElementValue(bsontype.String, 0); err != nil { + if err := vr.ensureElementValue(bsontype.String, 0, "ReadString"); err != nil { return "", err } @@ -627,7 +638,7 @@ func (vr *valueReader) ReadString() (string, error) { } func (vr *valueReader) ReadSymbol() (symbol string, err error) { - if err := vr.ensureElementValue(bsontype.Symbol, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Symbol, 0, "ReadSymbol"); err != nil { return "", err } @@ -636,7 +647,7 @@ func (vr *valueReader) ReadSymbol() (symbol string, err error) { } func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { - if err := vr.ensureElementValue(bsontype.Timestamp, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Timestamp, 0, "ReadTimestamp"); err != nil { return 0, 0, err } @@ -655,7 +666,7 @@ func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { } func (vr *valueReader) ReadUndefined() error { - if err := vr.ensureElementValue(bsontype.Undefined, 0); err != nil { + if err := vr.ensureElementValue(bsontype.Undefined, 0, "ReadUndefined"); err != nil { return err } @@ -667,7 +678,7 @@ func (vr *valueReader) ReadElement() (string, ValueReader, error) { switch vr.stack[vr.frame].mode { case mTopLevel, mDocument, mCodeWithScope: default: - return "", nil, vr.invalidTransitionErr(mElement) + return "", nil, vr.invalidTransitionErr(mElement, "ReadElement", []mode{mTopLevel, mDocument, mCodeWithScope}) } t, err := vr.readByte() @@ -697,7 +708,7 @@ func (vr *valueReader) ReadValue() (ValueReader, error) { switch vr.stack[vr.frame].mode { case mArray: default: - return nil, vr.invalidTransitionErr(mValue) + return nil, vr.invalidTransitionErr(mValue, "ReadValue", []mode{mArray}) } t, err := vr.readByte() @@ -817,7 +828,7 @@ func (vr *valueReader) readString() (string, error) { return string(vr.d[start : start+int64(length)-1]), nil } -func (vr *valueReader) peakLength() (int32, error) { +func (vr *valueReader) peekLength() (int32, error) { if vr.offset+4 > int64(len(vr.d)) { return 0, io.EOF } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/value_writer.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/value_writer.go similarity index 79% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/value_writer.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/value_writer.go index 73c231a..caa6fae 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/value_writer.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/value_writer.go @@ -14,10 +14,9 @@ import ( "strconv" "sync" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) var _ ValueWriter = (*valueWriter)(nil) @@ -224,10 +223,13 @@ func (vw *valueWriter) reset(buf []byte) { vw.w = nil } -func (vw *valueWriter) invalidTransitionError(destination mode) error { +func (vw *valueWriter) invalidTransitionError(destination mode, name string, modes []mode) error { te := TransitionError{ + name: name, current: vw.stack[vw.frame].mode, destination: destination, + modes: modes, + action: "write", } if vw.frame != 0 { te.parent = vw.stack[vw.frame-1].mode @@ -235,7 +237,7 @@ func (vw *valueWriter) invalidTransitionError(destination mode) error { return te } -func (vw *valueWriter) writeElementHeader(t bsontype.Type, destination mode) error { +func (vw *valueWriter) writeElementHeader(t bsontype.Type, destination mode, callerName string, addmodes ...mode) error { switch vw.stack[vw.frame].mode { case mElement: vw.buf = bsoncore.AppendHeader(vw.buf, t, vw.stack[vw.frame].key) @@ -243,15 +245,18 @@ func (vw *valueWriter) writeElementHeader(t bsontype.Type, destination mode) err // TODO: Do this with a cache of the first 1000 or so array keys. vw.buf = bsoncore.AppendHeader(vw.buf, t, strconv.Itoa(vw.stack[vw.frame].arrkey)) default: - return vw.invalidTransitionError(destination) + modes := []mode{mElement, mValue} + if addmodes != nil { + modes = append(modes, addmodes...) + } + return vw.invalidTransitionError(destination, callerName, modes) } return nil } func (vw *valueWriter) WriteValueBytes(t bsontype.Type, b []byte) error { - err := vw.writeElementHeader(t, mode(0)) - if err != nil { + if err := vw.writeElementHeader(t, mode(0), "WriteValueBytes"); err != nil { return err } vw.buf = append(vw.buf, b...) @@ -260,7 +265,7 @@ func (vw *valueWriter) WriteValueBytes(t bsontype.Type, b []byte) error { } func (vw *valueWriter) WriteArray() (ArrayWriter, error) { - if err := vw.writeElementHeader(bsontype.Array, mArray); err != nil { + if err := vw.writeElementHeader(bsontype.Array, mArray, "WriteArray"); err != nil { return nil, err } @@ -274,7 +279,7 @@ func (vw *valueWriter) WriteBinary(b []byte) error { } func (vw *valueWriter) WriteBinaryWithSubtype(b []byte, btype byte) error { - if err := vw.writeElementHeader(bsontype.Binary, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Binary, mode(0), "WriteBinaryWithSubtype"); err != nil { return err } @@ -284,7 +289,7 @@ func (vw *valueWriter) WriteBinaryWithSubtype(b []byte, btype byte) error { } func (vw *valueWriter) WriteBoolean(b bool) error { - if err := vw.writeElementHeader(bsontype.Boolean, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Boolean, mode(0), "WriteBoolean"); err != nil { return err } @@ -294,7 +299,7 @@ func (vw *valueWriter) WriteBoolean(b bool) error { } func (vw *valueWriter) WriteCodeWithScope(code string) (DocumentWriter, error) { - if err := vw.writeElementHeader(bsontype.CodeWithScope, mCodeWithScope); err != nil { + if err := vw.writeElementHeader(bsontype.CodeWithScope, mCodeWithScope, "WriteCodeWithScope"); err != nil { return nil, err } @@ -310,8 +315,8 @@ func (vw *valueWriter) WriteCodeWithScope(code string) (DocumentWriter, error) { return vw, nil } -func (vw *valueWriter) WriteDBPointer(ns string, oid objectid.ObjectID) error { - if err := vw.writeElementHeader(bsontype.DBPointer, mode(0)); err != nil { +func (vw *valueWriter) WriteDBPointer(ns string, oid primitive.ObjectID) error { + if err := vw.writeElementHeader(bsontype.DBPointer, mode(0), "WriteDBPointer"); err != nil { return err } @@ -321,7 +326,7 @@ func (vw *valueWriter) WriteDBPointer(ns string, oid objectid.ObjectID) error { } func (vw *valueWriter) WriteDateTime(dt int64) error { - if err := vw.writeElementHeader(bsontype.DateTime, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.DateTime, mode(0), "WriteDateTime"); err != nil { return err } @@ -330,8 +335,8 @@ func (vw *valueWriter) WriteDateTime(dt int64) error { return nil } -func (vw *valueWriter) WriteDecimal128(d128 decimal.Decimal128) error { - if err := vw.writeElementHeader(bsontype.Decimal128, mode(0)); err != nil { +func (vw *valueWriter) WriteDecimal128(d128 primitive.Decimal128) error { + if err := vw.writeElementHeader(bsontype.Decimal128, mode(0), "WriteDecimal128"); err != nil { return err } @@ -341,7 +346,7 @@ func (vw *valueWriter) WriteDecimal128(d128 decimal.Decimal128) error { } func (vw *valueWriter) WriteDouble(f float64) error { - if err := vw.writeElementHeader(bsontype.Double, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Double, mode(0), "WriteDouble"); err != nil { return err } @@ -351,7 +356,7 @@ func (vw *valueWriter) WriteDouble(f float64) error { } func (vw *valueWriter) WriteInt32(i32 int32) error { - if err := vw.writeElementHeader(bsontype.Int32, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Int32, mode(0), "WriteInt32"); err != nil { return err } @@ -361,7 +366,7 @@ func (vw *valueWriter) WriteInt32(i32 int32) error { } func (vw *valueWriter) WriteInt64(i64 int64) error { - if err := vw.writeElementHeader(bsontype.Int64, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Int64, mode(0), "WriteInt64"); err != nil { return err } @@ -371,7 +376,7 @@ func (vw *valueWriter) WriteInt64(i64 int64) error { } func (vw *valueWriter) WriteJavascript(code string) error { - if err := vw.writeElementHeader(bsontype.JavaScript, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.JavaScript, mode(0), "WriteJavascript"); err != nil { return err } @@ -381,7 +386,7 @@ func (vw *valueWriter) WriteJavascript(code string) error { } func (vw *valueWriter) WriteMaxKey() error { - if err := vw.writeElementHeader(bsontype.MaxKey, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.MaxKey, mode(0), "WriteMaxKey"); err != nil { return err } @@ -390,7 +395,7 @@ func (vw *valueWriter) WriteMaxKey() error { } func (vw *valueWriter) WriteMinKey() error { - if err := vw.writeElementHeader(bsontype.MinKey, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.MinKey, mode(0), "WriteMinKey"); err != nil { return err } @@ -399,7 +404,7 @@ func (vw *valueWriter) WriteMinKey() error { } func (vw *valueWriter) WriteNull() error { - if err := vw.writeElementHeader(bsontype.Null, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Null, mode(0), "WriteNull"); err != nil { return err } @@ -407,8 +412,8 @@ func (vw *valueWriter) WriteNull() error { return nil } -func (vw *valueWriter) WriteObjectID(oid objectid.ObjectID) error { - if err := vw.writeElementHeader(bsontype.ObjectID, mode(0)); err != nil { +func (vw *valueWriter) WriteObjectID(oid primitive.ObjectID) error { + if err := vw.writeElementHeader(bsontype.ObjectID, mode(0), "WriteObjectID"); err != nil { return err } @@ -418,7 +423,7 @@ func (vw *valueWriter) WriteObjectID(oid objectid.ObjectID) error { } func (vw *valueWriter) WriteRegex(pattern string, options string) error { - if err := vw.writeElementHeader(bsontype.Regex, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Regex, mode(0), "WriteRegex"); err != nil { return err } @@ -428,7 +433,7 @@ func (vw *valueWriter) WriteRegex(pattern string, options string) error { } func (vw *valueWriter) WriteString(s string) error { - if err := vw.writeElementHeader(bsontype.String, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.String, mode(0), "WriteString"); err != nil { return err } @@ -442,7 +447,7 @@ func (vw *valueWriter) WriteDocument() (DocumentWriter, error) { vw.reserveLength() return vw, nil } - if err := vw.writeElementHeader(bsontype.EmbeddedDocument, mDocument); err != nil { + if err := vw.writeElementHeader(bsontype.EmbeddedDocument, mDocument, "WriteDocument", mTopLevel); err != nil { return nil, err } @@ -451,7 +456,7 @@ func (vw *valueWriter) WriteDocument() (DocumentWriter, error) { } func (vw *valueWriter) WriteSymbol(symbol string) error { - if err := vw.writeElementHeader(bsontype.Symbol, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Symbol, mode(0), "WriteSymbol"); err != nil { return err } @@ -461,7 +466,7 @@ func (vw *valueWriter) WriteSymbol(symbol string) error { } func (vw *valueWriter) WriteTimestamp(t uint32, i uint32) error { - if err := vw.writeElementHeader(bsontype.Timestamp, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Timestamp, mode(0), "WriteTimestamp"); err != nil { return err } @@ -471,7 +476,7 @@ func (vw *valueWriter) WriteTimestamp(t uint32, i uint32) error { } func (vw *valueWriter) WriteUndefined() error { - if err := vw.writeElementHeader(bsontype.Undefined, mode(0)); err != nil { + if err := vw.writeElementHeader(bsontype.Undefined, mode(0), "WriteUndefined"); err != nil { return err } @@ -483,7 +488,7 @@ func (vw *valueWriter) WriteDocumentElement(key string) (ValueWriter, error) { switch vw.stack[vw.frame].mode { case mTopLevel, mDocument: default: - return nil, vw.invalidTransitionError(mElement) + return nil, vw.invalidTransitionError(mElement, "WriteDocumentElement", []mode{mTopLevel, mDocument}) } vw.push(mElement) @@ -534,7 +539,7 @@ func (vw *valueWriter) WriteDocumentEnd() error { func (vw *valueWriter) WriteArrayElement() (ValueWriter, error) { if vw.stack[vw.frame].mode != mArray { - return nil, vw.invalidTransitionError(mValue) + return nil, vw.invalidTransitionError(mValue, "WriteArrayElement", []mode{mArray}) } arrkey := vw.stack[vw.frame].arrkey diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/writer.go b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/writer.go similarity index 90% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/writer.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsonrw/writer.go index a6b71b0..128b79b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsonrw/writer.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsonrw/writer.go @@ -7,9 +7,8 @@ package bsonrw import ( - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // ArrayWriter is the interface used to create a BSON or BSON adjacent array. @@ -37,9 +36,9 @@ type ValueWriter interface { WriteBinaryWithSubtype(b []byte, btype byte) error WriteBoolean(bool) error WriteCodeWithScope(code string) (DocumentWriter, error) - WriteDBPointer(ns string, oid objectid.ObjectID) error + WriteDBPointer(ns string, oid primitive.ObjectID) error WriteDateTime(dt int64) error - WriteDecimal128(decimal.Decimal128) error + WriteDecimal128(primitive.Decimal128) error WriteDouble(float64) error WriteInt32(int32) error WriteInt64(int64) error @@ -47,7 +46,7 @@ type ValueWriter interface { WriteMaxKey() error WriteMinKey() error WriteNull() error - WriteObjectID(objectid.ObjectID) error + WriteObjectID(primitive.ObjectID) error WriteRegex(pattern, options string) error WriteString(string) error WriteDocument() (DocumentWriter, error) diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/bsontype/bsontype.go b/vendor/go.mongodb.org/mongo-driver/bson/bsontype/bsontype.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/bson/bsontype/bsontype.go rename to vendor/go.mongodb.org/mongo-driver/bson/bsontype/bsontype.go index a17e5f5..e76403a 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/bsontype/bsontype.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/bsontype/bsontype.go @@ -6,7 +6,7 @@ // Package bsontype is a utility package that contains types for each BSON type and the // a stringifier for the Type to enable easier debugging when working with BSON. -package bsontype +package bsontype // import "go.mongodb.org/mongo-driver/bson/bsontype" // These constants uniquely refer to each BSON type. const ( diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/decoder.go b/vendor/go.mongodb.org/mongo-driver/bson/decoder.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/bson/decoder.go rename to vendor/go.mongodb.org/mongo-driver/bson/decoder.go index a3650da..36fb4f8 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/decoder.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/decoder.go @@ -12,8 +12,8 @@ import ( "reflect" "sync" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" ) // This pool is used to keep the allocations of Decoders down. This is only used for the Marshal* @@ -28,21 +28,33 @@ var decPool = sync.Pool{ // A Decoder reads and decodes BSON documents from a stream. It reads from a bsonrw.ValueReader as // the source of BSON data. type Decoder struct { - r *bsoncodec.Registry + dc bsoncodec.DecodeContext vr bsonrw.ValueReader } -// NewDecoder returns a new decoder that uses Registry reg to read from r. -func NewDecoder(r *bsoncodec.Registry, vr bsonrw.ValueReader) (*Decoder, error) { - if r == nil { - return nil, errors.New("cannot create a new Decoder with a nil Registry") +// NewDecoder returns a new decoder that uses the DefaultRegistry to read from vr. +func NewDecoder(vr bsonrw.ValueReader) (*Decoder, error) { + if vr == nil { + return nil, errors.New("cannot create a new Decoder with a nil ValueReader") + } + + return &Decoder{ + dc: bsoncodec.DecodeContext{Registry: DefaultRegistry}, + vr: vr, + }, nil +} + +// NewDecoderWithContext returns a new decoder that uses DecodeContext dc to read from vr. +func NewDecoderWithContext(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader) (*Decoder, error) { + if dc.Registry == nil { + dc.Registry = DefaultRegistry } if vr == nil { return nil, errors.New("cannot create a new Decoder with a nil ValueReader") } return &Decoder{ - r: r, + dc: dc, vr: vr, }, nil } @@ -62,19 +74,20 @@ func (d *Decoder) Decode(val interface{}) error { return unmarshaler.UnmarshalBSON(buf) } - rval := reflect.TypeOf(val) + rval := reflect.ValueOf(val) if rval.Kind() != reflect.Ptr { return fmt.Errorf("argument to Decode must be a pointer to a type, but got %v", rval) } - decoder, err := d.r.LookupDecoder(rval.Elem()) + rval = rval.Elem() + decoder, err := d.dc.LookupDecoder(rval.Type()) if err != nil { return err } - return decoder.DecodeValue(bsoncodec.DecodeContext{Registry: d.r}, d.vr, val) + return decoder.DecodeValue(d.dc, d.vr, rval) } -// Reset will reset the state of the decoder, using the same *Registry used in -// the original construction but using r for reading. +// Reset will reset the state of the decoder, using the same *DecodeContext used in +// the original construction but using vr for reading. func (d *Decoder) Reset(vr bsonrw.ValueReader) error { d.vr = vr return nil @@ -82,6 +95,12 @@ func (d *Decoder) Reset(vr bsonrw.ValueReader) error { // SetRegistry replaces the current registry of the decoder with r. func (d *Decoder) SetRegistry(r *bsoncodec.Registry) error { - d.r = r + d.dc.Registry = r + return nil +} + +// SetContext replaces the current registry of the decoder with dc. +func (d *Decoder) SetContext(dc bsoncodec.DecodeContext) error { + d.dc = dc return nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/doc.go b/vendor/go.mongodb.org/mongo-driver/bson/doc.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/bson/doc.go rename to vendor/go.mongodb.org/mongo-driver/bson/doc.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/encoder.go b/vendor/go.mongodb.org/mongo-driver/bson/encoder.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/bson/encoder.go rename to vendor/go.mongodb.org/mongo-driver/bson/encoder.go index b3a49e8..fe5125d 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/encoder.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/encoder.go @@ -11,8 +11,8 @@ import ( "reflect" "sync" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" ) // This pool is used to keep the allocations of Encoders down. This is only used for the Marshal* @@ -27,21 +27,33 @@ var encPool = sync.Pool{ // An Encoder writes a serialization format to an output stream. It writes to a bsonrw.ValueWriter // as the destination of BSON data. type Encoder struct { - r *bsoncodec.Registry + ec bsoncodec.EncodeContext vw bsonrw.ValueWriter } -// NewEncoder returns a new encoder that uses Registry r to write to w. -func NewEncoder(r *bsoncodec.Registry, vw bsonrw.ValueWriter) (*Encoder, error) { - if r == nil { - return nil, errors.New("cannot create a new Encoder with a nil Registry") +// NewEncoder returns a new encoder that uses the DefaultRegistry to write to vw. +func NewEncoder(vw bsonrw.ValueWriter) (*Encoder, error) { + if vw == nil { + return nil, errors.New("cannot create a new Encoder with a nil ValueWriter") + } + + return &Encoder{ + ec: bsoncodec.EncodeContext{Registry: DefaultRegistry}, + vw: vw, + }, nil +} + +// NewEncoderWithContext returns a new encoder that uses EncodeContext ec to write to vw. +func NewEncoderWithContext(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter) (*Encoder, error) { + if ec.Registry == nil { + ec = bsoncodec.EncodeContext{Registry: DefaultRegistry} } if vw == nil { return nil, errors.New("cannot create a new Encoder with a nil ValueWriter") } return &Encoder{ - r: r, + ec: ec, vw: vw, }, nil } @@ -60,14 +72,14 @@ func (e *Encoder) Encode(val interface{}) error { return bsonrw.Copier{}.CopyDocumentFromBytes(e.vw, buf) } - encoder, err := e.r.LookupEncoder(reflect.TypeOf(val)) + encoder, err := e.ec.LookupEncoder(reflect.TypeOf(val)) if err != nil { return err } - return encoder.EncodeValue(bsoncodec.EncodeContext{Registry: e.r}, e.vw, val) + return encoder.EncodeValue(e.ec, e.vw, reflect.ValueOf(val)) } -// Reset will reset the state of the encoder, using the same *Registry used in +// Reset will reset the state of the encoder, using the same *EncodeContext used in // the original construction but using vw. func (e *Encoder) Reset(vw bsonrw.ValueWriter) error { e.vw = vw @@ -76,6 +88,12 @@ func (e *Encoder) Reset(vw bsonrw.ValueWriter) error { // SetRegistry replaces the current registry of the encoder with r. func (e *Encoder) SetRegistry(r *bsoncodec.Registry) error { - e.r = r + e.ec.Registry = r + return nil +} + +// SetContext replaces the current EncodeContext of the encoder with er. +func (e *Encoder) SetContext(ec bsoncodec.EncodeContext) error { + e.ec = ec return nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/marshal.go b/vendor/go.mongodb.org/mongo-driver/bson/marshal.go similarity index 70% rename from vendor/github.com/mongodb/mongo-go-driver/bson/marshal.go rename to vendor/go.mongodb.org/mongo-driver/bson/marshal.go index fba1d0c..9a4e28d 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/marshal.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/marshal.go @@ -7,9 +7,9 @@ package bson import ( - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" ) const defaultDstCap = 256 @@ -53,10 +53,23 @@ func MarshalWithRegistry(r *bsoncodec.Registry, val interface{}) ([]byte, error) return MarshalAppendWithRegistry(r, dst, val) } +// MarshalWithContext returns the BSON encoding of val using EncodeContext ec. +func MarshalWithContext(ec bsoncodec.EncodeContext, val interface{}) ([]byte, error) { + dst := make([]byte, 0, 256) // TODO: make the default cap a constant + return MarshalAppendWithContext(ec, dst, val) +} + // MarshalAppendWithRegistry will append the BSON encoding of val to dst using // Registry r. If dst is not large enough to hold the BSON encoding of val, dst // will be grown. func MarshalAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}) ([]byte, error) { + return MarshalAppendWithContext(bsoncodec.EncodeContext{Registry: r}, dst, val) +} + +// MarshalAppendWithContext will append the BSON encoding of val to dst using +// EncodeContext ec. If dst is not large enough to hold the BSON encoding of val, dst +// will be grown. +func MarshalAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}) ([]byte, error) { sw := new(bsonrw.SliceWriter) *sw = dst vw := bvwPool.Get(sw) @@ -69,7 +82,7 @@ func MarshalAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{ if err != nil { return nil, err } - err = enc.SetRegistry(r) + err = enc.SetContext(ec) if err != nil { return nil, err } @@ -97,13 +110,26 @@ func MarshalExtJSONAppend(dst []byte, val interface{}, canonical, escapeHTML boo // MarshalExtJSONWithRegistry returns the extended JSON encoding of val using Registry r. func MarshalExtJSONWithRegistry(r *bsoncodec.Registry, val interface{}, canonical, escapeHTML bool) ([]byte, error) { dst := make([]byte, 0, defaultDstCap) - return MarshalExtJSONAppendWithRegistry(r, dst, val, canonical, escapeHTML) + return MarshalExtJSONAppendWithContext(bsoncodec.EncodeContext{Registry: r}, dst, val, canonical, escapeHTML) +} + +// MarshalExtJSONWithContext returns the extended JSON encoding of val using Registry r. +func MarshalExtJSONWithContext(ec bsoncodec.EncodeContext, val interface{}, canonical, escapeHTML bool) ([]byte, error) { + dst := make([]byte, 0, defaultDstCap) + return MarshalExtJSONAppendWithContext(ec, dst, val, canonical, escapeHTML) } // MarshalExtJSONAppendWithRegistry will append the extended JSON encoding of // val to dst using Registry r. If dst is not large enough to hold the BSON // encoding of val, dst will be grown. func MarshalExtJSONAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val interface{}, canonical, escapeHTML bool) ([]byte, error) { + return MarshalExtJSONAppendWithContext(bsoncodec.EncodeContext{Registry: r}, dst, val, canonical, escapeHTML) +} + +// MarshalExtJSONAppendWithContext will append the extended JSON encoding of +// val to dst using Registry r. If dst is not large enough to hold the BSON +// encoding of val, dst will be grown. +func MarshalExtJSONAppendWithContext(ec bsoncodec.EncodeContext, dst []byte, val interface{}, canonical, escapeHTML bool) ([]byte, error) { sw := new(bsonrw.SliceWriter) *sw = dst ejvw := extjPool.Get(sw, canonical, escapeHTML) @@ -116,7 +142,7 @@ func MarshalExtJSONAppendWithRegistry(r *bsoncodec.Registry, dst []byte, val int if err != nil { return nil, err } - err = enc.SetRegistry(r) + err = enc.SetContext(ec) if err != nil { return nil, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/decimal/decimal.go b/vendor/go.mongodb.org/mongo-driver/bson/primitive/decimal.go similarity index 99% rename from vendor/github.com/mongodb/mongo-go-driver/bson/decimal/decimal.go rename to vendor/go.mongodb.org/mongo-driver/bson/primitive/decimal.go index 6dbb7a3..d7fdb22 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/decimal/decimal.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/primitive/decimal.go @@ -7,8 +7,7 @@ // Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer // See THIRD-PARTY-NOTICES for original license terms. -// Package decimal implements a Decimal128 type. -package decimal +package primitive import ( "fmt" diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/objectid/objectid.go b/vendor/go.mongodb.org/mongo-driver/bson/primitive/objectid.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/bson/objectid/objectid.go rename to vendor/go.mongodb.org/mongo-driver/bson/primitive/objectid.go index 4080ae0..9eaaa06 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/objectid/objectid.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/primitive/objectid.go @@ -7,9 +7,7 @@ // Based on gopkg.in/mgo.v2/bson by Gustavo Niemeyer // See THIRD-PARTY-NOTICES for original license terms. -// Package objectid contains an implementation of a BSON objectID type functions to create -// objectIDs. -package objectid +package primitive import ( "bytes" @@ -36,8 +34,8 @@ var NilObjectID ObjectID var objectIDCounter = readRandomUint32() var processUnique = processUniqueBytes() -// New generates a new ObjectID. -func New() ObjectID { +// NewObjectID generates a new ObjectID. +func NewObjectID() ObjectID { var b [12]byte binary.BigEndian.PutUint32(b[0:4], uint32(time.Now().Unix())) @@ -61,9 +59,9 @@ func (id ObjectID) IsZero() bool { return bytes.Equal(id[:], NilObjectID[:]) } -// FromHex creates a new ObjectID from a hex string. It returns an error if the hex string is not a +// ObjectIDFromHex creates a new ObjectID from a hex string. It returns an error if the hex string is not a // valid ObjectID. -func FromHex(s string) (ObjectID, error) { +func ObjectIDFromHex(s string) (ObjectID, error) { b, err := hex.DecodeString(s) if err != nil { return NilObjectID, err diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/primitive/primitive.go b/vendor/go.mongodb.org/mongo-driver/bson/primitive/primitive.go similarity index 55% rename from vendor/github.com/mongodb/mongo-go-driver/bson/primitive/primitive.go rename to vendor/go.mongodb.org/mongo-driver/bson/primitive/primitive.go index a1156f5..010f882 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/primitive/primitive.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/primitive/primitive.go @@ -6,13 +6,13 @@ // Package primitive contains types similar to Go primitives for BSON types can do not have direct // Go primitive representations. -package primitive +package primitive // import "go.mongodb.org/mongo-driver/bson/primitive" import ( "bytes" + "encoding/json" "fmt" - - "github.com/mongodb/mongo-go-driver/bson/objectid" + "time" ) // Binary represents a BSON binary value. @@ -35,6 +35,11 @@ type Undefined struct{} // DateTime represents the BSON datetime value. type DateTime int64 +// MarshalJSON marshal to time type +func (d DateTime) MarshalJSON() ([]byte, error) { + return json.Marshal(time.Unix(int64(d)/1000, int64(d)%1000*1000000)) +} + // Null repreesnts the BSON null value. type Null struct{} @@ -56,7 +61,7 @@ func (rp Regex) Equal(rp2 Regex) bool { // DBPointer represents a BSON dbpointer value. type DBPointer struct { DB string - Pointer objectid.ObjectID + Pointer ObjectID } func (d DBPointer) String() string { @@ -100,3 +105,52 @@ type MinKey struct{} // MaxKey represents the BSON maxkey value. type MaxKey struct{} + +// D represents a BSON Document. This type can be used to represent BSON in a concise and readable +// manner. It should generally be used when serializing to BSON. For deserializing, the Raw or +// Document types should be used. +// +// Example usage: +// +// primitive.D{{"foo", "bar"}, {"hello", "world"}, {"pi", 3.14159}} +// +// This type should be used in situations where order matters, such as MongoDB commands. If the +// order is not important, a map is more comfortable and concise. +type D []E + +// Map creates a map from the elements of the D. +func (d D) Map() M { + m := make(M, len(d)) + for _, e := range d { + m[e.Key] = e.Value + } + return m +} + +// E represents a BSON element for a D. It is usually used inside a D. +type E struct { + Key string + Value interface{} +} + +// M is an unordered, concise representation of a BSON Document. It should generally be used to +// serialize BSON when the order of the elements of a BSON document do not matter. If the element +// order matters, use a D instead. +// +// Example usage: +// +// primitive.M{"foo": "bar", "hello": "world", "pi": 3.14159} +// +// This type is handled in the encoders as a regular map[string]interface{}. The elements will be +// serialized in an undefined, random order, and the order will be different each time. +type M map[string]interface{} + +// An A represents a BSON array. This type can be used to represent a BSON array in a concise and +// readable manner. It should generally be used when serializing to BSON. For deserializing, the +// RawArray or Array types should be used. +// +// Example usage: +// +// primitive.A{"bar", "world", 3.14159, primitive.D{{"qux", 12345}}} +// +type A []interface{} diff --git a/vendor/go.mongodb.org/mongo-driver/bson/primitive_codecs.go b/vendor/go.mongodb.org/mongo-driver/bson/primitive_codecs.go new file mode 100644 index 0000000..1dae2fc --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/bson/primitive_codecs.go @@ -0,0 +1,111 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package bson + +import ( + "errors" + "reflect" + + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" +) + +var primitiveCodecs PrimitiveCodecs + +// PrimitiveCodecs is a namespace for all of the default bsoncodec.Codecs for the primitive types +// defined in this package. +type PrimitiveCodecs struct{} + +// RegisterPrimitiveCodecs will register the encode and decode methods attached to PrimitiveCodecs +// with the provided RegistryBuilder. if rb is nil, a new empty RegistryBuilder will be created. +func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder) { + if rb == nil { + panic(errors.New("argument to RegisterPrimitiveCodecs must not be nil")) + } + + rb. + RegisterEncoder(tRawValue, bsoncodec.ValueEncoderFunc(pc.RawValueEncodeValue)). + RegisterEncoder(tRaw, bsoncodec.ValueEncoderFunc(pc.RawEncodeValue)). + RegisterDecoder(tRawValue, bsoncodec.ValueDecoderFunc(pc.RawValueDecodeValue)). + RegisterDecoder(tRaw, bsoncodec.ValueDecoderFunc(pc.RawDecodeValue)) +} + +// RawValueEncodeValue is the ValueEncoderFunc for RawValue. +func (PrimitiveCodecs) RawValueEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tRawValue { + return bsoncodec.ValueEncoderError{Name: "RawValueEncodeValue", Types: []reflect.Type{tRawValue}, Received: val} + } + + rawvalue := val.Interface().(RawValue) + + return bsonrw.Copier{}.CopyValueFromBytes(vw, rawvalue.Type, rawvalue.Value) +} + +// RawValueDecodeValue is the ValueDecoderFunc for RawValue. +func (PrimitiveCodecs) RawValueDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tRawValue { + return bsoncodec.ValueDecoderError{Name: "RawValueDecodeValue", Types: []reflect.Type{tRawValue}, Received: val} + } + + t, value, err := bsonrw.Copier{}.CopyValueToBytes(vr) + if err != nil { + return err + } + + val.Set(reflect.ValueOf(RawValue{Type: t, Value: value})) + return nil +} + +// RawEncodeValue is the ValueEncoderFunc for Reader. +func (PrimitiveCodecs) RawEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tRaw { + return bsoncodec.ValueEncoderError{Name: "RawEncodeValue", Types: []reflect.Type{tRaw}, Received: val} + } + + rdr := val.Interface().(Raw) + + return bsonrw.Copier{}.CopyDocumentFromBytes(vw, rdr) +} + +// RawDecodeValue is the ValueDecoderFunc for Reader. +func (PrimitiveCodecs) RawDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tRaw { + return bsoncodec.ValueDecoderError{Name: "RawDecodeValue", Types: []reflect.Type{tRaw}, Received: val} + } + + if val.IsNil() { + val.Set(reflect.MakeSlice(val.Type(), 0, 0)) + } + + val.SetLen(0) + + rdr, err := bsonrw.Copier{}.AppendDocumentBytes(val.Interface().(Raw), vr) + val.Set(reflect.ValueOf(rdr)) + return err +} + +func (pc PrimitiveCodecs) encodeRaw(ec bsoncodec.EncodeContext, dw bsonrw.DocumentWriter, raw Raw) error { + var copier bsonrw.Copier + elems, err := raw.Elements() + if err != nil { + return err + } + for _, elem := range elems { + dvw, err := dw.WriteDocumentElement(elem.Key()) + if err != nil { + return err + } + + val := elem.Value() + err = copier.CopyValueFromBytes(dvw, val.Type, val.Value) + if err != nil { + return err + } + } + + return dw.WriteDocumentEnd() +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/raw.go b/vendor/go.mongodb.org/mongo-driver/bson/raw.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/bson/raw.go rename to vendor/go.mongodb.org/mongo-driver/bson/raw.go index 0bf5bc3..2aae9f5 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/raw.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/raw.go @@ -10,7 +10,7 @@ import ( "errors" "io" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // ErrNilReader indicates that an operation was attempted on a nil bson.Reader. @@ -35,8 +35,8 @@ func (r Raw) Validate() (err error) { return bsoncore.Document(r).Validate() } // Lookup search the document, potentially recursively, for the given key. If // there are multiple keys provided, this method will recurse down, as long as -// the top and intermediate nodes are either documents or arrays. If any key -// except for the last is not a document or an array, an error will be returned. +// the top and intermediate nodes are either documents or arrays.If an error +// occurs or if the value doesn't exist, an empty RawValue is returned. func (r Raw) Lookup(key ...string) RawValue { return convertFromCoreValue(bsoncore.Document(r).Lookup(key...)) } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/raw_element.go b/vendor/go.mongodb.org/mongo-driver/bson/raw_element.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/bson/raw_element.go rename to vendor/go.mongodb.org/mongo-driver/bson/raw_element.go index 2a01390..006f503 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/raw_element.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/raw_element.go @@ -7,7 +7,7 @@ package bson import ( - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // RawElement represents a BSON element in byte form. This type provides a simple way to diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/raw_value.go b/vendor/go.mongodb.org/mongo-driver/bson/raw_value.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/bson/raw_value.go rename to vendor/go.mongodb.org/mongo-driver/bson/raw_value.go index ec4003a..d59afcf 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/raw_value.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/raw_value.go @@ -9,17 +9,20 @@ package bson import ( "bytes" "errors" + "fmt" "reflect" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) +// ErrNilContext is returned when the provided DecodeContext is nil. +var ErrNilContext = errors.New("DecodeContext cannot be nil") + // ErrNilRegistry is returned when the provided registry is nil. var ErrNilRegistry = errors.New("Registry cannot be nil") @@ -68,11 +71,36 @@ func (rv RawValue) UnmarshalWithRegistry(r *bsoncodec.Registry, val interface{}) } vr := bsonrw.NewBSONValueReader(rv.Type, rv.Value) - dec, err := r.LookupDecoder(reflect.TypeOf(val)) + rval := reflect.ValueOf(val) + if rval.Kind() != reflect.Ptr { + return fmt.Errorf("argument to Unmarshal* must be a pointer to a type, but got %v", rval) + } + rval = rval.Elem() + dec, err := r.LookupDecoder(rval.Type()) + if err != nil { + return err + } + return dec.DecodeValue(bsoncodec.DecodeContext{Registry: r}, vr, rval) +} + +// UnmarshalWithContext performs the same unmarshalling as Unmarshal but uses the provided DecodeContext +// instead of the one attached or the default registry. +func (rv RawValue) UnmarshalWithContext(dc *bsoncodec.DecodeContext, val interface{}) error { + if dc == nil { + return ErrNilContext + } + + vr := bsonrw.NewBSONValueReader(rv.Type, rv.Value) + rval := reflect.ValueOf(val) + if rval.Kind() != reflect.Ptr { + return fmt.Errorf("argument to Unmarshal* must be a pointer to a type, but got %v", rval) + } + rval = rval.Elem() + dec, err := dc.LookupDecoder(rval.Type()) if err != nil { return err } - return dec.DecodeValue(bsoncodec.DecodeContext{Registry: r}, vr, val) + return dec.DecodeValue(*dc, vr, rval) } func convertFromCoreValue(v bsoncore.Value) RawValue { return RawValue{Type: v.Type, Value: v.Data} } @@ -99,7 +127,7 @@ func (rv RawValue) Double() float64 { return convertToCoreValue(rv).Double() } // DoubleOK is the same as Double, but returns a boolean instead of panicking. func (rv RawValue) DoubleOK() (float64, bool) { return convertToCoreValue(rv).DoubleOK() } -// StringValue returns the string balue for this element. +// StringValue returns the string value for this element. // It panics if e's BSON type is not bsontype.String. // // NOTE: This method is called StringValue to avoid a collision with the String method which @@ -144,11 +172,11 @@ func (rv RawValue) BinaryOK() (subtype byte, data []byte, ok bool) { // ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON // type other than objectid. -func (rv RawValue) ObjectID() objectid.ObjectID { return convertToCoreValue(rv).ObjectID() } +func (rv RawValue) ObjectID() primitive.ObjectID { return convertToCoreValue(rv).ObjectID() } // ObjectIDOK is the same as ObjectID, except it returns a boolean instead of // panicking. -func (rv RawValue) ObjectIDOK() (objectid.ObjectID, bool) { return convertToCoreValue(rv).ObjectIDOK() } +func (rv RawValue) ObjectIDOK() (primitive.ObjectID, bool) { return convertToCoreValue(rv).ObjectIDOK() } // Boolean returns the boolean value the Value represents. It panics if the // value is a BSON type other than boolean. @@ -186,11 +214,11 @@ func (rv RawValue) RegexOK() (pattern, options string, ok bool) { // DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON // type other than DBPointer. -func (rv RawValue) DBPointer() (string, objectid.ObjectID) { return convertToCoreValue(rv).DBPointer() } +func (rv RawValue) DBPointer() (string, primitive.ObjectID) { return convertToCoreValue(rv).DBPointer() } // DBPointerOK is the same as DBPoitner, except that it returns a boolean // instead of panicking. -func (rv RawValue) DBPointerOK() (string, objectid.ObjectID, bool) { +func (rv RawValue) DBPointerOK() (string, primitive.ObjectID, bool) { return convertToCoreValue(rv).DBPointerOK() } @@ -250,10 +278,10 @@ func (rv RawValue) Int64OK() (int64, bool) { return convertToCoreValue(rv).Int64 // Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than // decimal. -func (rv RawValue) Decimal128() decimal.Decimal128 { return convertToCoreValue(rv).Decimal128() } +func (rv RawValue) Decimal128() primitive.Decimal128 { return convertToCoreValue(rv).Decimal128() } // Decimal128OK is the same as Decimal128, except that it returns a boolean // instead of panicking. -func (rv RawValue) Decimal128OK() (decimal.Decimal128, bool) { +func (rv RawValue) Decimal128OK() (primitive.Decimal128, bool) { return convertToCoreValue(rv).Decimal128OK() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/registry.go b/vendor/go.mongodb.org/mongo-driver/bson/registry.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/bson/registry.go rename to vendor/go.mongodb.org/mongo-driver/bson/registry.go index c9ef029..09062d2 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/registry.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/registry.go @@ -6,7 +6,7 @@ package bson -import "github.com/mongodb/mongo-go-driver/bson/bsoncodec" +import "go.mongodb.org/mongo-driver/bson/bsoncodec" // DefaultRegistry is the default bsoncodec.Registry. It contains the default codecs and the // primitive codecs. diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/types.go b/vendor/go.mongodb.org/mongo-driver/bson/types.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/bson/types.go rename to vendor/go.mongodb.org/mongo-driver/bson/types.go index dec934c..bf91f69 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/types.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/types.go @@ -10,11 +10,8 @@ import ( "reflect" "time" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/bson/primitive" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // These constants uniquely refer to each BSON type. @@ -46,16 +43,12 @@ var tBinary = reflect.TypeOf(primitive.Binary{}) var tBool = reflect.TypeOf(false) var tCodeWithScope = reflect.TypeOf(primitive.CodeWithScope{}) var tDBPointer = reflect.TypeOf(primitive.DBPointer{}) -var tDecimal = reflect.TypeOf(decimal.Decimal128{}) -var tDocument = reflect.TypeOf((bsonx.Doc)(nil)) -var tMDoc = reflect.TypeOf((bsonx.MDoc)(nil)) +var tDecimal = reflect.TypeOf(primitive.Decimal128{}) var tD = reflect.TypeOf(D{}) -var tElementSlice = reflect.TypeOf(([]bsonx.Elem)(nil)) +var tA = reflect.TypeOf(A{}) var tDateTime = reflect.TypeOf(primitive.DateTime(0)) var tUndefined = reflect.TypeOf(primitive.Undefined{}) var tNull = reflect.TypeOf(primitive.Null{}) -var tArray = reflect.TypeOf((bsonx.Arr)(nil)) -var tValue = reflect.TypeOf(bsonx.Val{}) var tRawValue = reflect.TypeOf(RawValue{}) var tFloat32 = reflect.TypeOf(float32(0)) var tFloat64 = reflect.TypeOf(float64(0)) @@ -65,7 +58,7 @@ var tInt16 = reflect.TypeOf(int16(0)) var tInt32 = reflect.TypeOf(int32(0)) var tInt64 = reflect.TypeOf(int64(0)) var tJavaScript = reflect.TypeOf(primitive.JavaScript("")) -var tOID = reflect.TypeOf(objectid.ObjectID{}) +var tOID = reflect.TypeOf(primitive.ObjectID{}) var tRaw = reflect.TypeOf(Raw(nil)) var tRegex = reflect.TypeOf(primitive.Regex{}) var tString = reflect.TypeOf("") diff --git a/vendor/github.com/mongodb/mongo-go-driver/bson/unmarshal.go b/vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/bson/unmarshal.go rename to vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go index 780b531..6f9ca04 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/bson/unmarshal.go +++ b/vendor/go.mongodb.org/mongo-driver/bson/unmarshal.go @@ -9,9 +9,9 @@ package bson import ( "bytes" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" ) // Unmarshaler is an interface implemented by types that can unmarshal a BSON @@ -42,7 +42,15 @@ func Unmarshal(data []byte, val interface{}) error { // a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError. func UnmarshalWithRegistry(r *bsoncodec.Registry, data []byte, val interface{}) error { vr := bsonrw.NewBSONDocumentReader(data) - return unmarshalFromReader(r, vr, val) + return unmarshalFromReader(bsoncodec.DecodeContext{Registry: r}, vr, val) +} + +// UnmarshalWithContext parses the BSON-encoded data using DecodeContext dc and +// stores the result in the value pointed to by val. If val is nil or not +// a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError. +func UnmarshalWithContext(dc bsoncodec.DecodeContext, data []byte, val interface{}) error { + vr := bsonrw.NewBSONDocumentReader(data) + return unmarshalFromReader(dc, vr, val) } // UnmarshalExtJSON parses the extended JSON-encoded data and stores the result @@ -56,11 +64,27 @@ func UnmarshalExtJSON(data []byte, canonical bool, val interface{}) error { // Registry r and stores the result in the value pointed to by val. If val is // nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError. func UnmarshalExtJSONWithRegistry(r *bsoncodec.Registry, data []byte, canonical bool, val interface{}) error { - ejvr := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), canonical) - return unmarshalFromReader(r, ejvr, val) + ejvr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), canonical) + if err != nil { + return err + } + + return unmarshalFromReader(bsoncodec.DecodeContext{Registry: r}, ejvr, val) +} + +// UnmarshalExtJSONWithContext parses the extended JSON-encoded data using +// DecodeContext dc and stores the result in the value pointed to by val. If val is +// nil or not a pointer, UnmarshalWithRegistry returns InvalidUnmarshalError. +func UnmarshalExtJSONWithContext(dc bsoncodec.DecodeContext, data []byte, canonical bool, val interface{}) error { + ejvr, err := bsonrw.NewExtJSONValueReader(bytes.NewReader(data), canonical) + if err != nil { + return err + } + + return unmarshalFromReader(dc, ejvr, val) } -func unmarshalFromReader(r *bsoncodec.Registry, vr bsonrw.ValueReader, val interface{}) error { +func unmarshalFromReader(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val interface{}) error { dec := decPool.Get().(*Decoder) defer decPool.Put(dec) @@ -68,7 +92,7 @@ func unmarshalFromReader(r *bsoncodec.Registry, vr bsonrw.ValueReader, val inter if err != nil { return err } - err = dec.SetRegistry(r) + err = dec.SetContext(dc) if err != nil { return err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/etc/generate-notices.pl b/vendor/go.mongodb.org/mongo-driver/etc/generate-notices.pl similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/etc/generate-notices.pl rename to vendor/go.mongodb.org/mongo-driver/etc/generate-notices.pl diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/event/monitoring.go b/vendor/go.mongodb.org/mongo-driver/event/monitoring.go similarity index 66% rename from vendor/github.com/mongodb/mongo-go-driver/core/event/monitoring.go rename to vendor/go.mongodb.org/mongo-driver/event/monitoring.go index 0d8edad..f6062ed 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/event/monitoring.go +++ b/vendor/go.mongodb.org/mongo-driver/event/monitoring.go @@ -4,39 +4,17 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package event +package event // import "go.mongodb.org/mongo-driver/event" import ( "context" - "time" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" ) -// CommandMetadata contains metadata about a command sent to the server. -type CommandMetadata struct { - Name string - Time time.Time -} - -// CreateMetadata creates metadata for a command. -func CreateMetadata(name string) *CommandMetadata { - return &CommandMetadata{ - Name: name, - Time: time.Now(), - } -} - -// TimeDifference returns the difference between now and the time a command was sent in nanoseconds. -func (cm *CommandMetadata) TimeDifference() int64 { - t := time.Now() - duration := t.Sub(cm.Time) - return duration.Nanoseconds() -} - // CommandStartedEvent represents an event generated when a command is sent to a server. type CommandStartedEvent struct { - Command bsonx.Doc + Command bson.Raw DatabaseName string CommandName string RequestID int64 @@ -54,7 +32,7 @@ type CommandFinishedEvent struct { // CommandSucceededEvent represents an event generated when a command's execution succeeds. type CommandSucceededEvent struct { CommandFinishedEvent - Reply bsonx.Doc + Reply bson.Raw } // CommandFailedEvent represents an event generated when a command's execution fails. diff --git a/vendor/github.com/mongodb/mongo-go-driver/internal/channel_connection.go b/vendor/go.mongodb.org/mongo-driver/internal/channel_connection.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/internal/channel_connection.go rename to vendor/go.mongodb.org/mongo-driver/internal/channel_connection.go index f179445..7e8b9f7 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/internal/channel_connection.go +++ b/vendor/go.mongodb.org/mongo-driver/internal/channel_connection.go @@ -8,17 +8,17 @@ package internal import ( "context" - "testing" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/wiremessage" + "errors" + "fmt" ) // Implements the connection.Connection interface by reading and writing wire messages // to a channel type ChannelConn struct { - T *testing.T WriteErr error Written chan wiremessage.WireMessage ReadResp chan wiremessage.WireMessage @@ -29,7 +29,7 @@ func (c *ChannelConn) WriteWireMessage(ctx context.Context, wm wiremessage.WireM select { case c.Written <- wm: default: - c.T.Error("could not write wiremessage to written channel") + c.WriteErr = errors.New("could not write wiremessage to written channel") } return c.WriteErr } @@ -62,13 +62,13 @@ func (c *ChannelConn) ID() string { } // Create a OP_REPLY wiremessage from a BSON document -func MakeReply(t *testing.T, doc bsonx.Doc) wiremessage.WireMessage { +func MakeReply(doc bsonx.Doc) (wiremessage.WireMessage, error) { rdr, err := doc.MarshalBSON() if err != nil { - t.Fatalf("Could not create document: %v", err) + return nil, errors.New(fmt.Sprintf("could not create document: %v", err)) } return wiremessage.Reply{ NumberReturned: 1, Documents: []bson.Raw{rdr}, - } + }, nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/internal/const.go b/vendor/go.mongodb.org/mongo-driver/internal/const.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/internal/const.go rename to vendor/go.mongodb.org/mongo-driver/internal/const.go index 7100e31..11354c4 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/internal/const.go +++ b/vendor/go.mongodb.org/mongo-driver/internal/const.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package internal +package internal // import "go.mongodb.org/mongo-driver/internal" // Version is the current version of the driver. var Version = "local build" diff --git a/vendor/github.com/mongodb/mongo-go-driver/internal/error.go b/vendor/go.mongodb.org/mongo-driver/internal/error.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/internal/error.go rename to vendor/go.mongodb.org/mongo-driver/internal/error.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/internal/results.go b/vendor/go.mongodb.org/mongo-driver/internal/results.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/internal/results.go rename to vendor/go.mongodb.org/mongo-driver/internal/results.go index 6688ebf..0456899 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/internal/results.go +++ b/vendor/go.mongodb.org/mongo-driver/internal/results.go @@ -8,8 +8,7 @@ package internal import ( "time" - - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/primitive" ) // IsMasterResult is the result of executing this @@ -17,7 +16,7 @@ import ( type IsMasterResult struct { Arbiters []string `bson:"arbiters,omitempty"` ArbiterOnly bool `bson:"arbiterOnly,omitempty"` - ElectionID objectid.ObjectID `bson:"electionId,omitempty"` + ElectionID primitive.ObjectID `bson:"electionId,omitempty"` Hidden bool `bson:"hidden,omitempty"` Hosts []string `bson:"hosts,omitempty"` IsMaster bool `bson:"ismaster,omitempty"` diff --git a/vendor/github.com/mongodb/mongo-go-driver/internal/semaphore.go b/vendor/go.mongodb.org/mongo-driver/internal/semaphore.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/internal/semaphore.go rename to vendor/go.mongodb.org/mongo-driver/internal/semaphore.go diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/mongo/batch_cursor.go new file mode 100644 index 0000000..61b4589 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/batch_cursor.go @@ -0,0 +1,31 @@ +package mongo + +import ( + "context" + + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" +) + +// batchCursor is the interface implemented by types that can provide batches of document results. +// The Cursor type is built on top of this type. +type batchCursor interface { + // ID returns the ID of the cursor. + ID() int64 + + // Next returns true if there is a batch available. + Next(context.Context) bool + + // Batch will return a DocumentSequence for the current batch of documents. The returned + // DocumentSequence is only valid until the next call to Next or Close. + Batch() *bsoncore.DocumentSequence + + // Server returns a pointer to the cursor's server. + Server() *topology.Server + + // Err returns the last error encountered. + Err() error + + // Close closes the cursor. + Close(context.Context) error +} diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/bulk_write.go b/vendor/go.mongodb.org/mongo-driver/mongo/bulk_write.go new file mode 100644 index 0000000..1c856b7 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/bulk_write.go @@ -0,0 +1,341 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package mongo + +import ( + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/mongo/driver" +) + +// WriteModel is the interface satisfied by all models for bulk writes. +type WriteModel interface { + convertModel() driver.WriteModel +} + +// InsertOneModel is the write model for insert operations. +type InsertOneModel struct { + Document interface{} +} + +// NewInsertOneModel creates a new InsertOneModel. +func NewInsertOneModel() *InsertOneModel { + return &InsertOneModel{} +} + +// SetDocument sets the BSON document for the InsertOneModel. +func (iom *InsertOneModel) SetDocument(doc interface{}) *InsertOneModel { + iom.Document = doc + return iom +} + +func (iom *InsertOneModel) convertModel() driver.WriteModel { + return driver.InsertOneModel{ + Document: iom.Document, + } +} + +// DeleteOneModel is the write model for delete operations. +type DeleteOneModel struct { + Filter interface{} + Collation *options.Collation +} + +// NewDeleteOneModel creates a new DeleteOneModel. +func NewDeleteOneModel() *DeleteOneModel { + return &DeleteOneModel{} +} + +// SetFilter sets the filter for the DeleteOneModel. +func (dom *DeleteOneModel) SetFilter(filter interface{}) *DeleteOneModel { + dom.Filter = filter + return dom +} + +// SetCollation sets the collation for the DeleteOneModel. +func (dom *DeleteOneModel) SetCollation(collation *options.Collation) *DeleteOneModel { + dom.Collation = collation + return dom +} + +func (dom *DeleteOneModel) convertModel() driver.WriteModel { + return driver.DeleteOneModel{ + Collation: dom.Collation, + Filter: dom.Filter, + } +} + +// DeleteManyModel is the write model for deleteMany operations. +type DeleteManyModel struct { + Filter interface{} + Collation *options.Collation +} + +// NewDeleteManyModel creates a new DeleteManyModel. +func NewDeleteManyModel() *DeleteManyModel { + return &DeleteManyModel{} +} + +// SetFilter sets the filter for the DeleteManyModel. +func (dmm *DeleteManyModel) SetFilter(filter interface{}) *DeleteManyModel { + dmm.Filter = filter + return dmm +} + +// SetCollation sets the collation for the DeleteManyModel. +func (dmm *DeleteManyModel) SetCollation(collation *options.Collation) *DeleteManyModel { + dmm.Collation = collation + return dmm +} + +func (dmm *DeleteManyModel) convertModel() driver.WriteModel { + return driver.DeleteManyModel{ + Collation: dmm.Collation, + Filter: dmm.Filter, + } +} + +// ReplaceOneModel is the write model for replace operations. +type ReplaceOneModel struct { + Collation *options.Collation + Upsert *bool + Filter interface{} + Replacement interface{} +} + +// NewReplaceOneModel creates a new ReplaceOneModel. +func NewReplaceOneModel() *ReplaceOneModel { + return &ReplaceOneModel{} +} + +// SetFilter sets the filter for the ReplaceOneModel. +func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel { + rom.Filter = filter + return rom +} + +// SetReplacement sets the replacement document for the ReplaceOneModel. +func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel { + rom.Replacement = rep + return rom +} + +// SetCollation sets the collation for the ReplaceOneModel. +func (rom *ReplaceOneModel) SetCollation(collation *options.Collation) *ReplaceOneModel { + rom.Collation = collation + return rom +} + +// SetUpsert specifies if a new document should be created if no document matches the query. +func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel { + rom.Upsert = &upsert + return rom +} + +func (rom *ReplaceOneModel) convertModel() driver.WriteModel { + um := driver.UpdateModel{ + Collation: rom.Collation, + } + if rom.Upsert != nil { + um.Upsert = *rom.Upsert + um.UpsertSet = true + } + + return driver.ReplaceOneModel{ + UpdateModel: um, + Filter: rom.Filter, + Replacement: rom.Replacement, + } +} + +// UpdateOneModel is the write model for update operations. +type UpdateOneModel struct { + Collation *options.Collation + Upsert *bool + Filter interface{} + Update interface{} + ArrayFilters *options.ArrayFilters +} + +// NewUpdateOneModel creates a new UpdateOneModel. +func NewUpdateOneModel() *UpdateOneModel { + return &UpdateOneModel{} +} + +// SetFilter sets the filter for the UpdateOneModel. +func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel { + uom.Filter = filter + return uom +} + +// SetUpdate sets the update document for the UpdateOneModel. +func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel { + uom.Update = update + return uom +} + +// SetArrayFilters specifies a set of filters specifying to which array elements an update should apply. +func (uom *UpdateOneModel) SetArrayFilters(filters options.ArrayFilters) *UpdateOneModel { + uom.ArrayFilters = &filters + return uom +} + +// SetCollation sets the collation for the UpdateOneModel. +func (uom *UpdateOneModel) SetCollation(collation *options.Collation) *UpdateOneModel { + uom.Collation = collation + return uom +} + +// SetUpsert specifies if a new document should be created if no document matches the query. +func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel { + uom.Upsert = &upsert + return uom +} + +func (uom *UpdateOneModel) convertModel() driver.WriteModel { + um := driver.UpdateModel{ + Collation: uom.Collation, + } + if uom.Upsert != nil { + um.Upsert = *uom.Upsert + um.UpsertSet = true + } + + converted := driver.UpdateOneModel{ + UpdateModel: um, + Filter: uom.Filter, + Update: uom.Update, + } + if uom.ArrayFilters != nil { + converted.ArrayFilters = *uom.ArrayFilters + converted.ArrayFiltersSet = true + } + + return converted +} + +// UpdateManyModel is the write model for updateMany operations. +type UpdateManyModel struct { + Collation *options.Collation + Upsert *bool + Filter interface{} + Update interface{} + ArrayFilters *options.ArrayFilters +} + +// NewUpdateManyModel creates a new UpdateManyModel. +func NewUpdateManyModel() *UpdateManyModel { + return &UpdateManyModel{} +} + +// SetFilter sets the filter for the UpdateManyModel. +func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel { + umm.Filter = filter + return umm +} + +// SetUpdate sets the update document for the UpdateManyModel. +func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel { + umm.Update = update + return umm +} + +// SetArrayFilters specifies a set of filters specifying to which array elements an update should apply. +func (umm *UpdateManyModel) SetArrayFilters(filters options.ArrayFilters) *UpdateManyModel { + umm.ArrayFilters = &filters + return umm +} + +// SetCollation sets the collation for the UpdateManyModel. +func (umm *UpdateManyModel) SetCollation(collation *options.Collation) *UpdateManyModel { + umm.Collation = collation + return umm +} + +// SetUpsert specifies if a new document should be created if no document matches the query. +func (umm *UpdateManyModel) SetUpsert(upsert bool) *UpdateManyModel { + umm.Upsert = &upsert + return umm +} + +func (umm *UpdateManyModel) convertModel() driver.WriteModel { + um := driver.UpdateModel{ + Collation: umm.Collation, + } + if umm.Upsert != nil { + um.Upsert = *umm.Upsert + um.UpsertSet = true + } + + converted := driver.UpdateManyModel{ + UpdateModel: um, + Filter: umm.Filter, + Update: umm.Update, + } + if umm.ArrayFilters != nil { + converted.ArrayFilters = *umm.ArrayFilters + converted.ArrayFiltersSet = true + } + + return converted +} + +func dispatchToMongoModel(model driver.WriteModel) WriteModel { + switch conv := model.(type) { + case driver.InsertOneModel: + return &InsertOneModel{ + Document: conv.Document, + } + case driver.DeleteOneModel: + return &DeleteOneModel{ + Filter: conv.Filter, + Collation: conv.Collation, + } + case driver.DeleteManyModel: + return &DeleteManyModel{ + Filter: conv.Filter, + Collation: conv.Collation, + } + case driver.ReplaceOneModel: + rom := &ReplaceOneModel{ + Filter: conv.Filter, + Replacement: conv.Replacement, + Collation: conv.Collation, + } + if conv.UpsertSet { + rom.Upsert = &conv.Upsert + } + return rom + case driver.UpdateOneModel: + uom := &UpdateOneModel{ + Filter: conv.Filter, + Update: conv.Update, + Collation: conv.Collation, + } + if conv.UpsertSet { + uom.Upsert = &conv.Upsert + } + if conv.ArrayFiltersSet { + uom.ArrayFilters = &conv.ArrayFilters + } + return uom + case driver.UpdateManyModel: + umm := &UpdateManyModel{ + Filter: conv.Filter, + Update: conv.Update, + Collation: conv.Collation, + } + if conv.UpsertSet { + umm.Upsert = &conv.Upsert + } + if conv.ArrayFiltersSet { + umm.ArrayFilters = &conv.ArrayFilters + } + return umm + } + + return nil +} diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/change_stream.go b/vendor/go.mongodb.org/mongo-driver/mongo/change_stream.go new file mode 100644 index 0000000..f18e732 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/change_stream.go @@ -0,0 +1,513 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package mongo + +import ( + "context" + "errors" + "time" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" +) + +const errorInterrupted int32 = 11601 +const errorCappedPositionLost int32 = 136 +const errorCursorKilled int32 = 237 + +// ErrMissingResumeToken indicates that a change stream notification from the server did not +// contain a resume token. +var ErrMissingResumeToken = errors.New("cannot provide resume functionality when the resume token is missing") + +// ErrNilCursor indicates that the cursor for the change stream is nil. +var ErrNilCursor = errors.New("cursor is nil") + +// ChangeStream instances iterate a stream of change documents. Each document can be decoded via the +// Decode method. Resume tokens should be retrieved via the ResumeToken method and can be stored to +// resume the change stream at a specific point in time. +// +// A typical usage of the ChangeStream type would be: +type ChangeStream struct { + // Current is the BSON bytes of the current change document. This property is only valid until + // the next call to Next or Close. If continued access is required to the bson.Raw, you must + // make a copy of it. + Current bson.Raw + + cmd bsonx.Doc // aggregate command to run to create stream and rebuild cursor + pipeline bsonx.Arr + options *options.ChangeStreamOptions + coll *Collection + db *Database + ns command.Namespace + cursor *Cursor + cursorOpts bsonx.Doc + getMoreOpts bsonx.Doc + + resumeToken bsonx.Doc + err error + streamType StreamType + client *Client + sess Session + readPref *readpref.ReadPref + readConcern *readconcern.ReadConcern + registry *bsoncodec.Registry +} + +func (cs *ChangeStream) replaceOptions(desc description.SelectedServer) { + // if cs has not received any changes and resumeAfter not specified and max wire version >= 7, run known agg cmd + // with startAtOperationTime set to startAtOperationTime provided by user or saved from initial agg + // must not send resumeAfter key + + // else: run known agg cmd with resumeAfter set to last known resumeToken + // must not set startAtOperationTime (remove if originally in cmd) + + if cs.options.ResumeAfter == nil && desc.WireVersion.Max >= 7 && cs.resumeToken == nil { + cs.options.SetStartAtOperationTime(cs.sess.OperationTime()) + } else { + if cs.resumeToken == nil { + return // restart stream without the resume token + } + + cs.options.SetResumeAfter(cs.resumeToken) + // remove startAtOperationTime + cs.options.SetStartAtOperationTime(nil) + } +} + +// Create options docs for the pipeline and cursor +func createCmdDocs(csType StreamType, opts *options.ChangeStreamOptions, registry *bsoncodec.Registry) (bsonx.Doc, + bsonx.Doc, bsonx.Doc, bsonx.Doc, error) { + + pipelineDoc := bsonx.Doc{} + cursorDoc := bsonx.Doc{} + optsDoc := bsonx.Doc{} + getMoreOptsDoc := bsonx.Doc{} + + if csType == ClientStream { + pipelineDoc = pipelineDoc.Append("allChangesForCluster", bsonx.Boolean(true)) + } + + if opts.BatchSize != nil { + cursorDoc = cursorDoc.Append("batchSize", bsonx.Int32(*opts.BatchSize)) + } + if opts.Collation != nil { + collDoc, err := bsonx.ReadDoc(opts.Collation.ToDocument()) + if err != nil { + return nil, nil, nil, nil, err + } + optsDoc = optsDoc.Append("collation", bsonx.Document(collDoc)) + } + if opts.FullDocument != nil { + pipelineDoc = pipelineDoc.Append("fullDocument", bsonx.String(string(*opts.FullDocument))) + } + if opts.MaxAwaitTime != nil { + ms := int64(time.Duration(*opts.MaxAwaitTime) / time.Millisecond) + getMoreOptsDoc = getMoreOptsDoc.Append("maxTimeMS", bsonx.Int64(ms)) + } + if opts.ResumeAfter != nil { + rt, err := transformDocument(registry, opts.ResumeAfter) + if err != nil { + return nil, nil, nil, nil, err + } + + pipelineDoc = pipelineDoc.Append("resumeAfter", bsonx.Document(rt)) + } + if opts.StartAtOperationTime != nil { + pipelineDoc = pipelineDoc.Append("startAtOperationTime", + bsonx.Timestamp(opts.StartAtOperationTime.T, opts.StartAtOperationTime.I)) + } + + return pipelineDoc, cursorDoc, optsDoc, getMoreOptsDoc, nil +} + +func getSession(ctx context.Context, client *Client) (Session, error) { + sess := sessionFromContext(ctx) + if err := client.validSession(sess); err != nil { + return nil, err + } + + var mongoSess Session + if sess != nil { + mongoSess = &sessionImpl{ + Client: sess, + } + } else { + // create implicit session because it will be needed + newSess, err := session.NewClientSession(client.topology.SessionPool, client.id, session.Implicit) + if err != nil { + return nil, err + } + + mongoSess = &sessionImpl{ + Client: newSess, + } + } + + return mongoSess, nil +} + +func parseOptions(csType StreamType, opts *options.ChangeStreamOptions, registry *bsoncodec.Registry) (bsonx.Doc, + bsonx.Doc, bsonx.Doc, bsonx.Doc, error) { + + if opts.FullDocument == nil { + opts = opts.SetFullDocument(options.Default) + } + + pipelineDoc, cursorDoc, optsDoc, getMoreOptsDoc, err := createCmdDocs(csType, opts, registry) + if err != nil { + return nil, nil, nil, nil, err + } + + return pipelineDoc, cursorDoc, optsDoc, getMoreOptsDoc, nil +} + +func (cs *ChangeStream) runCommand(ctx context.Context, replaceOptions bool) error { + ss, err := cs.client.topology.SelectServer(ctx, cs.db.writeSelector) + if err != nil { + return replaceErrors(err) + } + + desc := ss.Description() + conn, err := ss.Connection(ctx) + if err != nil { + return replaceErrors(err) + } + defer conn.Close() + + if replaceOptions { + cs.replaceOptions(desc) + optionsDoc, _, _, _, err := createCmdDocs(cs.streamType, cs.options, cs.registry) + if err != nil { + return err + } + + changeStreamDoc := bsonx.Doc{ + {"$changeStream", bsonx.Document(optionsDoc)}, + } + cs.pipeline[0] = bsonx.Document(changeStreamDoc) + cs.cmd.Set("pipeline", bsonx.Array(cs.pipeline)) + } + + readCmd := command.Read{ + DB: cs.db.name, + Command: cs.cmd, + Session: cs.sess.(*sessionImpl).Client, + Clock: cs.client.clock, + ReadPref: cs.readPref, + ReadConcern: cs.readConcern, + } + + rdr, err := readCmd.RoundTrip(ctx, desc, conn) + if err != nil { + cs.sess.EndSession(ctx) + return replaceErrors(err) + } + + batchCursor, err := driver.NewBatchCursor(bsoncore.Document(rdr), readCmd.Session, readCmd.Clock, ss.Server, cs.getMoreOpts...) + if err != nil { + cs.sess.EndSession(ctx) + return replaceErrors(err) + } + cursor, err := newCursor(batchCursor, cs.registry) + if err != nil { + cs.sess.EndSession(ctx) + return err + } + cs.cursor = cursor + + cursorValue, err := rdr.LookupErr("cursor") + if err != nil { + return err + } + cursorDoc := cursorValue.Document() + cs.ns = command.ParseNamespace(cursorDoc.Lookup("ns").StringValue()) + + return nil +} + +func newChangeStream(ctx context.Context, coll *Collection, pipeline interface{}, + opts ...*options.ChangeStreamOptions) (*ChangeStream, error) { + + pipelineArr, err := transformAggregatePipeline(coll.registry, pipeline) + if err != nil { + return nil, err + } + + csOpts := options.MergeChangeStreamOptions(opts...) + pipelineDoc, cursorDoc, optsDoc, getMoreDoc, err := parseOptions(CollectionStream, csOpts, coll.registry) + if err != nil { + return nil, err + } + sess, err := getSession(ctx, coll.client) + if err != nil { + return nil, err + } + + csDoc := bsonx.Document(bsonx.Doc{ + {"$changeStream", bsonx.Document(pipelineDoc)}, + }) + pipelineArr = append(bsonx.Arr{csDoc}, pipelineArr...) + + cmd := bsonx.Doc{ + {"aggregate", bsonx.String(coll.name)}, + {"pipeline", bsonx.Array(pipelineArr)}, + {"cursor", bsonx.Document(cursorDoc)}, + } + cmd = append(cmd, optsDoc...) + + cs := &ChangeStream{ + client: coll.client, + sess: sess, + cmd: cmd, + pipeline: pipelineArr, + coll: coll, + db: coll.db, + streamType: CollectionStream, + readPref: coll.readPreference, + readConcern: coll.readConcern, + options: csOpts, + registry: coll.registry, + cursorOpts: cursorDoc, + getMoreOpts: getMoreDoc, + } + + err = cs.runCommand(ctx, false) + if err != nil { + return nil, err + } + + return cs, nil +} + +func newDbChangeStream(ctx context.Context, db *Database, pipeline interface{}, + opts ...*options.ChangeStreamOptions) (*ChangeStream, error) { + + pipelineArr, err := transformAggregatePipeline(db.registry, pipeline) + if err != nil { + return nil, err + } + + csOpts := options.MergeChangeStreamOptions(opts...) + pipelineDoc, cursorDoc, optsDoc, getMoreDoc, err := parseOptions(DatabaseStream, csOpts, db.registry) + if err != nil { + return nil, err + } + sess, err := getSession(ctx, db.client) + if err != nil { + return nil, err + } + + csDoc := bsonx.Document(bsonx.Doc{ + {"$changeStream", bsonx.Document(pipelineDoc)}, + }) + pipelineArr = append(bsonx.Arr{csDoc}, pipelineArr...) + + cmd := bsonx.Doc{ + {"aggregate", bsonx.Int32(1)}, + {"pipeline", bsonx.Array(pipelineArr)}, + {"cursor", bsonx.Document(cursorDoc)}, + } + cmd = append(cmd, optsDoc...) + + cs := &ChangeStream{ + client: db.client, + db: db, + sess: sess, + cmd: cmd, + pipeline: pipelineArr, + streamType: DatabaseStream, + readPref: db.readPreference, + readConcern: db.readConcern, + options: csOpts, + registry: db.registry, + cursorOpts: cursorDoc, + getMoreOpts: getMoreDoc, + } + + err = cs.runCommand(ctx, false) + if err != nil { + return nil, err + } + + return cs, nil +} + +func newClientChangeStream(ctx context.Context, client *Client, pipeline interface{}, + opts ...*options.ChangeStreamOptions) (*ChangeStream, error) { + + pipelineArr, err := transformAggregatePipeline(client.registry, pipeline) + if err != nil { + return nil, err + } + + csOpts := options.MergeChangeStreamOptions(opts...) + pipelineDoc, cursorDoc, optsDoc, getMoreDoc, err := parseOptions(ClientStream, csOpts, client.registry) + if err != nil { + return nil, err + } + sess, err := getSession(ctx, client) + if err != nil { + return nil, err + } + + csDoc := bsonx.Document(bsonx.Doc{ + {"$changeStream", bsonx.Document(pipelineDoc)}, + }) + pipelineArr = append(bsonx.Arr{csDoc}, pipelineArr...) + + cmd := bsonx.Doc{ + {"aggregate", bsonx.Int32(1)}, + {"pipeline", bsonx.Array(pipelineArr)}, + {"cursor", bsonx.Document(cursorDoc)}, + } + cmd = append(cmd, optsDoc...) + + cs := &ChangeStream{ + client: client, + db: client.Database("admin"), + sess: sess, + cmd: cmd, + pipeline: pipelineArr, + streamType: ClientStream, + readPref: client.readPreference, + readConcern: client.readConcern, + options: csOpts, + registry: client.registry, + cursorOpts: cursorDoc, + getMoreOpts: getMoreDoc, + } + + err = cs.runCommand(ctx, false) + if err != nil { + return nil, err + } + + return cs, nil +} + +func (cs *ChangeStream) storeResumeToken() error { + idVal, err := cs.cursor.Current.LookupErr("_id") + if err != nil { + _ = cs.Close(context.Background()) + return ErrMissingResumeToken + } + + var idDoc bson.Raw + idDoc, ok := idVal.DocumentOK() + if !ok { + _ = cs.Close(context.Background()) + return ErrMissingResumeToken + } + tokenDoc, err := bsonx.ReadDoc(idDoc) + if err != nil { + _ = cs.Close(context.Background()) + return ErrMissingResumeToken + } + + cs.resumeToken = tokenDoc + return nil +} + +// ID returns the cursor ID for this change stream. +func (cs *ChangeStream) ID() int64 { + if cs.cursor == nil { + return 0 + } + + return cs.cursor.ID() +} + +// Next gets the next result from this change stream. Returns true if there were no errors and the next +// result is available for decoding. +func (cs *ChangeStream) Next(ctx context.Context) bool { + // execute in a loop to retry resume-able errors and advance the underlying cursor + for { + if cs.cursor == nil { + return false + } + + if cs.cursor.Next(ctx) { + err := cs.storeResumeToken() + if err != nil { + cs.err = err + return false + } + + cs.Current = cs.cursor.Current + return true + } + + err := cs.cursor.Err() + if err == nil { + return false + } + + switch t := err.(type) { + case command.Error: + if t.Code == errorInterrupted || t.Code == errorCappedPositionLost || t.Code == errorCursorKilled { + return false + } + } + + _, _ = driver.KillCursors(ctx, cs.ns, cs.cursor.bc.Server(), cs.ID()) + + cs.err = cs.runCommand(ctx, true) + if cs.err != nil { + return false + } + } +} + +// Decode will decode the current document into val. +func (cs *ChangeStream) Decode(out interface{}) error { + if cs.cursor == nil { + return ErrNilCursor + } + + return bson.UnmarshalWithRegistry(cs.registry, cs.Current, out) +} + +// Err returns the current error. +func (cs *ChangeStream) Err() error { + if cs.err != nil { + return replaceErrors(cs.err) + } + if cs.cursor == nil { + return nil + } + + return cs.cursor.Err() +} + +// Close closes this cursor. +func (cs *ChangeStream) Close(ctx context.Context) error { + if cs.cursor == nil { + return nil // cursor is already closed + } + + return replaceErrors(cs.cursor.Close(ctx)) +} + +// StreamType represents the type of a change stream. +type StreamType uint8 + +// These constants represent valid change stream types. A change stream can be initialized over a collection, all +// collections in a database, or over a whole client. +const ( + CollectionStream StreamType = iota + DatabaseStream + ClientStream +) diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/client.go b/vendor/go.mongodb.org/mongo-driver/mongo/client.go new file mode 100644 index 0000000..cf42af1 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/client.go @@ -0,0 +1,539 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package mongo + +import ( + "context" + "strings" + "time" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/event" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/connstring" + "go.mongodb.org/mongo-driver/x/network/description" +) + +const defaultLocalThreshold = 15 * time.Millisecond + +// Client performs operations on a given topology. +type Client struct { + id uuid.UUID + topologyOptions []topology.Option + topology *topology.Topology + connString connstring.ConnString + localThreshold time.Duration + retryWrites bool + clock *session.ClusterClock + readPreference *readpref.ReadPref + readConcern *readconcern.ReadConcern + writeConcern *writeconcern.WriteConcern + registry *bsoncodec.Registry + marshaller BSONAppender +} + +// Connect creates a new Client and then initializes it using the Connect method. +func Connect(ctx context.Context, opts ...*options.ClientOptions) (*Client, error) { + c, err := NewClient(opts...) + if err != nil { + return nil, err + } + err = c.Connect(ctx) + if err != nil { + return nil, err + } + return c, nil +} + +// NewClient creates a new client to connect to a cluster specified by the uri. +// +// When creating an options.ClientOptions, the order the methods are called matters. Later Set* +// methods will overwrite the values from previous Set* method invocations. This includes the +// ApplyURI method. This allows callers to determine the order of precedence for option +// application. For instance, if ApplyURI is called before SetAuth, the Credential from +// SetAuth will overwrite the values from the connection string. If ApplyURI is called +// after SetAuth, then its values will overwrite those from SetAuth. +// +// The opts parameter is processed using options.MergeClientOptions, which will overwrite entire +// option fields of previous options, there is no partial overwriting. For example, if Username is +// set in the Auth field for the first option, and Password is set for the second but with no +// Username, after the merge the Username field will be empty. +func NewClient(opts ...*options.ClientOptions) (*Client, error) { + clientOpt := options.MergeClientOptions(opts...) + + id, err := uuid.New() + if err != nil { + return nil, err + } + client := &Client{id: id} + + err = client.configure(clientOpt) + if err != nil { + return nil, err + } + + client.topology, err = topology.New(client.topologyOptions...) + if err != nil { + return nil, replaceErrors(err) + } + + return client, nil +} + +// Connect initializes the Client by starting background monitoring goroutines. +// This method must be called before a Client can be used. +func (c *Client) Connect(ctx context.Context) error { + err := c.topology.Connect(ctx) + if err != nil { + return replaceErrors(err) + } + + return nil + +} + +// Disconnect closes sockets to the topology referenced by this Client. It will +// shut down any monitoring goroutines, close the idle connection pool, and will +// wait until all the in use connections have been returned to the connection +// pool and closed before returning. If the context expires via cancellation, +// deadline, or timeout before the in use connections have returned, the in use +// connections will be closed, resulting in the failure of any in flight read +// or write operations. If this method returns with no errors, all connections +// associated with this Client have been closed. +func (c *Client) Disconnect(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } + + c.endSessions(ctx) + return replaceErrors(c.topology.Disconnect(ctx)) +} + +// Ping verifies that the client can connect to the topology. +// If readPreference is nil then will use the client's default read +// preference. +func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error { + if ctx == nil { + ctx = context.Background() + } + + if rp == nil { + rp = c.readPreference + } + + _, err := c.topology.SelectServer(ctx, description.ReadPrefSelector(rp)) + return replaceErrors(err) +} + +// StartSession starts a new session. +func (c *Client) StartSession(opts ...*options.SessionOptions) (Session, error) { + if c.topology.SessionPool == nil { + return nil, ErrClientDisconnected + } + + sopts := options.MergeSessionOptions(opts...) + coreOpts := &session.ClientOptions{ + DefaultReadConcern: c.readConcern, + DefaultReadPreference: c.readPreference, + DefaultWriteConcern: c.writeConcern, + } + if sopts.CausalConsistency != nil { + coreOpts.CausalConsistency = sopts.CausalConsistency + } + if sopts.DefaultReadConcern != nil { + coreOpts.DefaultReadConcern = sopts.DefaultReadConcern + } + if sopts.DefaultWriteConcern != nil { + coreOpts.DefaultWriteConcern = sopts.DefaultWriteConcern + } + if sopts.DefaultReadPreference != nil { + coreOpts.DefaultReadPreference = sopts.DefaultReadPreference + } + + sess, err := session.NewClientSession(c.topology.SessionPool, c.id, session.Explicit, coreOpts) + if err != nil { + return nil, replaceErrors(err) + } + + sess.RetryWrite = c.retryWrites + + return &sessionImpl{ + Client: sess, + topo: c.topology, + }, nil +} + +func (c *Client) endSessions(ctx context.Context) { + if c.topology.SessionPool == nil { + return + } + cmd := command.EndSessions{ + Clock: c.clock, + SessionIDs: c.topology.SessionPool.IDSlice(), + } + + _, _ = driver.EndSessions(ctx, cmd, c.topology, description.ReadPrefSelector(readpref.PrimaryPreferred())) +} + +func (c *Client) configure(opts *options.ClientOptions) error { + if err := opts.Validate(); err != nil { + return err + } + + var connOpts []connection.Option + var serverOpts []topology.ServerOption + var topologyOpts []topology.Option + + // TODO(GODRIVER-814): Add tests for topology, server, and connection related options. + + // AppName + var appName string + if opts.AppName != nil { + appName = *opts.AppName + } + // Compressors & ZlibLevel + var comps []string + if len(opts.Compressors) > 0 { + comps = opts.Compressors + + connOpts = append(connOpts, connection.WithCompressors( + func(compressors []string) []string { + return append(compressors, comps...) + }, + )) + + for _, comp := range comps { + if comp == "zlib" { + connOpts = append(connOpts, connection.WithZlibLevel(func(level *int) *int { + return opts.ZlibLevel + })) + } + } + + serverOpts = append(serverOpts, topology.WithCompressionOptions( + func(opts ...string) []string { return append(opts, comps...) }, + )) + } + // Handshaker + var handshaker = func(connection.Handshaker) connection.Handshaker { + return &command.Handshake{Client: command.ClientDoc(appName), Compressors: comps} + } + // Auth & Database & Password & Username + if opts.Auth != nil { + cred := &auth.Cred{ + Username: opts.Auth.Username, + Password: opts.Auth.Password, + PasswordSet: opts.Auth.PasswordSet, + Props: opts.Auth.AuthMechanismProperties, + Source: opts.Auth.AuthSource, + } + mechanism := opts.Auth.AuthMechanism + + if len(cred.Source) == 0 { + switch strings.ToUpper(mechanism) { + case auth.MongoDBX509, auth.GSSAPI, auth.PLAIN: + cred.Source = "$external" + default: + cred.Source = "admin" + } + } + + authenticator, err := auth.CreateAuthenticator(mechanism, cred) + if err != nil { + return err + } + + handshakeOpts := &auth.HandshakeOptions{ + AppName: appName, + Authenticator: authenticator, + Compressors: comps, + } + if mechanism == "" { + // Required for SASL mechanism negotiation during handshake + handshakeOpts.DBUser = cred.Source + "." + cred.Username + } + if opts.AuthenticateToAnything != nil && *opts.AuthenticateToAnything { + // Authenticate arbiters + handshakeOpts.PerformAuthentication = func(serv description.Server) bool { + return true + } + } + + handshaker = func(connection.Handshaker) connection.Handshaker { + return auth.Handshaker(nil, handshakeOpts) + } + } + connOpts = append(connOpts, connection.WithHandshaker(handshaker)) + // ConnectTimeout + if opts.ConnectTimeout != nil { + serverOpts = append(serverOpts, topology.WithHeartbeatTimeout( + func(time.Duration) time.Duration { return *opts.ConnectTimeout }, + )) + connOpts = append(connOpts, connection.WithConnectTimeout( + func(time.Duration) time.Duration { return *opts.ConnectTimeout }, + )) + } + // Dialer + if opts.Dialer != nil { + connOpts = append(connOpts, connection.WithDialer( + func(connection.Dialer) connection.Dialer { return opts.Dialer }, + )) + } + // Direct + if opts.Direct != nil && *opts.Direct { + topologyOpts = append(topologyOpts, topology.WithMode( + func(topology.MonitorMode) topology.MonitorMode { return topology.SingleMode }, + )) + } + // HeartbeatInterval + if opts.HeartbeatInterval != nil { + serverOpts = append(serverOpts, topology.WithHeartbeatInterval( + func(time.Duration) time.Duration { return *opts.HeartbeatInterval }, + )) + } + // Hosts + hosts := []string{"localhost:27017"} // default host + if len(opts.Hosts) > 0 { + hosts = opts.Hosts + } + topologyOpts = append(topologyOpts, topology.WithSeedList( + func(...string) []string { return hosts }, + )) + // LocalThreshold + if opts.LocalThreshold != nil { + c.localThreshold = *opts.LocalThreshold + } + // MaxConIdleTime + if opts.MaxConnIdleTime != nil { + connOpts = append(connOpts, connection.WithIdleTimeout( + func(time.Duration) time.Duration { return *opts.MaxConnIdleTime }, + )) + } + // MaxPoolSize + if opts.MaxPoolSize != nil { + serverOpts = append( + serverOpts, + topology.WithMaxConnections(func(uint16) uint16 { return *opts.MaxPoolSize }), + topology.WithMaxIdleConnections(func(uint16) uint16 { return *opts.MaxPoolSize }), + ) + } + // Monitor + if opts.Monitor != nil { + connOpts = append(connOpts, connection.WithMonitor( + func(*event.CommandMonitor) *event.CommandMonitor { return opts.Monitor }, + )) + } + // ReadConcern + c.readConcern = readconcern.New() + if opts.ReadConcern != nil { + c.readConcern = opts.ReadConcern + } + // ReadPreference + c.readPreference = readpref.Primary() + if opts.ReadPreference != nil { + c.readPreference = opts.ReadPreference + } + // Registry + c.registry = bson.DefaultRegistry + if opts.Registry != nil { + c.registry = opts.Registry + } + // ReplicaSet + if opts.ReplicaSet != nil { + topologyOpts = append(topologyOpts, topology.WithReplicaSetName( + func(string) string { return *opts.ReplicaSet }, + )) + } + // RetryWrites + if opts.RetryWrites != nil { + c.retryWrites = *opts.RetryWrites + } + // ServerSelectionTimeout + if opts.ServerSelectionTimeout != nil { + topologyOpts = append(topologyOpts, topology.WithServerSelectionTimeout( + func(time.Duration) time.Duration { return *opts.ServerSelectionTimeout }, + )) + } + // SocketTimeout + if opts.SocketTimeout != nil { + connOpts = append( + connOpts, + connection.WithReadTimeout(func(time.Duration) time.Duration { return *opts.SocketTimeout }), + connection.WithWriteTimeout(func(time.Duration) time.Duration { return *opts.SocketTimeout }), + ) + } + // TLSConfig + if opts.TLSConfig != nil { + connOpts = append(connOpts, connection.WithTLSConfig( + func(*connection.TLSConfig) *connection.TLSConfig { + return &connection.TLSConfig{Config: opts.TLSConfig} + }, + )) + } + // WriteConcern + if opts.WriteConcern != nil { + c.writeConcern = opts.WriteConcern + } + + // ClusterClock + c.clock = new(session.ClusterClock) + + serverOpts = append( + serverOpts, + topology.WithClock(func(*session.ClusterClock) *session.ClusterClock { return c.clock }), + topology.WithConnectionOptions(func(...connection.Option) []connection.Option { return connOpts }), + ) + c.topologyOptions = append(topologyOpts, topology.WithServerOptions( + func(...topology.ServerOption) []topology.ServerOption { return serverOpts }, + )) + + return nil +} + +// validSession returns an error if the session doesn't belong to the client +func (c *Client) validSession(sess *session.Client) error { + if sess != nil && !uuid.Equal(sess.ClientID, c.id) { + return ErrWrongClient + } + return nil +} + +// Database returns a handle for a given database. +func (c *Client) Database(name string, opts ...*options.DatabaseOptions) *Database { + return newDatabase(c, name, opts...) +} + +// ListDatabases returns a ListDatabasesResult. +func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) (ListDatabasesResult, error) { + if ctx == nil { + ctx = context.Background() + } + + sess := sessionFromContext(ctx) + + err := c.validSession(sess) + if err != nil { + return ListDatabasesResult{}, err + } + + f, err := transformDocument(c.registry, filter) + if err != nil { + return ListDatabasesResult{}, err + } + + cmd := command.ListDatabases{ + Filter: f, + Session: sess, + Clock: c.clock, + } + + readSelector := description.CompositeSelector([]description.ServerSelector{ + description.ReadPrefSelector(readpref.Primary()), + description.LatencySelector(c.localThreshold), + }) + res, err := driver.ListDatabases( + ctx, cmd, + c.topology, + readSelector, + c.id, + c.topology.SessionPool, + opts..., + ) + if err != nil { + return ListDatabasesResult{}, replaceErrors(err) + } + + return (ListDatabasesResult{}).fromResult(res), nil +} + +// ListDatabaseNames returns a slice containing the names of all of the databases on the server. +func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...*options.ListDatabasesOptions) ([]string, error) { + opts = append(opts, options.ListDatabases().SetNameOnly(true)) + + res, err := c.ListDatabases(ctx, filter, opts...) + if err != nil { + return nil, err + } + + names := make([]string, 0) + for _, spec := range res.Databases { + names = append(names, spec.Name) + } + + return names, nil +} + +// WithSession allows a user to start a session themselves and manage +// its lifetime. The only way to provide a session to a CRUD method is +// to invoke that CRUD method with the mongo.SessionContext within the +// closure. The mongo.SessionContext can be used as a regular context, +// so methods like context.WithDeadline and context.WithTimeout are +// supported. +// +// If the context.Context already has a mongo.Session attached, that +// mongo.Session will be replaced with the one provided. +// +// Errors returned from the closure are transparently returned from +// this function. +func WithSession(ctx context.Context, sess Session, fn func(SessionContext) error) error { + return fn(contextWithSession(ctx, sess)) +} + +// UseSession creates a default session, that is only valid for the +// lifetime of the closure. No cleanup outside of closing the session +// is done upon exiting the closure. This means that an outstanding +// transaction will be aborted, even if the closure returns an error. +// +// If ctx already contains a mongo.Session, that mongo.Session will be +// replaced with the newly created mongo.Session. +// +// Errors returned from the closure are transparently returned from +// this method. +func (c *Client) UseSession(ctx context.Context, fn func(SessionContext) error) error { + return c.UseSessionWithOptions(ctx, options.Session(), fn) +} + +// UseSessionWithOptions works like UseSession but allows the caller +// to specify the options used to create the session. +func (c *Client) UseSessionWithOptions(ctx context.Context, opts *options.SessionOptions, fn func(SessionContext) error) error { + defaultSess, err := c.StartSession(opts) + if err != nil { + return err + } + + defer defaultSess.EndSession(ctx) + + sessCtx := sessionContext{ + Context: context.WithValue(ctx, sessionKey{}, defaultSess), + Session: defaultSess, + } + + return fn(sessCtx) +} + +// Watch returns a change stream cursor used to receive information of changes to the client. This method is preferred +// to running a raw aggregation with a $changeStream stage because it supports resumability in the case of some errors. +// The client must have read concern majority or no read concern for a change stream to be created successfully. +func (c *Client) Watch(ctx context.Context, pipeline interface{}, + opts ...*options.ChangeStreamOptions) (*ChangeStream, error) { + if c.topology.SessionPool == nil { + return nil, ErrClientDisconnected + } + + return newClientChangeStream(ctx, c, pipeline, opts...) +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/collection.go b/vendor/go.mongodb.org/mongo-driver/mongo/collection.go similarity index 66% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/collection.go rename to vendor/go.mongodb.org/mongo-driver/mongo/collection.go index 767404f..0e5bd22 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/collection.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/collection.go @@ -11,16 +11,17 @@ import ( "errors" "strings" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // Collection performs operations on a given collection. @@ -142,13 +143,14 @@ func (coll *Collection) Database() *Database { return coll.db } -// BulkWrite performs a bulk write operation. A custom context can be supplied to this method or nil to default to -// context.Background(). +// BulkWrite performs a bulk write operation. +// +// See https://docs.mongodb.com/manual/core/bulk-write-operations/. func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, opts ...*options.BulkWriteOptions) (*BulkWriteResult, error) { if len(models) == 0 { - return nil, errors.New("a bulk write must contain at least one write model") + return nil, ErrEmptySlice } if ctx == nil { @@ -157,17 +159,20 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, sess := sessionFromContext(ctx) - err := coll.client.ValidSession(sess) + err := coll.client.validSession(sess) if err != nil { return nil, err } - dispatchModels := make([]dispatch.WriteModel, len(models)) + dispatchModels := make([]driver.WriteModel, len(models)) for i, model := range models { + if model == nil { + return nil, ErrNilDocument + } dispatchModels[i] = model.convertModel() } - res, err := dispatch.BulkWrite( + res, err := driver.BulkWrite( ctx, coll.namespace(), dispatchModels, @@ -182,37 +187,19 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, coll.registry, opts..., ) - - if err != nil { - if conv, ok := err.(dispatch.BulkWriteException); ok { - return &BulkWriteResult{}, BulkWriteException{ - WriteConcernError: convertWriteConcernError(conv.WriteConcernError), - WriteErrors: convertBulkWriteErrors(conv.WriteErrors), - } - } - - return &BulkWriteResult{}, replaceTopologyErr(err) - } - - return &BulkWriteResult{ + result := BulkWriteResult{ InsertedCount: res.InsertedCount, MatchedCount: res.MatchedCount, ModifiedCount: res.ModifiedCount, DeletedCount: res.DeletedCount, UpsertedCount: res.UpsertedCount, UpsertedIDs: res.UpsertedIDs, - }, nil + } + + return &result, replaceErrors(err) } -// InsertOne inserts a single document into the collection. A user can supply -// a custom context to this method, or nil to default to context.Background(). -// -// This method uses TransformDocument to turn the document parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// document. -// -// TODO(skriptble): Determine if we should unwrap the value for the -// InsertOneResult or just return the bsonx.Element or a bsonx.Value. +// InsertOne inserts a single document into the collection. func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...*options.InsertOneOptions) (*InsertOneResult, error) { @@ -220,22 +207,20 @@ func (coll *Collection) InsertOne(ctx context.Context, document interface{}, ctx = context.Background() } - doc, err := transformDocument(coll.registry, document) + doc, insertedID, err := transformAndEnsureID(coll.registry, document) if err != nil { return nil, err } - doc, insertedID := ensureID(doc) - sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } oldns := coll.namespace() @@ -254,7 +239,7 @@ func (coll *Collection) InsertOne(ctx context.Context, document interface{}, insertOpts[i].BypassDocumentValidation = opt.BypassDocumentValidation } - res, err := dispatch.Insert( + res, err := driver.Insert( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -272,16 +257,7 @@ func (coll *Collection) InsertOne(ctx context.Context, document interface{}, return &InsertOneResult{InsertedID: insertedID}, err } -// InsertMany inserts the provided documents. A user can supply a custom context to this -// method. -// -// Currently, batching is not implemented for this operation. Because of this, extremely large -// sets of documents will not fit into a single BSON document to be sent to the server, so the -// operation will fail. -// -// This method uses TransformDocument to turn the documents parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// documents. +// InsertMany inserts the provided documents. func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, opts ...*options.InsertManyOptions) (*InsertManyResult, error) { @@ -289,15 +265,21 @@ func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, ctx = context.Background() } + if len(documents) == 0 { + return nil, ErrEmptySlice + } + result := make([]interface{}, len(documents)) docs := make([]bsonx.Doc, len(documents)) for i, doc := range documents { - bdoc, err := transformDocument(coll.registry, doc) + if doc == nil { + return nil, ErrNilDocument + } + bdoc, insertedID, err := transformAndEnsureID(coll.registry, doc) if err != nil { return nil, err } - bdoc, insertedID := ensureID(bdoc) docs[i] = bdoc result[i] = insertedID @@ -305,13 +287,13 @@ func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, sess := sessionFromContext(ctx) - err := coll.client.ValidSession(sess) + err := coll.client.validSession(sess) if err != nil { return nil, err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -324,7 +306,7 @@ func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, Clock: coll.client.clock, } - res, err := dispatch.Insert( + res, err := driver.Insert( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -339,7 +321,7 @@ func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, case command.ErrUnacknowledgedWrite: return &InsertManyResult{InsertedIDs: result}, ErrUnacknowledgedWrite default: - return nil, replaceTopologyErr(err) + return nil, replaceErrors(err) } if len(res.WriteErrors) > 0 || res.WriteConcernError != nil { bwErrors := make([]BulkWriteError, 0, len(res.WriteErrors)) @@ -363,12 +345,7 @@ func (coll *Collection) InsertMany(ctx context.Context, documents []interface{}, return &InsertManyResult{InsertedIDs: result}, err } -// DeleteOne deletes a single document from the collection. A user can supply -// a custom context to this method, or nil to default to context.Background(). -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. +// DeleteOne deletes a single document from the collection. func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error) { @@ -389,13 +366,13 @@ func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -408,7 +385,7 @@ func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, Clock: coll.client.clock, } - res, err := dispatch.Delete( + res, err := driver.Delete( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -425,13 +402,7 @@ func (coll *Collection) DeleteOne(ctx context.Context, filter interface{}, return &DeleteResult{DeletedCount: int64(res.N)}, err } -// DeleteMany deletes multiple documents from the collection. A user can -// supply a custom context to this method, or nil to default to -// context.Background(). -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. +// DeleteMany deletes multiple documents from the collection. func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, opts ...*options.DeleteOptions) (*DeleteResult, error) { @@ -447,13 +418,13 @@ func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -466,7 +437,7 @@ func (coll *Collection) DeleteMany(ctx context.Context, filter interface{}, Clock: coll.client.clock, } - res, err := dispatch.Delete( + res, err := driver.Delete( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -500,7 +471,7 @@ func (coll *Collection) updateOrReplaceOne(ctx context.Context, filter, } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -513,7 +484,7 @@ func (coll *Collection) updateOrReplaceOne(ctx context.Context, filter, Clock: coll.client.clock, } - r, err := dispatch.Update( + r, err := driver.Update( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -523,12 +494,13 @@ func (coll *Collection) updateOrReplaceOne(ctx context.Context, filter, opts..., ) if err != nil && err != command.ErrUnacknowledgedWrite { - return nil, replaceTopologyErr(err) + return nil, replaceErrors(err) } res := &UpdateResult{ MatchedCount: r.MatchedCount, ModifiedCount: r.ModifiedCount, + UpsertedCount: int64(len(r.Upserted)), } if len(r.Upserted) > 0 { res.UpsertedID = r.Upserted[0].ID @@ -542,12 +514,7 @@ func (coll *Collection) updateOrReplaceOne(ctx context.Context, filter, return res, err } -// UpdateOne updates a single document in the collection. A user can supply a -// custom context to this method, or nil to default to context.Background(). -// -// This method uses TransformDocument to turn the filter and update parameter -// into a *bsonx.Document. See TransformDocument for the list of valid types for -// filter and update. +// UpdateOne updates a single document in the collection. func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*UpdateResult, error) { @@ -571,7 +538,7 @@ func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, updat sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } @@ -579,12 +546,7 @@ func (coll *Collection) UpdateOne(ctx context.Context, filter interface{}, updat return coll.updateOrReplaceOne(ctx, f, u, sess, opts...) } -// UpdateMany updates multiple documents in the collection. A user can supply -// a custom context to this method, or nil to default to context.Background(). -// -// This method uses TransformDocument to turn the filter and update parameter -// into a *bsonx.Document. See TransformDocument for the list of valid types for -// filter and update. +// UpdateMany updates multiple documents in the collection. func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, update interface{}, opts ...*options.UpdateOptions) (*UpdateResult, error) { @@ -616,13 +578,13 @@ func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, upda sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -635,7 +597,7 @@ func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, upda Clock: coll.client.clock, } - r, err := dispatch.Update( + r, err := driver.Update( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -645,11 +607,12 @@ func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, upda opts..., ) if err != nil && err != command.ErrUnacknowledgedWrite { - return nil, replaceTopologyErr(err) + return nil, replaceErrors(err) } res := &UpdateResult{ MatchedCount: r.MatchedCount, ModifiedCount: r.ModifiedCount, + UpsertedCount: int64(len(r.Upserted)), } // TODO(skriptble): Is this correct? Do we only return the first upserted ID for an UpdateMany? if len(r.Upserted) > 0 { @@ -664,12 +627,7 @@ func (coll *Collection) UpdateMany(ctx context.Context, filter interface{}, upda return res, err } -// ReplaceOne replaces a single document in the collection. A user can supply -// a custom context to this method, or nil to default to context.Background(). -// -// This method uses TransformDocument to turn the filter and replacement -// parameter into a *bsonx.Document. See TransformDocument for the list of -// valid types for filter and replacement. +// ReplaceOne replaces a single document in the collection. func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, replacement interface{}, opts ...*options.ReplaceOptions) (*UpdateResult, error) { @@ -693,7 +651,7 @@ func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } @@ -710,16 +668,11 @@ func (coll *Collection) ReplaceOne(ctx context.Context, filter interface{}, return coll.updateOrReplaceOne(ctx, f, r, sess, updateOptions...) } -// Aggregate runs an aggregation framework pipeline. A user can supply a custom context to -// this method. +// Aggregate runs an aggregation framework pipeline. // // See https://docs.mongodb.com/manual/aggregation/. -// -// This method uses TransformDocument to turn the pipeline parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// pipeline. func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, - opts ...*options.AggregateOptions) (Cursor, error) { + opts ...*options.AggregateOptions) (*Cursor, error) { if ctx == nil { ctx = context.Background() @@ -734,18 +687,16 @@ func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { - wc = nil - } - rc := coll.readConcern - if sess != nil && (sess.TransactionInProgress()) { + + if sess.TransactionRunning() { + wc = nil rc = nil } @@ -760,7 +711,7 @@ func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, Clock: coll.client.clock, } - cursor, err := dispatch.Aggregate( + batchCursor, err := driver.Aggregate( ctx, cmd, coll.client.topology, coll.readSelector, @@ -770,68 +721,18 @@ func (coll *Collection) Aggregate(ctx context.Context, pipeline interface{}, coll.registry, aggOpts, ) - - return cursor, replaceTopologyErr(err) -} - -// Count gets the number of documents matching the filter. A user can supply a -// custom context to this method, or nil to default to context.Background(). -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. -func (coll *Collection) Count(ctx context.Context, filter interface{}, - opts ...*options.CountOptions) (int64, error) { - - if ctx == nil { - ctx = context.Background() - } - - f, err := transformDocument(coll.registry, filter) - if err != nil { - return 0, err - } - - sess := sessionFromContext(ctx) - - err = coll.client.ValidSession(sess) if err != nil { - return 0, err - } - - rc := coll.readConcern - if sess != nil && (sess.TransactionInProgress()) { - rc = nil - } - - oldns := coll.namespace() - cmd := command.Count{ - NS: command.Namespace{DB: oldns.DB, Collection: oldns.Collection}, - Query: f, - ReadPref: coll.readPreference, - ReadConcern: rc, - Session: sess, - Clock: coll.client.clock, + if wce, ok := err.(result.WriteConcernError); ok { + return nil, *convertWriteConcernError(&wce) + } + return nil, replaceErrors(err) } - count, err := dispatch.Count( - ctx, cmd, - coll.client.topology, - coll.readSelector, - coll.client.id, - coll.client.topology.SessionPool, - coll.registry, - opts..., - ) - - return count, replaceTopologyErr(err) + cursor, err := newCursor(batchCursor, coll.registry) + return cursor, replaceErrors(err) } -// CountDocuments gets the number of documents matching the filter. A user can supply a -// custom context to this method, or nil to default to context.Background(). -// -// This method uses countDocumentsAggregatePipeline to turn the filter parameter and options -// into aggregate pipeline. +// CountDocuments gets the number of documents matching the filter. func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...*options.CountOptions) (int64, error) { @@ -848,13 +749,13 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return 0, err } rc := coll.readConcern - if sess != nil && (sess.TransactionInProgress()) { + if sess.TransactionRunning() { rc = nil } @@ -868,7 +769,7 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, Clock: coll.client.clock, } - count, err := dispatch.CountDocuments( + count, err := driver.CountDocuments( ctx, cmd, coll.client.topology, coll.readSelector, @@ -878,7 +779,7 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, countOpts, ) - return count, replaceTopologyErr(err) + return count, replaceErrors(err) } // EstimatedDocumentCount gets an estimate of the count of documents in a collection using collection metadata. @@ -891,7 +792,7 @@ func (coll *Collection) EstimatedDocumentCount(ctx context.Context, sess := sessionFromContext(ctx) - err := coll.client.ValidSession(sess) + err := coll.client.validSession(sess) if err != nil { return 0, err } @@ -916,7 +817,7 @@ func (coll *Collection) EstimatedDocumentCount(ctx context.Context, countOpts = countOpts.SetMaxTime(*opts[len(opts)-1].MaxTime) } - count, err := dispatch.Count( + count, err := driver.Count( ctx, cmd, coll.client.topology, coll.readSelector, @@ -926,16 +827,11 @@ func (coll *Collection) EstimatedDocumentCount(ctx context.Context, countOpts, ) - return count, replaceTopologyErr(err) + return count, replaceErrors(err) } // Distinct finds the distinct values for a specified field across a single -// collection. A user can supply a custom context to this method, or nil to -// default to context.Background(). -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. +// collection. func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter interface{}, opts ...*options.DistinctOptions) ([]interface{}, error) { @@ -943,24 +839,20 @@ func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter i ctx = context.Background() } - var f bsonx.Doc - var err error - if filter != nil { - f, err = transformDocument(coll.registry, filter) - if err != nil { - return nil, err - } + f, err := transformDocument(coll.registry, filter) + if err != nil { + return nil, err } sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } rc := coll.readConcern - if sess != nil && (sess.TransactionInProgress()) { + if sess.TransactionRunning() { rc = nil } @@ -975,7 +867,7 @@ func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter i Clock: coll.client.clock, } - res, err := dispatch.Distinct( + res, err := driver.Distinct( ctx, cmd, coll.client.topology, coll.readSelector, @@ -984,43 +876,34 @@ func (coll *Collection) Distinct(ctx context.Context, fieldName string, filter i opts..., ) if err != nil { - return nil, replaceTopologyErr(err) + return nil, replaceErrors(err) } return res.Values, nil } -// Find finds the documents matching a model. A user can supply a custom context to this -// method. -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. +// Find finds the documents matching a model. func (coll *Collection) Find(ctx context.Context, filter interface{}, - opts ...*options.FindOptions) (Cursor, error) { + opts ...*options.FindOptions) (*Cursor, error) { if ctx == nil { ctx = context.Background() } - var f bsonx.Doc - var err error - if filter != nil { - f, err = transformDocument(coll.registry, filter) - if err != nil { - return nil, err - } + f, err := transformDocument(coll.registry, filter) + if err != nil { + return nil, err } sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { return nil, err } rc := coll.readConcern - if sess != nil && (sess.TransactionInProgress()) { + if sess.TransactionRunning() { rc = nil } @@ -1034,7 +917,7 @@ func (coll *Collection) Find(ctx context.Context, filter interface{}, Clock: coll.client.clock, } - cursor, err := dispatch.Find( + batchCursor, err := driver.Find( ctx, cmd, coll.client.topology, coll.readSelector, @@ -1043,42 +926,36 @@ func (coll *Collection) Find(ctx context.Context, filter interface{}, coll.registry, opts..., ) + if err != nil { + return nil, replaceErrors(err) + } - return cursor, replaceTopologyErr(err) + cursor, err := newCursor(batchCursor, coll.registry) + return cursor, replaceErrors(err) } -// FindOne returns up to one document that matches the model. A user can -// supply a custom context to this method, or nil to default to -// context.Background(). -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. +// FindOne returns up to one document that matches the model. func (coll *Collection) FindOne(ctx context.Context, filter interface{}, - opts ...*options.FindOneOptions) *DocumentResult { + opts ...*options.FindOneOptions) *SingleResult { if ctx == nil { ctx = context.Background() } - var f bsonx.Doc - var err error - if filter != nil { - f, err = transformDocument(coll.registry, filter) - if err != nil { - return &DocumentResult{err: err} - } + f, err := transformDocument(coll.registry, filter) + if err != nil { + return &SingleResult{err: err} } sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } rc := coll.readConcern - if sess != nil && (sess.TransactionInProgress()) { + if sess.TransactionRunning() { rc = nil } @@ -1115,7 +992,7 @@ func (coll *Collection) FindOne(ctx context.Context, filter interface{}, } } - cursor, err := dispatch.Find( + batchCursor, err := driver.Find( ctx, cmd, coll.client.topology, coll.readSelector, @@ -1125,47 +1002,37 @@ func (coll *Collection) FindOne(ctx context.Context, filter interface{}, findOpts..., ) if err != nil { - return &DocumentResult{err: replaceTopologyErr(err)} + return &SingleResult{err: replaceErrors(err)} } - return &DocumentResult{cur: cursor, reg: coll.registry} + cursor, err := newCursor(batchCursor, coll.registry) + return &SingleResult{cur: cursor, reg: coll.registry, err: replaceErrors(err)} } // FindOneAndDelete find a single document and deletes it, returning the -// original in result. The document to return may be nil. -// -// A user can supply a custom context to this method, or nil to default to -// context.Background(). -// -// This method uses TransformDocument to turn the filter parameter into a -// *bsonx.Document. See TransformDocument for the list of valid types for -// filter. +// original in result. func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{}, - opts ...*options.FindOneAndDeleteOptions) *DocumentResult { + opts ...*options.FindOneAndDeleteOptions) *SingleResult { if ctx == nil { ctx = context.Background() } - var f bsonx.Doc - var err error - if filter != nil { - f, err = transformDocument(coll.registry, filter) - if err != nil { - return &DocumentResult{err: err} - } + f, err := transformDocument(coll.registry, filter) + if err != nil { + return &SingleResult{err: err} } sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } oldns := coll.namespace() wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -1177,7 +1044,7 @@ func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{} Clock: coll.client.clock, } - res, err := dispatch.FindOneAndDelete( + res, err := driver.FindOneAndDelete( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -1187,24 +1054,22 @@ func (coll *Collection) FindOneAndDelete(ctx context.Context, filter interface{} coll.registry, opts..., ) + if err != nil { - return &DocumentResult{err: replaceTopologyErr(err)} + return &SingleResult{err: replaceErrors(err)} + } + + if res.WriteConcernError != nil { + return &SingleResult{err: *convertWriteConcernError(res.WriteConcernError)} } - return &DocumentResult{rdr: res.Value, reg: coll.registry} + return &SingleResult{rdr: res.Value, reg: coll.registry} } // FindOneAndReplace finds a single document and replaces it, returning either -// the original or the replaced document. The document to return may be nil. -// -// A user can supply a custom context to this method, or nil to default to -// context.Background(). -// -// This method uses TransformDocument to turn the filter and replacement -// parameter into a *bsonx.Document. See TransformDocument for the list of -// valid types for filter and replacement. +// the original or the replaced document. func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{}, - replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *DocumentResult { + replacement interface{}, opts ...*options.FindOneAndReplaceOptions) *SingleResult { if ctx == nil { ctx = context.Background() @@ -1212,27 +1077,27 @@ func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{ f, err := transformDocument(coll.registry, filter) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } r, err := transformDocument(coll.registry, replacement) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } if len(r) > 0 && strings.HasPrefix(r[0].Key, "$") { - return &DocumentResult{err: errors.New("replacement document cannot contains keys beginning with '$")} + return &SingleResult{err: errors.New("replacement document cannot contains keys beginning with '$")} } sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -1246,7 +1111,7 @@ func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{ Clock: coll.client.clock, } - res, err := dispatch.FindOneAndReplace( + res, err := driver.FindOneAndReplace( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -1257,23 +1122,20 @@ func (coll *Collection) FindOneAndReplace(ctx context.Context, filter interface{ opts..., ) if err != nil { - return &DocumentResult{err: replaceTopologyErr(err)} + return &SingleResult{err: replaceErrors(err)} + } + + if res.WriteConcernError != nil { + return &SingleResult{err: *convertWriteConcernError(res.WriteConcernError)} } - return &DocumentResult{rdr: res.Value, reg: coll.registry} + return &SingleResult{rdr: res.Value, reg: coll.registry} } // FindOneAndUpdate finds a single document and updates it, returning either -// the original or the updated. The document to return may be nil. -// -// A user can supply a custom context to this method, or nil to default to -// context.Background(). -// -// This method uses TransformDocument to turn the filter and update parameter -// into a *bsonx.Document. See TransformDocument for the list of valid types for -// filter and update. +// the original or the updated. func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{}, - update interface{}, opts ...*options.FindOneAndUpdateOptions) *DocumentResult { + update interface{}, opts ...*options.FindOneAndUpdateOptions) *SingleResult { if ctx == nil { ctx = context.Background() @@ -1281,27 +1143,30 @@ func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{} f, err := transformDocument(coll.registry, filter) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } u, err := transformDocument(coll.registry, update) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } - if len(u) > 0 && !strings.HasPrefix(u[0].Key, "$") { - return &DocumentResult{err: errors.New("update document must contain key beginning with '$")} + err = ensureDollarKey(u) + if err != nil { + return &SingleResult{ + err: err, + } } sess := sessionFromContext(ctx) - err = coll.client.ValidSession(sess) + err = coll.client.validSession(sess) if err != nil { - return &DocumentResult{err: err} + return &SingleResult{err: err} } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -1315,7 +1180,7 @@ func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{} Clock: coll.client.clock, } - res, err := dispatch.FindOneAndUpdate( + res, err := driver.FindOneAndUpdate( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -1326,17 +1191,23 @@ func (coll *Collection) FindOneAndUpdate(ctx context.Context, filter interface{} opts..., ) if err != nil { - return &DocumentResult{err: replaceTopologyErr(err)} + return &SingleResult{err: replaceErrors(err)} } - return &DocumentResult{rdr: res.Value, reg: coll.registry} + if res.WriteConcernError != nil { + return &SingleResult{err: *convertWriteConcernError(res.WriteConcernError)} + } + + return &SingleResult{rdr: res.Value, reg: coll.registry} } // Watch returns a change stream cursor used to receive notifications of changes to the collection. +// // This method is preferred to running a raw aggregation with a $changeStream stage because it -// supports resumability in the case of some errors. +// supports resumability in the case of some errors. The collection must have read concern majority or no read concern +// for a change stream to be created successfully. func (coll *Collection) Watch(ctx context.Context, pipeline interface{}, - opts ...*options.ChangeStreamOptions) (Cursor, error) { + opts ...*options.ChangeStreamOptions) (*ChangeStream, error) { return newChangeStream(ctx, coll, pipeline, opts...) } @@ -1353,13 +1224,13 @@ func (coll *Collection) Drop(ctx context.Context) error { sess := sessionFromContext(ctx) - err := coll.client.ValidSession(sess) + err := coll.client.validSession(sess) if err != nil { return err } wc := coll.writeConcern - if sess != nil && sess.TransactionRunning() { + if sess.TransactionRunning() { wc = nil } @@ -1370,7 +1241,7 @@ func (coll *Collection) Drop(ctx context.Context) error { Session: sess, Clock: coll.client.clock, } - _, err = dispatch.DropCollection( + _, err = driver.DropCollection( ctx, cmd, coll.client.topology, coll.writeSelector, @@ -1378,7 +1249,7 @@ func (coll *Collection) Drop(ctx context.Context) error { coll.client.topology.SessionPool, ) if err != nil && !command.IsNotFound(err) { - return replaceTopologyErr(err) + return replaceErrors(err) } return nil } diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/cursor.go b/vendor/go.mongodb.org/mongo-driver/mongo/cursor.go new file mode 100644 index 0000000..53ae121 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/cursor.go @@ -0,0 +1,130 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package mongo + +import ( + "context" + "errors" + "io" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver" +) + +// Cursor is used to iterate a stream of documents. Each document is decoded into the result +// according to the rules of the bson package. +// +// A typical usage of the Cursor type would be: +// +// var cur *Cursor +// ctx := context.Background() +// defer cur.Close(ctx) +// +// for cur.Next(ctx) { +// elem := &bson.D{} +// if err := cur.Decode(elem); err != nil { +// log.Fatal(err) +// } +// +// // do something with elem.... +// } +// +// if err := cur.Err(); err != nil { +// log.Fatal(err) +// } +// +type Cursor struct { + // Current is the BSON bytes of the current document. This property is only valid until the next + // call to Next or Close. If continued access is required to the bson.Raw, you must make a copy + // of it. + Current bson.Raw + + bc batchCursor + batch *bsoncore.DocumentSequence + registry *bsoncodec.Registry + + err error +} + +func newCursor(bc batchCursor, registry *bsoncodec.Registry) (*Cursor, error) { + if registry == nil { + registry = bson.DefaultRegistry + } + if bc == nil { + return nil, errors.New("batch cursor must not be nil") + } + return &Cursor{bc: bc, registry: registry}, nil +} + +func newEmptyCursor() *Cursor { + return &Cursor{bc: driver.NewEmptyBatchCursor()} +} + +// ID returns the ID of this cursor. +func (c *Cursor) ID() int64 { return c.bc.ID() } + +// Next gets the next result from this cursor. Returns true if there were no errors and the next +// result is available for decoding. +func (c *Cursor) Next(ctx context.Context) bool { + if ctx == nil { + ctx = context.Background() + } + doc, err := c.batch.Next() + switch err { + case nil: + c.Current = bson.Raw(doc) + return true + case io.EOF: // Need to do a getMore + default: + c.err = err + return false + } + + // call the Next method in a loop until at least one document is returned in the next batch or + // the context times out. + for { + // If we don't have a next batch + if !c.bc.Next(ctx) { + // Do we have an error? If so we return false. + c.err = c.bc.Err() + if c.err != nil { + return false + } + // Is the cursor ID zero? + if c.bc.ID() == 0 { + return false + } + // empty batch, but cursor is still valid, so continue. + continue + } + + c.batch = c.bc.Batch() + doc, err = c.batch.Next() + switch err { + case nil: + c.Current = bson.Raw(doc) + return true + case io.EOF: // Empty batch so we continue + default: + c.err = err + return false + } + } +} + +// Decode will decode the current document into val. +func (c *Cursor) Decode(val interface{}) error { + return bson.UnmarshalWithRegistry(c.registry, c.Current, val) +} + +// Err returns the current error. +func (c *Cursor) Err() error { return c.err } + +// Close closes this cursor. +func (c *Cursor) Close(ctx context.Context) error { return c.bc.Close(ctx) } diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/database.go b/vendor/go.mongodb.org/mongo-driver/mongo/database.go similarity index 56% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/database.go rename to vendor/go.mongodb.org/mongo-driver/mongo/database.go index c6a4174..f457ba9 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/database.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/database.go @@ -9,16 +9,14 @@ package mongo import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // Database performs operations on a given database. @@ -88,16 +86,20 @@ func (db *Database) Collection(name string, opts ...*options.CollectionOptions) return newCollection(db, name, opts...) } -// RunCommand runs a command on the database. A user can supply a custom -// context to this method, or nil to default to context.Background(). -func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (bson.Raw, error) { +func (db *Database) processRunCommand(ctx context.Context, cmd interface{}, opts ...*options.RunCmdOptions) (command.Read, + description.ServerSelector, error) { + if ctx == nil { ctx = context.Background() } sess := sessionFromContext(ctx) - runCmd := options.MergeRunCmdOptions(opts...) + + if err := db.client.validSession(sess); err != nil { + return command.Read{}, nil, err + } + rp := runCmd.ReadPreference if rp == nil { if sess != nil && sess.TransactionRunning() { @@ -108,30 +110,74 @@ func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts } } + runCmdDoc, err := transformDocument(db.registry, cmd) + if err != nil { + return command.Read{}, nil, err + } + readSelect := description.CompositeSelector([]description.ServerSelector{ description.ReadPrefSelector(rp), description.LatencySelector(db.client.localThreshold), }) - runCmdDoc, err := transformDocument(db.registry, runCommand) + return command.Read{ + DB: db.Name(), + Command: runCmdDoc, + ReadPref: rp, + Session: sess, + Clock: db.client.clock, + }, readSelect, nil +} + +// RunCommand runs a command on the database. A user can supply a custom +// context to this method, or nil to default to context.Background(). +func (db *Database) RunCommand(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) *SingleResult { + if ctx == nil { + ctx = context.Background() + } + + readCmd, readSelect, err := db.processRunCommand(ctx, runCommand, opts...) + if err != nil { + return &SingleResult{err: err} + } + + doc, err := driver.Read(ctx, + readCmd, + db.client.topology, + readSelect, + db.client.id, + db.client.topology.SessionPool, + ) + + return &SingleResult{err: replaceErrors(err), rdr: doc, reg: db.registry} +} + +// RunCommandCursor runs a command on the database and returns a cursor over the resulting reader. A user can supply +// a custom context to this method, or nil to default to context.Background(). +func (db *Database) RunCommandCursor(ctx context.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (*Cursor, error) { + if ctx == nil { + ctx = context.Background() + } + + readCmd, readSelect, err := db.processRunCommand(ctx, runCommand, opts...) if err != nil { return nil, err } - result, err := dispatch.Read(ctx, - command.Read{ - DB: db.Name(), - Command: runCmdDoc, - ReadPref: rp, - Session: sess, - Clock: db.client.clock, - }, + + batchCursor, err := driver.ReadCursor( + ctx, + readCmd, db.client.topology, readSelect, db.client.id, db.client.topology.SessionPool, ) + if err != nil { + return nil, replaceErrors(err) + } - return result, replaceTopologyErr(err) + cursor, err := newCursor(batchCursor, db.registry) + return cursor, replaceErrors(err) } // Drop drops this database from mongodb. @@ -142,7 +188,7 @@ func (db *Database) Drop(ctx context.Context) error { sess := sessionFromContext(ctx) - err := db.client.ValidSession(sess) + err := db.client.validSession(sess) if err != nil { return err } @@ -152,7 +198,7 @@ func (db *Database) Drop(ctx context.Context) error { Session: sess, Clock: db.client.clock, } - _, err = dispatch.DropDatabase( + _, err = driver.DropDatabase( ctx, cmd, db.client.topology, db.writeSelector, @@ -160,54 +206,55 @@ func (db *Database) Drop(ctx context.Context) error { db.client.topology.SessionPool, ) if err != nil && !command.IsNotFound(err) { - return replaceTopologyErr(err) + return replaceErrors(err) } return nil } // ListCollections list collections from mongodb database. -func (db *Database) ListCollections(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (Cursor, error) { +func (db *Database) ListCollections(ctx context.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (*Cursor, error) { if ctx == nil { ctx = context.Background() } sess := sessionFromContext(ctx) - err := db.client.ValidSession(sess) + err := db.client.validSession(sess) if err != nil { return nil, err } - var filterDoc bsonx.Doc - if filter != nil { - filterDoc, err = transformDocument(db.registry, filter) - if err != nil { - return nil, err - } + filterDoc, err := transformDocument(db.registry, filter) + if err != nil { + return nil, err } cmd := command.ListCollections{ DB: db.name, Filter: filterDoc, - ReadPref: db.readPreference, + ReadPref: readpref.Primary(), // list collections must be run on a primary by default Session: sess, Clock: db.client.clock, } - cursor, err := dispatch.ListCollections( + readSelector := description.CompositeSelector([]description.ServerSelector{ + description.ReadPrefSelector(readpref.Primary()), + description.LatencySelector(db.client.localThreshold), + }) + batchCursor, err := driver.ListCollections( ctx, cmd, db.client.topology, - db.readSelector, + readSelector, db.client.id, db.client.topology.SessionPool, opts..., ) - if err != nil && !command.IsNotFound(err) { - return nil, replaceTopologyErr(err) + if err != nil { + return nil, replaceErrors(err) } - return cursor, nil - + cursor, err := newCursor(batchCursor, db.registry) + return cursor, replaceErrors(err) } // ReadConcern returns the read concern of this database. @@ -224,3 +271,12 @@ func (db *Database) ReadPreference() *readpref.ReadPref { func (db *Database) WriteConcern() *writeconcern.WriteConcern { return db.writeConcern } + +// Watch returns a change stream cursor used to receive information of changes to the database. This method is preferred +// to running a raw aggregation with a $changeStream stage because it supports resumability in the case of some errors. +// The database must have read concern majority or no read concern for a change stream to be created successfully. +func (db *Database) Watch(ctx context.Context, pipeline interface{}, + opts ...*options.ChangeStreamOptions) (*ChangeStream, error) { + + return newDbChangeStream(ctx, db, pipeline, opts...) +} diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/doc.go b/vendor/go.mongodb.org/mongo-driver/mongo/doc.go new file mode 100644 index 0000000..284e961 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/doc.go @@ -0,0 +1,81 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +// NOTE: This documentation should be kept in line with the Example* test functions. + +// Package mongo provides a MongoDB Driver API for Go. +// +// Basic usage of the driver starts with creating a Client from a connection +// string. To do so, call the NewClient and Connect functions: +// +// client, err := NewClient(options.Client().ApplyURI("mongodb://foo:bar@localhost:27017")) +// if err != nil { return err } +// ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) +// defer cancel() +// err = client.Connect(ctx) +// if err != nil { return err } +// +// This will create a new client and start monitoring the MongoDB server on localhost. +// The Database and Collection types can be used to access the database: +// +// collection := client.Database("baz").Collection("qux") +// +// A Collection can be used to query the database or insert documents: +// +// res, err := collection.InsertOne(context.Background(), bson.M{"hello": "world"}) +// if err != nil { return err } +// id := res.InsertedID +// +// Several methods return a cursor, which can be used like this: +// +// cur, err := collection.Find(context.Background(), bson.D{}) +// if err != nil { log.Fatal(err) } +// defer cur.Close(context.Background()) +// for cur.Next(context.Background()) { +// // To decode into a struct, use cursor.Decode() +// result := struct{ +// Foo string +// Bar int32 +// }{} +// err := cur.Decode(&result) +// if err != nil { log.Fatal(err) } +// // do something with result... +// +// // To get the raw bson bytes use cursor.Current +// raw := cur.Current +// // do something with raw... +// } +// if err := cur.Err(); err != nil { +// return err +// } +// +// Methods that only return a single document will return a *SingleResult, which works +// like a *sql.Row: +// +// result := struct{ +// Foo string +// Bar int32 +// }{} +// filter := bson.D{{"hello", "world"}} +// err := collection.FindOne(context.Background(), filter).Decode(&result) +// if err != nil { return err } +// // do something with result... +// +// All Client, Collection, and Database methods that take parameters of type interface{} +// will return ErrNilDocument if nil is passed in for an interface{}. +// +// Additional examples can be found under the examples directory in the driver's repository and +// on the MongoDB website. +// +// Potential DNS Issues +// +// Building with Go 1.11+ and using connection strings with the "mongodb+srv"[1] scheme is +// incompatible with some DNS servers in the wild due to the change introduced in +// https://github.com/golang/go/issues/10622. If you receive an error with the message "cannot +// unmarshal DNS message" while running an operation, we suggest you use a different DNS server. +// +// [1] See https://docs.mongodb.com/manual/reference/connection-string/#dns-seedlist-connection-format +package mongo diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/errors.go b/vendor/go.mongodb.org/mongo-driver/mongo/errors.go similarity index 65% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/errors.go rename to vendor/go.mongodb.org/mongo-driver/mongo/errors.go index 19c44f2..3957ea5 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/errors.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/errors.go @@ -11,11 +11,11 @@ import ( "errors" "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/topology" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/result" ) // ErrUnacknowledgedWrite is returned from functions that have an unacknowledged @@ -26,13 +26,59 @@ var ErrUnacknowledgedWrite = errors.New("unacknowledged write") // disconnected client var ErrClientDisconnected = errors.New("client is disconnected") -func replaceTopologyErr(err error) error { +// ErrNilDocument is returned when a user attempts to pass a nil document or filter +// to a function where the field is required. +var ErrNilDocument = errors.New("document is nil") + +// ErrEmptySlice is returned when a user attempts to pass an empty slice as input +// to a function wehere the field is required. +var ErrEmptySlice = errors.New("must provide at least one element in input slice") + +func replaceErrors(err error) error { if err == topology.ErrTopologyClosed { return ErrClientDisconnected } + if ce, ok := err.(command.Error); ok { + return CommandError{Code: ce.Code, Message: ce.Message, Labels: ce.Labels, Name: ce.Name} + } + if conv, ok := err.(driver.BulkWriteException); ok { + return BulkWriteException{ + WriteConcernError: convertWriteConcernError(conv.WriteConcernError), + WriteErrors: convertBulkWriteErrors(conv.WriteErrors), + } + } + return err } +// CommandError represents an error in execution of a command against the database. +type CommandError struct { + Code int32 + Message string + Labels []string + Name string +} + +// Error implements the error interface. +func (e CommandError) Error() string { + if e.Name != "" { + return fmt.Sprintf("(%v) %v", e.Name, e.Message) + } + return e.Message +} + +// HasErrorLabel returns true if the error contains the specified label. +func (e CommandError) HasErrorLabel(label string) bool { + if e.Labels != nil { + for _, l := range e.Labels { + if l == label { + return true + } + } + } + return false +} + // WriteError is a non-write concern failure that occurred as a result of a write // operation. type WriteError struct { @@ -78,7 +124,21 @@ type WriteConcernError struct { func (wce WriteConcernError) Error() string { return wce.Message } -func convertBulkWriteErrors(errors []dispatch.BulkWriteError) []BulkWriteError { +// WriteException is an error for a non-bulk write operation. +type WriteException struct { + WriteConcernError *WriteConcernError + WriteErrors WriteErrors +} + +func (mwe WriteException) Error() string { + var buf bytes.Buffer + fmt.Fprint(&buf, "multiple write errors: [") + fmt.Fprintf(&buf, "{%s}, ", mwe.WriteErrors) + fmt.Fprintf(&buf, "{%s}]", mwe.WriteConcernError) + return buf.String() +} + +func convertBulkWriteErrors(errors []driver.BulkWriteError) []BulkWriteError { bwErrors := make([]BulkWriteError, 0, len(errors)) for _, err := range errors { bwErrors = append(bwErrors, BulkWriteError{ @@ -152,11 +212,12 @@ func processWriteError(wce *result.WriteConcernError, wes []result.WriteError, e case err == command.ErrUnacknowledgedWrite: return rrAll, ErrUnacknowledgedWrite case err != nil: - return rrNone, replaceTopologyErr(err) - case wce != nil: - return rrMany, WriteConcernError{Code: wce.Code, Message: wce.ErrMsg} - case len(wes) > 0: - return rrMany, writeErrorsFromResult(wes) + return rrNone, replaceErrors(err) + case wce != nil || len(wes) > 0: + return rrMany, WriteException{ + WriteConcernError: convertWriteConcernError(wce), + WriteErrors: writeErrorsFromResult(wes), + } default: return rrAll, nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/index_options_builder.go b/vendor/go.mongodb.org/mongo-driver/mongo/index_options_builder.go similarity index 57% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/index_options_builder.go rename to vendor/go.mongodb.org/mongo-driver/mongo/index_options_builder.go index 566ae64..e3a61d0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/index_options_builder.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/index_options_builder.go @@ -7,130 +7,128 @@ package mongo import ( - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" ) // IndexOptionsBuilder constructs a BSON document for index options type IndexOptionsBuilder struct { - document bsonx.Doc + document bson.D } // NewIndexOptionsBuilder creates a new instance of IndexOptionsBuilder func NewIndexOptionsBuilder() *IndexOptionsBuilder { - var b IndexOptionsBuilder - b.document = bsonx.Doc{} - return &b + return &IndexOptionsBuilder{} } // Background sets the background option func (iob *IndexOptionsBuilder) Background(background bool) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"background", bsonx.Boolean(background)}) + iob.document = append(iob.document, bson.E{"background", background}) return iob } // ExpireAfterSeconds sets the expireAfterSeconds option func (iob *IndexOptionsBuilder) ExpireAfterSeconds(expireAfterSeconds int32) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"expireAfterSeconds", bsonx.Int32(expireAfterSeconds)}) + iob.document = append(iob.document, bson.E{"expireAfterSeconds", expireAfterSeconds}) return iob } // Name sets the name option func (iob *IndexOptionsBuilder) Name(name string) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"name", bsonx.String(name)}) + iob.document = append(iob.document, bson.E{"name", name}) return iob } // Sparse sets the sparse option func (iob *IndexOptionsBuilder) Sparse(sparse bool) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"sparse", bsonx.Boolean(sparse)}) + iob.document = append(iob.document, bson.E{"sparse", sparse}) return iob } // StorageEngine sets the storageEngine option -func (iob *IndexOptionsBuilder) StorageEngine(storageEngine bsonx.Doc) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"storageEngine", bsonx.Document(storageEngine)}) +func (iob *IndexOptionsBuilder) StorageEngine(storageEngine interface{}) *IndexOptionsBuilder { + iob.document = append(iob.document, bson.E{"storageEngine", storageEngine}) return iob } // Unique sets the unique option func (iob *IndexOptionsBuilder) Unique(unique bool) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"unique", bsonx.Boolean(unique)}) + iob.document = append(iob.document, bson.E{"unique", unique}) return iob } // Version sets the version option func (iob *IndexOptionsBuilder) Version(version int32) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"v", bsonx.Int32(version)}) + iob.document = append(iob.document, bson.E{"v", version}) return iob } // DefaultLanguage sets the defaultLanguage option func (iob *IndexOptionsBuilder) DefaultLanguage(defaultLanguage string) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"default_language", bsonx.String(defaultLanguage)}) + iob.document = append(iob.document, bson.E{"default_language", defaultLanguage}) return iob } // LanguageOverride sets the languageOverride option func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"language_override", bsonx.String(languageOverride)}) + iob.document = append(iob.document, bson.E{"language_override", languageOverride}) return iob } // TextVersion sets the textVersion option func (iob *IndexOptionsBuilder) TextVersion(textVersion int32) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"textIndexVersion", bsonx.Int32(textVersion)}) + iob.document = append(iob.document, bson.E{"textIndexVersion", textVersion}) return iob } // Weights sets the weights option -func (iob *IndexOptionsBuilder) Weights(weights bsonx.Doc) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"weights", bsonx.Document(weights)}) +func (iob *IndexOptionsBuilder) Weights(weights interface{}) *IndexOptionsBuilder { + iob.document = append(iob.document, bson.E{"weights", weights}) return iob } // SphereVersion sets the sphereVersion option func (iob *IndexOptionsBuilder) SphereVersion(sphereVersion int32) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"2dsphereIndexVersion", bsonx.Int32(sphereVersion)}) + iob.document = append(iob.document, bson.E{"2dsphereIndexVersion", sphereVersion}) return iob } // Bits sets the bits option func (iob *IndexOptionsBuilder) Bits(bits int32) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"bits", bsonx.Int32(bits)}) + iob.document = append(iob.document, bson.E{"bits", bits}) return iob } // Max sets the max option func (iob *IndexOptionsBuilder) Max(max float64) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"max", bsonx.Double(max)}) + iob.document = append(iob.document, bson.E{"max", max}) return iob } // Min sets the min option func (iob *IndexOptionsBuilder) Min(min float64) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"min", bsonx.Double(min)}) + iob.document = append(iob.document, bson.E{"min", min}) return iob } // BucketSize sets the bucketSize option func (iob *IndexOptionsBuilder) BucketSize(bucketSize int32) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"bucketSize", bsonx.Int32(bucketSize)}) + iob.document = append(iob.document, bson.E{"bucketSize", bucketSize}) return iob } // PartialFilterExpression sets the partialFilterExpression option -func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression bsonx.Doc) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"partialFilterExpression", bsonx.Document(partialFilterExpression)}) +func (iob *IndexOptionsBuilder) PartialFilterExpression(partialFilterExpression interface{}) *IndexOptionsBuilder { + iob.document = append(iob.document, bson.E{"partialFilterExpression", partialFilterExpression}) return iob } // Collation sets the collation option -func (iob *IndexOptionsBuilder) Collation(collation bsonx.Doc) *IndexOptionsBuilder { - iob.document = append(iob.document, bsonx.Elem{"collation", bsonx.Document(collation)}) +func (iob *IndexOptionsBuilder) Collation(collation interface{}) *IndexOptionsBuilder { + iob.document = append(iob.document, bson.E{"collation", collation}) return iob } // Build returns the BSON document from the builder -func (iob *IndexOptionsBuilder) Build() bsonx.Doc { +func (iob *IndexOptionsBuilder) Build() bson.D { return iob.document } diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/index_view.go b/vendor/go.mongodb.org/mongo-driver/mongo/index_view.go similarity index 50% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/index_view.go rename to vendor/go.mongodb.org/mongo-driver/mongo/index_view.go index 8e1b82b..0ab9ffb 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/index_view.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/index_view.go @@ -12,12 +12,15 @@ import ( "errors" "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // ErrInvalidIndexValue indicates that the index Keys document has a value that isn't either a number or a string. @@ -36,15 +39,15 @@ type IndexView struct { // IndexModel contains information about an index. type IndexModel struct { - Keys bsonx.Doc - Options bsonx.Doc + Keys interface{} + Options *options.IndexOptions } // List returns a cursor iterating over all the indexes in the collection. -func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOptions) (Cursor, error) { +func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOptions) (*Cursor, error) { sess := sessionFromContext(ctx) - err := iv.coll.client.ValidSession(sess) + err := iv.coll.client.validSession(sess) if err != nil { return nil, err } @@ -55,14 +58,27 @@ func (iv IndexView) List(ctx context.Context, opts ...*options.ListIndexesOption Clock: iv.coll.client.clock, } - return dispatch.ListIndexes( + readSelector := description.CompositeSelector([]description.ServerSelector{ + description.ReadPrefSelector(readpref.Primary()), + description.LatencySelector(iv.coll.client.localThreshold), + }) + batchCursor, err := driver.ListIndexes( ctx, listCmd, iv.coll.client.topology, - iv.coll.writeSelector, + readSelector, iv.coll.client.id, iv.coll.client.topology.SessionPool, opts..., ) + if err != nil { + if err == command.ErrEmptyCursor { + return newEmptyCursor(), nil + } + return nil, replaceErrors(err) + } + + cursor, err := newCursor(batchCursor, iv.coll.registry) + return cursor, replaceErrors(err) } // CreateOne creates a single index in the collection specified by the model. @@ -76,7 +92,7 @@ func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...*op } // CreateMany creates multiple indexes in the collection specified by the models. The names of the -// creates indexes are returned. +// created indexes are returned. func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...*options.CreateIndexesOptions) ([]string, error) { names := make([]string, 0, len(models)) indexes := bsonx.Arr{} @@ -86,16 +102,25 @@ func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts .. return nil, fmt.Errorf("index model keys cannot be nil") } - name, err := getOrGenerateIndexName(model) + name, err := getOrGenerateIndexName(iv.coll.registry, model) if err != nil { return nil, err } names = append(names, name) - index := bsonx.Doc{{"key", bsonx.Document(model.Keys)}} + keys, err := transformDocument(iv.coll.registry, model.Keys) + if err != nil { + return nil, err + } + index := bsonx.Doc{{"key", bsonx.Document(keys)}} if model.Options != nil { - index = append(index, model.Options...) + optsDoc, err := iv.createOptionsDoc(model.Options) + if err != nil { + return nil, err + } + + index = append(index, optsDoc...) } index = index.Set("name", bsonx.String(name)) @@ -104,7 +129,7 @@ func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts .. sess := sessionFromContext(ctx) - err := iv.coll.client.ValidSession(sess) + err := iv.coll.client.validSession(sess) if err != nil { return nil, err } @@ -116,7 +141,7 @@ func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts .. Clock: iv.coll.client.clock, } - _, err = dispatch.CreateIndexes( + _, err = driver.CreateIndexes( ctx, cmd, iv.coll.client.topology, iv.coll.writeSelector, @@ -131,6 +156,85 @@ func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts .. return names, nil } +func (iv IndexView) createOptionsDoc(opts *options.IndexOptions) (bsonx.Doc, error) { + optsDoc := bsonx.Doc{} + if opts.Background != nil { + optsDoc = append(optsDoc, bsonx.Elem{"background", bsonx.Boolean(*opts.Background)}) + } + if opts.ExpireAfterSeconds != nil { + optsDoc = append(optsDoc, bsonx.Elem{"expireAfterSeconds", bsonx.Int32(*opts.ExpireAfterSeconds)}) + } + if opts.Name != nil { + optsDoc = append(optsDoc, bsonx.Elem{"name", bsonx.String(*opts.Name)}) + } + if opts.Sparse != nil { + optsDoc = append(optsDoc, bsonx.Elem{"sparse", bsonx.Boolean(*opts.Sparse)}) + } + if opts.StorageEngine != nil { + doc, err := transformDocument(iv.coll.registry, opts.StorageEngine) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, bsonx.Elem{"storageEngine", bsonx.Document(doc)}) + } + if opts.Unique != nil { + optsDoc = append(optsDoc, bsonx.Elem{"unique", bsonx.Boolean(*opts.Unique)}) + } + if opts.Version != nil { + optsDoc = append(optsDoc, bsonx.Elem{"v", bsonx.Int32(*opts.Version)}) + } + if opts.DefaultLanguage != nil { + optsDoc = append(optsDoc, bsonx.Elem{"default_language", bsonx.String(*opts.DefaultLanguage)}) + } + if opts.LanguageOverride != nil { + optsDoc = append(optsDoc, bsonx.Elem{"language_override", bsonx.String(*opts.LanguageOverride)}) + } + if opts.TextVersion != nil { + optsDoc = append(optsDoc, bsonx.Elem{"textIndexVersion", bsonx.Int32(*opts.TextVersion)}) + } + if opts.Weights != nil { + weightsDoc, err := transformDocument(iv.coll.registry, opts.Weights) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, bsonx.Elem{"weights", bsonx.Document(weightsDoc)}) + } + if opts.SphereVersion != nil { + optsDoc = append(optsDoc, bsonx.Elem{"2dsphereIndexVersion", bsonx.Int32(*opts.SphereVersion)}) + } + if opts.Bits != nil { + optsDoc = append(optsDoc, bsonx.Elem{"bits", bsonx.Int32(*opts.Bits)}) + } + if opts.Max != nil { + optsDoc = append(optsDoc, bsonx.Elem{"max", bsonx.Double(*opts.Max)}) + } + if opts.Min != nil { + optsDoc = append(optsDoc, bsonx.Elem{"min", bsonx.Double(*opts.Min)}) + } + if opts.BucketSize != nil { + optsDoc = append(optsDoc, bsonx.Elem{"bucketSize", bsonx.Int32(*opts.BucketSize)}) + } + if opts.PartialFilterExpression != nil { + doc, err := transformDocument(iv.coll.registry, opts.PartialFilterExpression) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, bsonx.Elem{"partialFilterExpression", bsonx.Document(doc)}) + } + if opts.Collation != nil { + collDoc, err := bsonx.ReadDoc(opts.Collation.ToDocument()) + if err != nil { + return nil, err + } + optsDoc = append(optsDoc, bsonx.Elem{"collation", bsonx.Document(collDoc)}) + } + + return optsDoc, nil +} + // DropOne drops the index with the given name from the collection. func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.DropIndexesOptions) (bson.Raw, error) { if name == "*" { @@ -139,7 +243,7 @@ func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.D sess := sessionFromContext(ctx) - err := iv.coll.client.ValidSession(sess) + err := iv.coll.client.validSession(sess) if err != nil { return nil, err } @@ -151,7 +255,7 @@ func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.D Clock: iv.coll.client.clock, } - return dispatch.DropIndexes( + return driver.DropIndexes( ctx, cmd, iv.coll.client.topology, iv.coll.writeSelector, @@ -165,7 +269,7 @@ func (iv IndexView) DropOne(ctx context.Context, name string, opts ...*options.D func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOptions) (bson.Raw, error) { sess := sessionFromContext(ctx) - err := iv.coll.client.ValidSession(sess) + err := iv.coll.client.validSession(sess) if err != nil { return nil, err } @@ -177,7 +281,7 @@ func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOpt Clock: iv.coll.client.clock, } - return dispatch.DropIndexes( + return driver.DropIndexes( ctx, cmd, iv.coll.client.topology, iv.coll.writeSelector, @@ -187,28 +291,19 @@ func (iv IndexView) DropAll(ctx context.Context, opts ...*options.DropIndexesOpt ) } -func getOrGenerateIndexName(model IndexModel) (string, error) { - if model.Options != nil { - nameVal, err := model.Options.LookupErr("name") - - switch err.(type) { - case bsonx.KeyNotFound: - break - case nil: - if nameVal.Type() != bson.TypeString { - return "", ErrNonStringIndexName - } - - return nameVal.StringValue(), nil - default: - return "", err - } +func getOrGenerateIndexName(registry *bsoncodec.Registry, model IndexModel) (string, error) { + if model.Options != nil && model.Options.Name != nil { + return *model.Options.Name, nil } name := bytes.NewBufferString("") first := true - for _, elem := range model.Keys { + keys, err := transformDocument(registry, model.Keys) + if err != nil { + return "", err + } + for _, elem := range keys { if !first { _, err := name.WriteRune('_') if err != nil { diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/mongo.go b/vendor/go.mongodb.org/mongo-driver/mongo/mongo.go similarity index 54% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/mongo.go rename to vendor/go.mongodb.org/mongo-driver/mongo/mongo.go index d4ae628..0630efb 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/mongo.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/mongo.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package mongo +package mongo // import "go.mongodb.org/mongo-driver/mongo" import ( "context" @@ -14,12 +14,13 @@ import ( "reflect" "strings" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // Dialer is used to make network connections. @@ -54,7 +55,7 @@ type MarshalError struct { // Error implements the error interface. func (me MarshalError) Error() string { - return fmt.Sprintf("cannot transform type %s to a *bsonx.Document", reflect.TypeOf(me.Value)) + return fmt.Sprintf("cannot transform type %s to a BSON Document: %v", reflect.TypeOf(me.Value), me.Err) } // Pipeline is a type that makes creating aggregation pipelines easier. It is a @@ -62,19 +63,80 @@ func (me MarshalError) Error() string { // // Example usage: // -// mongo.Pipeline{{ -// {"$group", bson.D{{"_id", "$state"}, {"totalPop", bson.D{"$sum", "$pop"}}}}, -// {"$match": bson.D{{"totalPop", bson.D{"$gte", 10*1000*1000}}}}, -// }} +// mongo.Pipeline{ +// {{"$group", bson.D{{"_id", "$state"}, {"totalPop", bson.D{{"$sum", "$pop"}}}}}}, +// {{"$match", bson.D{{"totalPop", bson.D{{"$gte", 10*1000*1000}}}}}}, +// } // type Pipeline []bson.D +// transformAndEnsureID is a hack that makes it easy to get a RawValue as the _id value. This will +// be removed when we switch from using bsonx to bsoncore for the driver package. +func transformAndEnsureID(registry *bsoncodec.Registry, val interface{}) (bsonx.Doc, interface{}, error) { + // TODO: performance is going to be pretty bad for bsonx.Doc here since we turn it into a []byte + // only to turn it back into a bsonx.Doc. We can fix this post beta1 when we refactor the driver + // package to use bsoncore.Document instead of bsonx.Doc. + if registry == nil { + registry = bson.NewRegistryBuilder().Build() + } + switch tt := val.(type) { + case nil: + return nil, nil, ErrNilDocument + case bsonx.Doc: + val = tt.Copy() + case []byte: + // Slight optimization so we'll just use MarshalBSON and not go through the codec machinery. + val = bson.Raw(tt) + } + + // TODO(skriptble): Use a pool of these instead. + buf := make([]byte, 0, 256) + b, err := bson.MarshalAppendWithRegistry(registry, buf, val) + if err != nil { + return nil, nil, MarshalError{Value: val, Err: err} + } + + d, err := bsonx.ReadDoc(b) + if err != nil { + return nil, nil, err + } + + var id interface{} + + idx := d.IndexOf("_id") + var idElem bsonx.Elem + switch idx { + case -1: + idElem = bsonx.Elem{"_id", bsonx.ObjectID(primitive.NewObjectID())} + d = append(d, bsonx.Elem{}) + copy(d[1:], d) + d[0] = idElem + default: + idElem = d[idx] + copy(d[1:idx+1], d[0:idx]) + d[0] = idElem + } + + idBuf := make([]byte, 0, 256) + t, data, err := idElem.Value.MarshalAppendBSONValue(idBuf[:0]) + if err != nil { + return nil, nil, err + } + + err = bson.RawValue{Type: t, Value: data}.UnmarshalWithRegistry(registry, &id) + if err != nil { + return nil, nil, err + } + + return d, id, nil +} + func transformDocument(registry *bsoncodec.Registry, val interface{}) (bsonx.Doc, error) { if registry == nil { registry = bson.NewRegistryBuilder().Build() } if val == nil { - return bsonx.Doc{}, nil + return nil, ErrNilDocument } if doc, ok := val.(bsonx.Doc); ok { return doc.Copy(), nil @@ -101,7 +163,7 @@ func ensureID(d bsonx.Doc) (bsonx.Doc, interface{}) { case nil: id = elem default: - oid := objectid.New() + oid := primitive.NewObjectID() d = append(d, bsonx.Elem{"_id", bsonx.ObjectID(oid)}) id = oid } @@ -109,7 +171,10 @@ func ensureID(d bsonx.Doc) (bsonx.Doc, interface{}) { } func ensureDollarKey(doc bsonx.Doc) error { - if len(doc) > 0 && !strings.HasPrefix(doc[0].Key, "$") { + if len(doc) == 0 { + return errors.New("update document must have at least one element") + } + if !strings.HasPrefix(doc[0].Key, "$") { return errors.New("update document must contain key beginning with '$'") } return nil @@ -118,42 +183,29 @@ func ensureDollarKey(doc bsonx.Doc) error { func transformAggregatePipeline(registry *bsoncodec.Registry, pipeline interface{}) (bsonx.Arr, error) { pipelineArr := bsonx.Arr{} switch t := pipeline.(type) { - case Pipeline: - for _, d := range t { - doc, err := transformDocument(registry, d) - if err != nil { - return nil, err - } - pipelineArr = append(pipelineArr, bsonx.Document(doc)) + case bsoncodec.ValueMarshaler: + btype, val, err := t.MarshalBSONValue() + if err != nil { + return nil, err } - case bsonx.Arr: - pipelineArr = make(bsonx.Arr, len(t)) - copy(pipelineArr, t) - case []bsonx.Doc: - pipelineArr = bsonx.Arr{} - - for _, doc := range t { - pipelineArr = append(pipelineArr, bsonx.Document(doc)) + if btype != bsontype.Array { + return nil, fmt.Errorf("ValueMarshaler returned a %v, but was expecting %v", btype, bsontype.Array) } - case []interface{}: - pipelineArr = bsonx.Arr{} - - for _, val := range t { - doc, err := transformDocument(registry, val) - if err != nil { - return nil, err - } - - pipelineArr = append(pipelineArr, bsonx.Document(doc)) - } - default: - p, err := transformDocument(registry, pipeline) + err = pipelineArr.UnmarshalBSONValue(btype, val) if err != nil { return nil, err } - - for _, elem := range p { - pipelineArr = append(pipelineArr, elem.Value) + default: + val := reflect.ValueOf(t) + if !val.IsValid() || (val.Kind() != reflect.Slice && val.Kind() != reflect.Array) { + return nil, fmt.Errorf("can only transform slices and arrays into aggregation pipelines, but got %v", val.Kind()) + } + for idx := 0; idx < val.Len(); idx++ { + elem, err := transformDocument(registry, val.Index(idx).Interface()) + if err != nil { + return nil, err + } + pipelineArr = append(pipelineArr, bsonx.Document(elem)) } } diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/aggregateoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/aggregateoptions.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/options/aggregateoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/aggregateoptions.go index 30cda1b..decc8a7 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/aggregateoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/aggregateoptions.go @@ -8,7 +8,7 @@ package options import "time" -// AggregateOptions represents all possible options to the aggregate() function +// AggregateOptions represents all possible options to the Aggregate() function. type AggregateOptions struct { AllowDiskUse *bool // Enables writing to temporary files. When set to true, aggregation stages can write data to the _tmp subdirectory in the dbPath directory BatchSize *int32 // The number of documents to return per batch @@ -47,7 +47,7 @@ func (ao *AggregateOptions) SetBypassDocumentValidation(b bool) *AggregateOption return ao } -// SetCollations specifies a collation. +// SetCollation specifies a collation. // Valid for server versions >= 3.4 func (ao *AggregateOptions) SetCollation(c *Collation) *AggregateOptions { ao.Collation = c @@ -62,6 +62,7 @@ func (ao *AggregateOptions) SetMaxTime(d time.Duration) *AggregateOptions { // SetMaxAwaitTime specifies the maximum amount of time for the server to // wait on new documents to satisfy a tailable cursor query +// For servers < 3.2, this option is ignored func (ao *AggregateOptions) SetMaxAwaitTime(d time.Duration) *AggregateOptions { ao.MaxAwaitTime = &d return ao diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/bulkwriteoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/bulkwriteoptions.go similarity index 95% rename from vendor/github.com/mongodb/mongo-go-driver/options/bulkwriteoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/bulkwriteoptions.go index 790affe..86282fa 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/bulkwriteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/bulkwriteoptions.go @@ -6,6 +6,7 @@ package options +// DefaultOrdered is the default order for a BulkWriteOptions struct created from BulkWrite. var DefaultOrdered = true // BulkWriteOptions represent all possible options for a bulkWrite operation. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/changestreamoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/changestreamoptions.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/options/changestreamoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/changestreamoptions.go index ce942c1..7106a79 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/changestreamoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/changestreamoptions.go @@ -7,18 +7,18 @@ package options import ( + "go.mongodb.org/mongo-driver/bson/primitive" "time" - - "github.com/mongodb/mongo-go-driver/x/bsonx" ) // ChangeStreamOptions represents all possible options to a change stream type ChangeStreamOptions struct { - BatchSize *int32 // The number of documents to return per batch - Collation *Collation // Specifies a collation - FullDocument *FullDocument // When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. - MaxAwaitTime *time.Duration // The maximum amount of time for the server to wait on new documents to satisfy a change stream query - ResumeAfter bsonx.Doc // Specifies the logical starting point for the new change stream + BatchSize *int32 // The number of documents to return per batch + Collation *Collation // Specifies a collation + FullDocument *FullDocument // When set to ‘updateLookup’, the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. + MaxAwaitTime *time.Duration // The maximum amount of time for the server to wait on new documents to satisfy a change stream query + ResumeAfter interface{} // Specifies the logical starting point for the new change stream + StartAtOperationTime *primitive.Timestamp // Ensures that a change stream will only provide changes that occurred after a timestamp. } // ChangeStream returns a pointer to a new ChangeStreamOptions @@ -55,8 +55,14 @@ func (cso *ChangeStreamOptions) SetMaxAwaitTime(d time.Duration) *ChangeStreamOp } // SetResumeAfter specifies the logical starting point for the new change stream -func (cso *ChangeStreamOptions) SetResumeAfter(d bsonx.Doc) *ChangeStreamOptions { - cso.ResumeAfter = d +func (cso *ChangeStreamOptions) SetResumeAfter(rt interface{}) *ChangeStreamOptions { + cso.ResumeAfter = rt + return cso +} + +// SetStartAtOperationTime ensures that a change stream will only provide changes that occurred after a specified timestamp. +func (cso *ChangeStreamOptions) SetStartAtOperationTime(t *primitive.Timestamp) *ChangeStreamOptions { + cso.StartAtOperationTime = t return cso } @@ -82,6 +88,9 @@ func MergeChangeStreamOptions(opts ...*ChangeStreamOptions) *ChangeStreamOptions if cso.ResumeAfter != nil { csOpts.ResumeAfter = cso.ResumeAfter } + if cso.StartAtOperationTime != nil { + csOpts.StartAtOperationTime = cso.StartAtOperationTime + } } return csOpts diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions.go new file mode 100644 index 0000000..46ffec9 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions.go @@ -0,0 +1,633 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package options // import "go.mongodb.org/mongo-driver/mongo/options" + +import ( + "bytes" + "context" + "crypto/tls" + "crypto/x509" + "encoding/pem" + "errors" + "fmt" + "io/ioutil" + "net" + "strings" + "time" + + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/event" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/tag" + "go.mongodb.org/mongo-driver/x/network/connstring" +) + +// ContextDialer makes new network connections +type ContextDialer interface { + DialContext(ctx context.Context, network, address string) (net.Conn, error) +} + +// Credential holds auth options. +// +// AuthMechanism indicates the mechanism to use for authentication. +// Supported values include "SCRAM-SHA-256", "SCRAM-SHA-1", "MONGODB-CR", "PLAIN", "GSSAPI", and "MONGODB-X509". +// +// AuthMechanismProperties specifies additional configuration options which may be used by certain +// authentication mechanisms. Supported properties are: +// SERVICE_NAME: Specifies the name of the service. Defaults to mongodb. +// CANONICALIZE_HOST_NAME: If true, tells the driver to canonicalize the given hostname. Defaults to false. This +// property may not be used on Linux and Darwin systems and may not be used at the same time as SERVICE_HOST. +// SERVICE_REALM: Specifies the realm of the service. +// SERVICE_HOST: Specifies a hostname for GSSAPI authentication if it is different from the server's address. For +// authentication mechanisms besides GSSAPI, this property is ignored. +// +// AuthSource specifies the database to authenticate against. +// +// Username specifies the username that will be authenticated. +// +// Password specifies the password used for authentication. +// +// PasswordSet specifies if the password is actually set, since an empty password is a valid password. +type Credential struct { + AuthMechanism string + AuthMechanismProperties map[string]string + AuthSource string + Username string + Password string + PasswordSet bool +} + +// ClientOptions represents all possible options to configure a client. +type ClientOptions struct { + AppName *string + Auth *Credential + ConnectTimeout *time.Duration + Compressors []string + Dialer ContextDialer + HeartbeatInterval *time.Duration + Hosts []string + LocalThreshold *time.Duration + MaxConnIdleTime *time.Duration + MaxPoolSize *uint16 + Monitor *event.CommandMonitor + ReadConcern *readconcern.ReadConcern + ReadPreference *readpref.ReadPref + Registry *bsoncodec.Registry + ReplicaSet *string + RetryWrites *bool + ServerSelectionTimeout *time.Duration + Direct *bool + SocketTimeout *time.Duration + TLSConfig *tls.Config + WriteConcern *writeconcern.WriteConcern + ZlibLevel *int + + err error + + // Adds an option for internal use only and should not be set. This option is deprecated and is + // not part of the stability guarantee. It may be removed in the future. + AuthenticateToAnything *bool +} + +// Client creates a new ClientOptions instance. +func Client() *ClientOptions { + return new(ClientOptions) +} + +// Validate validates the client options. This method will return the first error found. +func (c *ClientOptions) Validate() error { return c.err } + +// ApplyURI parses the provided connection string and sets the values and options accordingly. +// +// Errors that occur in this method can be retrieved by calling Validate. +// +// If the URI contains ssl=true this method will overwrite TLSConfig, even if there aren't any other +// tls options specified. +func (c *ClientOptions) ApplyURI(uri string) *ClientOptions { + if c.err != nil { + return c + } + + cs, err := connstring.Parse(uri) + if err != nil { + c.err = err + return c + } + + if cs.AppName != "" { + c.AppName = &cs.AppName + } + + if cs.AuthMechanism != "" || cs.AuthMechanismProperties != nil || cs.AuthSource != "admin" || + cs.Username != "" || cs.PasswordSet { + c.Auth = &Credential{ + AuthMechanism: cs.AuthMechanism, + AuthMechanismProperties: cs.AuthMechanismProperties, + AuthSource: cs.AuthSource, + Username: cs.Username, + Password: cs.Password, + PasswordSet: cs.PasswordSet, + } + } + + if cs.ConnectSet { + direct := cs.Connect == connstring.SingleConnect + c.Direct = &direct + } + + if cs.ConnectTimeoutSet { + c.ConnectTimeout = &cs.ConnectTimeout + } + + if len(cs.Compressors) > 0 { + c.Compressors = cs.Compressors + } + + if cs.HeartbeatIntervalSet { + c.HeartbeatInterval = &cs.HeartbeatInterval + } + + c.Hosts = cs.Hosts + + if cs.LocalThresholdSet { + c.LocalThreshold = &cs.LocalThreshold + } + + if cs.MaxConnIdleTimeSet { + c.MaxConnIdleTime = &cs.MaxConnIdleTime + } + + if cs.MaxPoolSizeSet { + c.MaxPoolSize = &cs.MaxPoolSize + } + + if cs.ReadConcernLevel != "" { + c.ReadConcern = readconcern.New(readconcern.Level(cs.ReadConcernLevel)) + } + + if cs.ReadPreference != "" || len(cs.ReadPreferenceTagSets) > 0 || cs.MaxStalenessSet { + opts := make([]readpref.Option, 0, 1) + + tagSets := tag.NewTagSetsFromMaps(cs.ReadPreferenceTagSets) + if len(tagSets) > 0 { + opts = append(opts, readpref.WithTagSets(tagSets...)) + } + + if cs.MaxStaleness != 0 { + opts = append(opts, readpref.WithMaxStaleness(cs.MaxStaleness)) + } + + mode, err := readpref.ModeFromString(cs.ReadPreference) + if err != nil { + c.err = err + return c + } + + c.ReadPreference, c.err = readpref.New(mode, opts...) + if c.err != nil { + return c + } + } + + if cs.RetryWritesSet { + c.RetryWrites = &cs.RetryWrites + } + + if cs.ReplicaSet != "" { + c.ReplicaSet = &cs.ReplicaSet + } + + if cs.ServerSelectionTimeoutSet { + c.ServerSelectionTimeout = &cs.ServerSelectionTimeout + } + + if cs.SocketTimeoutSet { + c.SocketTimeout = &cs.SocketTimeout + } + + if cs.SSL { + tlsConfig := new(tls.Config) + + if cs.SSLCaFileSet { + c.err = addCACertFromFile(tlsConfig, cs.SSLCaFile) + if c.err != nil { + return c + } + } + + if cs.SSLInsecure { + tlsConfig.InsecureSkipVerify = true + } + + if cs.SSLClientCertificateKeyFileSet { + var keyPasswd string + if cs.SSLClientCertificateKeyPasswordSet && cs.SSLClientCertificateKeyPassword != nil { + keyPasswd = cs.SSLClientCertificateKeyPassword() + } + s, err := addClientCertFromFile(tlsConfig, cs.SSLClientCertificateKeyFile, keyPasswd) + if err != nil { + c.err = err + return c + } + + // If a username wasn't specified, add one from the certificate. + if c.Auth != nil && strings.ToLower(c.Auth.AuthMechanism) == "mongodb-x509" && c.Auth.Username == "" { + // The Go x509 package gives the subject with the pairs in reverse order that we want. + pairs := strings.Split(s, ",") + for left, right := 0, len(pairs)-1; left < right; left, right = left+1, right-1 { + pairs[left], pairs[right] = pairs[right], pairs[left] + } + c.Auth.Username = strings.Join(pairs, ",") + } + } + + c.TLSConfig = tlsConfig + } + + if cs.JSet || cs.WString != "" || cs.WNumberSet || cs.WTimeoutSet { + opts := make([]writeconcern.Option, 0, 1) + + if len(cs.WString) > 0 { + opts = append(opts, writeconcern.WTagSet(cs.WString)) + } else if cs.WNumberSet { + opts = append(opts, writeconcern.W(cs.WNumber)) + } + + if cs.JSet { + opts = append(opts, writeconcern.J(cs.J)) + } + + if cs.WTimeoutSet { + opts = append(opts, writeconcern.WTimeout(cs.WTimeout)) + } + + c.WriteConcern = writeconcern.New(opts...) + } + + if cs.ZlibLevelSet { + c.ZlibLevel = &cs.ZlibLevel + } + + return c +} + +// SetAppName specifies the client application name. This value is used by MongoDB when it logs +// connection information and profile information, such as slow queries. +func (c *ClientOptions) SetAppName(s string) *ClientOptions { + c.AppName = &s + return c +} + +// SetAuth sets the authentication options. +func (c *ClientOptions) SetAuth(auth Credential) *ClientOptions { + c.Auth = &auth + return c +} + +// SetCompressors sets the compressors that can be used when communicating with a server. +func (c *ClientOptions) SetCompressors(comps []string) *ClientOptions { + c.Compressors = comps + + return c +} + +// SetConnectTimeout specifies the timeout for an initial connection to a server. +// If a custom Dialer is used, this method won't be set and the user is +// responsible for setting the ConnectTimeout for connections on the dialer +// themselves. +func (c *ClientOptions) SetConnectTimeout(d time.Duration) *ClientOptions { + c.ConnectTimeout = &d + return c +} + +// SetDialer specifies a custom dialer used to dial new connections to a server. +// If a custom dialer is not set, a net.Dialer with a 300 second keepalive time will be used by default. +func (c *ClientOptions) SetDialer(d ContextDialer) *ClientOptions { + c.Dialer = d + return c +} + +// SetDirect specifies whether the driver should connect directly to the server instead of +// auto-discovering other servers in the cluster. +func (c *ClientOptions) SetDirect(b bool) *ClientOptions { + c.Direct = &b + return c +} + +// SetHeartbeatInterval specifies the interval to wait between server monitoring checks. +func (c *ClientOptions) SetHeartbeatInterval(d time.Duration) *ClientOptions { + c.HeartbeatInterval = &d + return c +} + +// SetHosts specifies the initial list of addresses from which to discover the rest of the cluster. +func (c *ClientOptions) SetHosts(s []string) *ClientOptions { + c.Hosts = s + return c +} + +// SetLocalThreshold specifies how far to distribute queries, beyond the server with the fastest +// round-trip time. If a server's roundtrip time is more than LocalThreshold slower than the +// the fastest, the driver will not send queries to that server. +func (c *ClientOptions) SetLocalThreshold(d time.Duration) *ClientOptions { + c.LocalThreshold = &d + return c +} + +// SetMaxConnIdleTime specifies the maximum number of milliseconds that a connection can remain idle +// in a connection pool before being removed and closed. +func (c *ClientOptions) SetMaxConnIdleTime(d time.Duration) *ClientOptions { + c.MaxConnIdleTime = &d + return c +} + +// SetMaxPoolSize specifies the max size of a server's connection pool. +func (c *ClientOptions) SetMaxPoolSize(u uint16) *ClientOptions { + c.MaxPoolSize = &u + return c +} + +// SetMonitor specifies a command monitor used to see commands for a client. +func (c *ClientOptions) SetMonitor(m *event.CommandMonitor) *ClientOptions { + c.Monitor = m + return c +} + +// SetReadConcern specifies the read concern. +func (c *ClientOptions) SetReadConcern(rc *readconcern.ReadConcern) *ClientOptions { + c.ReadConcern = rc + + return c +} + +// SetReadPreference specifies the read preference. +func (c *ClientOptions) SetReadPreference(rp *readpref.ReadPref) *ClientOptions { + c.ReadPreference = rp + + return c +} + +// SetRegistry specifies the bsoncodec.Registry. +func (c *ClientOptions) SetRegistry(registry *bsoncodec.Registry) *ClientOptions { + c.Registry = registry + return c +} + +// SetReplicaSet specifies the name of the replica set of the cluster. +func (c *ClientOptions) SetReplicaSet(s string) *ClientOptions { + c.ReplicaSet = &s + return c +} + +// SetRetryWrites specifies whether the client has retryable writes enabled. +func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions { + c.RetryWrites = &b + + return c +} + +// SetServerSelectionTimeout specifies a timeout in milliseconds to block for server selection. +func (c *ClientOptions) SetServerSelectionTimeout(d time.Duration) *ClientOptions { + c.ServerSelectionTimeout = &d + return c +} + +// SetSocketTimeout specifies the time in milliseconds to attempt to send or receive on a socket +// before the attempt times out. +func (c *ClientOptions) SetSocketTimeout(d time.Duration) *ClientOptions { + c.SocketTimeout = &d + return c +} + +// SetTLSConfig sets the tls.Config. +func (c *ClientOptions) SetTLSConfig(cfg *tls.Config) *ClientOptions { + c.TLSConfig = cfg + return c +} + +// SetWriteConcern sets the write concern. +func (c *ClientOptions) SetWriteConcern(wc *writeconcern.WriteConcern) *ClientOptions { + c.WriteConcern = wc + + return c +} + +// SetZlibLevel sets the level for the zlib compressor. +func (c *ClientOptions) SetZlibLevel(level int) *ClientOptions { + c.ZlibLevel = &level + + return c +} + +// MergeClientOptions combines the given connstring and *ClientOptions into a single *ClientOptions in a last one wins +// fashion. The given connstring will be used for the default options, which can be overwritten using the given +// *ClientOptions. +func MergeClientOptions(opts ...*ClientOptions) *ClientOptions { + c := Client() + + for _, opt := range opts { + if opt == nil { + continue + } + + if opt.Dialer != nil { + c.Dialer = opt.Dialer + } + if opt.AppName != nil { + c.AppName = opt.AppName + } + if opt.Auth != nil { + c.Auth = opt.Auth + } + if opt.AuthenticateToAnything != nil { + c.AuthenticateToAnything = opt.AuthenticateToAnything + } + if opt.Compressors != nil { + c.Compressors = opt.Compressors + } + if opt.ConnectTimeout != nil { + c.ConnectTimeout = opt.ConnectTimeout + } + if opt.HeartbeatInterval != nil { + c.HeartbeatInterval = opt.HeartbeatInterval + } + if len(opt.Hosts) > 0 { + c.Hosts = opt.Hosts + } + if opt.LocalThreshold != nil { + c.LocalThreshold = opt.LocalThreshold + } + if opt.MaxConnIdleTime != nil { + c.MaxConnIdleTime = opt.MaxConnIdleTime + } + if opt.MaxPoolSize != nil { + c.MaxPoolSize = opt.MaxPoolSize + } + if opt.Monitor != nil { + c.Monitor = opt.Monitor + } + if opt.ReadConcern != nil { + c.ReadConcern = opt.ReadConcern + } + if opt.ReadPreference != nil { + c.ReadPreference = opt.ReadPreference + } + if opt.Registry != nil { + c.Registry = opt.Registry + } + if opt.ReplicaSet != nil { + c.ReplicaSet = opt.ReplicaSet + } + if opt.RetryWrites != nil { + c.RetryWrites = opt.RetryWrites + } + if opt.ServerSelectionTimeout != nil { + c.ServerSelectionTimeout = opt.ServerSelectionTimeout + } + if opt.Direct != nil { + c.Direct = opt.Direct + } + if opt.SocketTimeout != nil { + c.SocketTimeout = opt.SocketTimeout + } + if opt.TLSConfig != nil { + c.TLSConfig = opt.TLSConfig + } + if opt.WriteConcern != nil { + c.WriteConcern = opt.WriteConcern + } + if opt.ZlibLevel != nil { + c.ZlibLevel = opt.ZlibLevel + } + if opt.err != nil { + c.err = opt.err + } + } + + return c +} + +// addCACertFromFile adds a root CA certificate to the configuration given a path +// to the containing file. +func addCACertFromFile(cfg *tls.Config, file string) error { + data, err := ioutil.ReadFile(file) + if err != nil { + return err + } + + certBytes, err := loadCert(data) + if err != nil { + return err + } + + cert, err := x509.ParseCertificate(certBytes) + if err != nil { + return err + } + + if cfg.RootCAs == nil { + cfg.RootCAs = x509.NewCertPool() + } + + cfg.RootCAs.AddCert(cert) + + return nil +} + +func loadCert(data []byte) ([]byte, error) { + var certBlock *pem.Block + + for certBlock == nil { + if data == nil || len(data) == 0 { + return nil, errors.New(".pem file must have both a CERTIFICATE and an RSA PRIVATE KEY section") + } + + block, rest := pem.Decode(data) + if block == nil { + return nil, errors.New("invalid .pem file") + } + + switch block.Type { + case "CERTIFICATE": + if certBlock != nil { + return nil, errors.New("multiple CERTIFICATE sections in .pem file") + } + + certBlock = block + } + + data = rest + } + + return certBlock.Bytes, nil +} + +// addClientCertFromFile adds a client certificate to the configuration given a path to the +// containing file and returns the certificate's subject name. +func addClientCertFromFile(cfg *tls.Config, clientFile, keyPasswd string) (string, error) { + data, err := ioutil.ReadFile(clientFile) + if err != nil { + return "", err + } + + var currentBlock *pem.Block + var certBlock, certDecodedBlock, keyBlock []byte + + remaining := data + start := 0 + for { + currentBlock, remaining = pem.Decode(remaining) + if currentBlock == nil { + break + } + + if currentBlock.Type == "CERTIFICATE" { + certBlock = data[start : len(data)-len(remaining)] + certDecodedBlock = currentBlock.Bytes + start += len(certBlock) + } else if strings.HasSuffix(currentBlock.Type, "PRIVATE KEY") { + if keyPasswd != "" && x509.IsEncryptedPEMBlock(currentBlock) { + var encoded bytes.Buffer + buf, err := x509.DecryptPEMBlock(currentBlock, []byte(keyPasswd)) + if err != nil { + return "", err + } + + pem.Encode(&encoded, &pem.Block{Type: currentBlock.Type, Bytes: buf}) + keyBlock = encoded.Bytes() + start = len(data) - len(remaining) + } else { + keyBlock = data[start : len(data)-len(remaining)] + start += len(keyBlock) + } + } + } + if len(certBlock) == 0 { + return "", fmt.Errorf("failed to find CERTIFICATE") + } + if len(keyBlock) == 0 { + return "", fmt.Errorf("failed to find PRIVATE KEY") + } + + cert, err := tls.X509KeyPair(certBlock, keyBlock) + if err != nil { + return "", err + } + + cfg.Certificates = append(cfg.Certificates, cert) + + // The documentation for the tls.X509KeyPair indicates that the Leaf certificate is not + // retained. + crt, err := x509.ParseCertificate(certDecodedBlock) + if err != nil { + return "", err + } + + return x509CertSubject(crt), nil +} diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions_1_10.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions_1_10.go new file mode 100644 index 0000000..97c0045 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions_1_10.go @@ -0,0 +1,9 @@ +// +build go1.10 + +package options + +import "crypto/x509" + +func x509CertSubject(cert *x509.Certificate) string { + return cert.Subject.String() +} diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions_1_9.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions_1_9.go new file mode 100644 index 0000000..385d6d3 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/clientoptions_1_9.go @@ -0,0 +1,13 @@ +// +build !go1.10 + +package options + +import ( + "crypto/x509" +) + +// We don't support version less then 1.10, but Evergreen needs to be able to compile the driver +// using version 1.8. +func x509CertSubject(cert *x509.Certificate) string { + return "" +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/collectionoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/collectionoptions.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/options/collectionoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/collectionoptions.go index 3415505..10d8827 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/collectionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/collectionoptions.go @@ -7,10 +7,10 @@ package options import ( - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" ) // CollectionOptions represent all possible options to configure a Collection. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/countoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/countoptions.go similarity index 77% rename from vendor/github.com/mongodb/mongo-go-driver/options/countoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/countoptions.go index 850095d..ebcee3b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/countoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/countoptions.go @@ -6,13 +6,15 @@ package options -// CountOptions represents all possible options to the count() function +import "time" + +// CountOptions represents all possible options to the Count() function. type CountOptions struct { - Collation *Collation // Specifies a collation - Hint interface{} // The index to use - Limit *int64 // The maximum number of documents to count - MaxTime *int64 // The maximum amount of time to allow the operation to run - Skip *int64 // The number of documents to skip before counting + Collation *Collation // Specifies a collation + Hint interface{} // The index to use + Limit *int64 // The maximum number of documents to count + MaxTime *time.Duration // The maximum amount of time to allow the operation to run + Skip *int64 // The number of documents to skip before counting } // Count returns a pointer to a new CountOptions @@ -40,8 +42,8 @@ func (co *CountOptions) SetLimit(i int64) *CountOptions { } // SetMaxTime specifies the maximum amount of time to allow the operation to run -func (co *CountOptions) SetMaxTime(i int64) *CountOptions { - co.MaxTime = &i +func (co *CountOptions) SetMaxTime(d time.Duration) *CountOptions { + co.MaxTime = &d return co } diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/dboptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/dboptions.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/options/dboptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/dboptions.go index 989cb13..57f0581 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/dboptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/dboptions.go @@ -7,10 +7,10 @@ package options import ( - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" ) // DatabaseOptions represent all possible options to configure a Database. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/deleteoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/deleteoptions.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/options/deleteoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/deleteoptions.go index 919d6b8..10f2f2e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/deleteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/deleteoptions.go @@ -6,7 +6,7 @@ package options -// DeleteOptions represents all possible options to the deleteOne() and deleteMany() functions +// DeleteOptions represents all possible options to the DeleteOne() and DeleteMany() functions. type DeleteOptions struct { Collation *Collation // Specifies a collation } diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/distinctoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/distinctoptions.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/options/distinctoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/distinctoptions.go index 8a39c0c..08ecd1d 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/distinctoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/distinctoptions.go @@ -6,10 +6,12 @@ package options -// DistinctOptions represents all possible options to the distinct() function +import "time" + +// DistinctOptions represents all possible options to the Distinct() function. type DistinctOptions struct { - Collation *Collation // Specifies a collation - MaxTime *int64 // The maximum amount of time to allow the operation to run + Collation *Collation // Specifies a collation + MaxTime *time.Duration // The maximum amount of time to allow the operation to run } // Distinct returns a pointer to a new DistinctOptions @@ -25,8 +27,8 @@ func (do *DistinctOptions) SetCollation(c *Collation) *DistinctOptions { } // SetMaxTime specifies the maximum amount of time to allow the operation to run -func (do *DistinctOptions) SetMaxTime(i int64) *DistinctOptions { - do.MaxTime = &i +func (do *DistinctOptions) SetMaxTime(d time.Duration) *DistinctOptions { + do.MaxTime = &d return do } diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/estimatedcountoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/estimatedcountoptions.go similarity index 81% rename from vendor/github.com/mongodb/mongo-go-driver/options/estimatedcountoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/estimatedcountoptions.go index 685e322..ce244de 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/estimatedcountoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/estimatedcountoptions.go @@ -6,9 +6,11 @@ package options -// EstimatedDocumentCountOptions represents all possible options to the estimatedDocumentCount() function +import "time" + +// EstimatedDocumentCountOptions represents all possible options to the EstimatedDocumentCount() function. type EstimatedDocumentCountOptions struct { - MaxTime *int64 // The maximum amount of time to allow the operation to run + MaxTime *time.Duration // The maximum amount of time to allow the operation to run } // EstimatedDocumentCount returns a pointer to a new EstimatedDocumentCountOptions @@ -17,8 +19,8 @@ func EstimatedDocumentCount() *EstimatedDocumentCountOptions { } // SetMaxTime specifies the maximum amount of time to allow the operation to run -func (eco *EstimatedDocumentCountOptions) SetMaxTime(i int64) *EstimatedDocumentCountOptions { - eco.MaxTime = &i +func (eco *EstimatedDocumentCountOptions) SetMaxTime(d time.Duration) *EstimatedDocumentCountOptions { + eco.MaxTime = &d return eco } diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/findoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/findoptions.go similarity index 98% rename from vendor/github.com/mongodb/mongo-go-driver/options/findoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/findoptions.go index d44b26f..c951516 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/findoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/findoptions.go @@ -10,7 +10,7 @@ import ( "time" ) -// FindOptions represent all possible options to the find() function. +// FindOptions represent all possible options to the Find() function. type FindOptions struct { AllowPartialResults *bool // If true, allows partial results to be returned if some shards are down. BatchSize *int32 // Specifies the number of documents to return in every batch. @@ -230,7 +230,7 @@ func MergeFindOptions(opts ...*FindOptions) *FindOptions { return fo } -// FindOneOptions represent all possible options to the findOne() function. +// FindOneOptions represent all possible options to the FindOne() function. type FindOneOptions struct { AllowPartialResults *bool // If true, allows partial results to be returned if some shards are down. BatchSize *int32 // Specifies the number of documents to return in every batch. @@ -300,6 +300,7 @@ func (f *FindOneOptions) SetMax(max interface{}) *FindOneOptions { } // SetMaxAwaitTime specifies the max amount of time for the server to wait on new documents. +// For server versions < 3.2, this option is ignored. func (f *FindOneOptions) SetMaxAwaitTime(d time.Duration) *FindOneOptions { f.MaxAwaitTime = &d return f @@ -432,7 +433,7 @@ func MergeFindOneOptions(opts ...*FindOneOptions) *FindOneOptions { return fo } -// FindOneAndReplaceOptions represent all possible options to the findOne() function. +// FindOneAndReplaceOptions represent all possible options to the FindOneAndReplace() function. type FindOneAndReplaceOptions struct { BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation. Collation *Collation // Specifies a collation to be used @@ -526,7 +527,7 @@ func MergeFindOneAndReplaceOptions(opts ...*FindOneAndReplaceOptions) *FindOneAn return fo } -// FindOneAndUpdateOptions represent all possible options to the findOne() function. +// FindOneAndUpdateOptions represent all possible options to the FindOneAndUpdate() function. type FindOneAndUpdateOptions struct { ArrayFilters *ArrayFilters // A set of filters specifying to which array elements an update should apply. BypassDocumentValidation *bool // If true, allows the write to opt out of document-level validation. @@ -543,13 +544,13 @@ func FindOneAndUpdate() *FindOneAndUpdateOptions { return &FindOneAndUpdateOptions{} } -// SetArrayFilters specifies a set of filters, which +// SetBypassDocumentValidation sets filters that specify to which array elements an update should apply. func (f *FindOneAndUpdateOptions) SetBypassDocumentValidation(b bool) *FindOneAndUpdateOptions { f.BypassDocumentValidation = &b return f } -// SetBypassDocumentValidation sets filters that specify to which array elements an update should apply. +// SetArrayFilters specifies a set of filters, which func (f *FindOneAndUpdateOptions) SetArrayFilters(filters ArrayFilters) *FindOneAndUpdateOptions { f.ArrayFilters = &filters return f @@ -629,7 +630,7 @@ func MergeFindOneAndUpdateOptions(opts ...*FindOneAndUpdateOptions) *FindOneAndU return fo } -// FindOneAndDeleteOptions represent all possible options to the findOne() function. +// FindOneAndDeleteOptions represent all possible options to the FindOneAndDelete() function. type FindOneAndDeleteOptions struct { Collation *Collation // Specifies a collation to be used MaxTime *time.Duration // Specifies the maximum amount of time to allow the query to run. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/gridfsoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/gridfsoptions.go similarity index 88% rename from vendor/github.com/mongodb/mongo-go-driver/options/gridfsoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/gridfsoptions.go index 28bc1f1..33eae3f 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/gridfsoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/gridfsoptions.go @@ -9,17 +9,18 @@ package options import ( "time" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" ) // DefaultName is the default name for a GridFS bucket. var DefaultName = "fs" // DefaultChunkSize is the default size of each file chunk in bytes. -var DefaultChunkSize int32 = 255 * 1000 +var DefaultChunkSize int32 = 255 * 1024 // 255 KiB // DefaultRevision is the default revision number for a download by name operation. var DefaultRevision int32 = -1 @@ -101,17 +102,17 @@ func MergeBucketOptions(opts ...*BucketOptions) *BucketOptions { return b } -// UploadOptions represents all possible options for a GridFS upload operation. +// UploadOptions represents all possible options for a GridFS upload operation. If a registry is nil, bson.DefaultRegistry +// will be used when converting the Metadata interface to BSON. type UploadOptions struct { - ChunkSizeBytes *int32 // Chunk size in bytes. Defaults to the chunk size of the bucket. - Metadata bsonx.Doc // User data for the 'metadata' field of the files collection document. + ChunkSizeBytes *int32 // Chunk size in bytes. Defaults to the chunk size of the bucket. + Metadata interface{} // User data for the 'metadata' field of the files collection document. + Registry *bsoncodec.Registry // The registry to use for converting filters. Defaults to bson.DefaultRegistry. } // GridFSUpload creates a new *UploadOptions func GridFSUpload() *UploadOptions { - return &UploadOptions{ - ChunkSizeBytes: &DefaultChunkSize, - } + return &UploadOptions{Registry: bson.DefaultRegistry} } // SetChunkSizeBytes sets the chunk size in bytes for the upload. Defaults to 255KB if not set. @@ -121,7 +122,7 @@ func (u *UploadOptions) SetChunkSizeBytes(i int32) *UploadOptions { } // SetMetadata specfies the metadata for the upload. -func (u *UploadOptions) SetMetadata(doc bsonx.Doc) *UploadOptions { +func (u *UploadOptions) SetMetadata(doc interface{}) *UploadOptions { u.Metadata = doc return u } @@ -142,6 +143,9 @@ func MergeUploadOptions(opts ...*UploadOptions) *UploadOptions { if opt.Metadata != nil { u.Metadata = opt.Metadata } + if opt.Registry != nil { + u.Registry = opt.Registry + } } return u diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/options/indexoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/indexoptions.go new file mode 100644 index 0000000..a0d21e8 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/indexoptions.go @@ -0,0 +1,326 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package options + +import ( + "time" +) + +// CreateIndexesOptions represents all possible options for the CreateOne() and CreateMany() functions. +type CreateIndexesOptions struct { + MaxTime *time.Duration // The maximum amount of time to allow the query to run. +} + +// CreateIndexes creates a new CreateIndexesOptions instance. +func CreateIndexes() *CreateIndexesOptions { + return &CreateIndexesOptions{} +} + +// SetMaxTime specifies the maximum amount of time to allow the query to run. +func (c *CreateIndexesOptions) SetMaxTime(d time.Duration) *CreateIndexesOptions { + c.MaxTime = &d + return c +} + +// MergeCreateIndexesOptions combines the given *CreateIndexesOptions into a single *CreateIndexesOptions in a last one +// wins fashion. +func MergeCreateIndexesOptions(opts ...*CreateIndexesOptions) *CreateIndexesOptions { + c := CreateIndexes() + for _, opt := range opts { + if opt == nil { + continue + } + if opt.MaxTime != nil { + c.MaxTime = opt.MaxTime + } + } + + return c +} + +// DropIndexesOptions represents all possible options for the DropIndexes() function. +type DropIndexesOptions struct { + MaxTime *time.Duration +} + +// DropIndexes creates a new DropIndexesOptions instance. +func DropIndexes() *DropIndexesOptions { + return &DropIndexesOptions{} +} + +// SetMaxTime specifies the maximum amount of time to allow the query to run. +func (d *DropIndexesOptions) SetMaxTime(duration time.Duration) *DropIndexesOptions { + d.MaxTime = &duration + return d +} + +// MergeDropIndexesOptions combines the given *DropIndexesOptions into a single *DropIndexesOptions in a last one +// wins fashion. +func MergeDropIndexesOptions(opts ...*DropIndexesOptions) *DropIndexesOptions { + c := DropIndexes() + for _, opt := range opts { + if opt == nil { + continue + } + if opt.MaxTime != nil { + c.MaxTime = opt.MaxTime + } + } + + return c +} + +// ListIndexesOptions represents all possible options for the ListIndexes() function. +type ListIndexesOptions struct { + BatchSize *int32 + MaxTime *time.Duration +} + +// ListIndexes creates a new ListIndexesOptions instance. +func ListIndexes() *ListIndexesOptions { + return &ListIndexesOptions{} +} + +// SetBatchSize specifies the number of documents to return in every batch. +func (l *ListIndexesOptions) SetBatchSize(i int32) *ListIndexesOptions { + l.BatchSize = &i + return l +} + +// SetMaxTime specifies the maximum amount of time to allow the query to run. +func (l *ListIndexesOptions) SetMaxTime(d time.Duration) *ListIndexesOptions { + l.MaxTime = &d + return l +} + +// MergeListIndexesOptions combines the given *ListIndexesOptions into a single *ListIndexesOptions in a last one +// wins fashion. +func MergeListIndexesOptions(opts ...*ListIndexesOptions) *ListIndexesOptions { + c := ListIndexes() + for _, opt := range opts { + if opt == nil { + continue + } + if opt.MaxTime != nil { + c.MaxTime = opt.MaxTime + } + } + + return c +} + +// IndexOptions represents all possible options to configure a new index. +type IndexOptions struct { + Background *bool + ExpireAfterSeconds *int32 + Name *string + Sparse *bool + StorageEngine interface{} + Unique *bool + Version *int32 + DefaultLanguage *string + LanguageOverride *string + TextVersion *int32 + Weights interface{} + SphereVersion *int32 + Bits *int32 + Max *float64 + Min *float64 + BucketSize *int32 + PartialFilterExpression interface{} + Collation *Collation +} + +// Index creates a new *IndexOptions +func Index() *IndexOptions { + return &IndexOptions{} +} + +// SetBackground sets the background option. If true, the server will create the index in the background and not block +// other tasks +func (i *IndexOptions) SetBackground(background bool) *IndexOptions { + i.Background = &background + return i +} + +// SetExpireAfterSeconds specifies the number of seconds for a document to remain in a collection. +func (i *IndexOptions) SetExpireAfterSeconds(seconds int32) *IndexOptions { + i.ExpireAfterSeconds = &seconds + return i +} + +// SetName specifies a name for the index. +// If not set, a name will be generated in the format "[field]_[direction]". +// If multiple indexes are created for the same key pattern with different collations, a name must be provided to avoid +// ambiguity. +func (i *IndexOptions) SetName(name string) *IndexOptions { + i.Name = &name + return i +} + +// SetSparse sets the sparse option. +// If true, the index will only reference documents with the specified field in the index. +func (i *IndexOptions) SetSparse(sparse bool) *IndexOptions { + i.Sparse = &sparse + return i +} + +// SetStorageEngine specifies the storage engine to use. +// Valid for server versions >= 3.0 +func (i *IndexOptions) SetStorageEngine(engine interface{}) *IndexOptions { + i.StorageEngine = engine + return i +} + +// SetUnique forces the index to be unique. +func (i *IndexOptions) SetUnique(unique bool) *IndexOptions { + i.Unique = &unique + return i +} + +// SetVersion specifies the index version number, either 0 or 1. +func (i *IndexOptions) SetVersion(version int32) *IndexOptions { + i.Version = &version + return i +} + +// SetDefaultLanguage specifies the default language for text indexes. +// If not set, this will default to english. +func (i *IndexOptions) SetDefaultLanguage(language string) *IndexOptions { + i.DefaultLanguage = &language + return i +} + +// SetLanguageOverride specifies the field in the document to override the language. +func (i *IndexOptions) SetLanguageOverride(override string) *IndexOptions { + i.LanguageOverride = &override + return i +} + +// SetTextVersion specifies the text index version number. +// MongoDB version 2.4 can only support version 1. +// MongoDB versions 2.6 and higher can support versions 1 or 2. +func (i *IndexOptions) SetTextVersion(version int32) *IndexOptions { + i.TextVersion = &version + return i +} + +// SetWeights specifies fields in the index and their corresponding weight values. +func (i *IndexOptions) SetWeights(weights interface{}) *IndexOptions { + i.Weights = weights + return i +} + +// SetSphereVersion specifies the 2dsphere index version number. +// MongoDB version 2.4 can only support version 1. +// MongoDB versions 2.6 and higher can support versions 1 or 2. +func (i *IndexOptions) SetSphereVersion(version int32) *IndexOptions { + i.SphereVersion = &version + return i +} + +// SetBits specifies the precision of the stored geo hash in the 2d index, from 1 to 32. +func (i *IndexOptions) SetBits(bits int32) *IndexOptions { + i.Bits = &bits + return i +} + +// SetMax specifies the maximum boundary for latitude and longitude in the 2d index. +func (i *IndexOptions) SetMax(max float64) *IndexOptions { + i.Max = &max + return i +} + +// SetMin specifies the minimum boundary for latitude and longitude in the 2d index. +func (i *IndexOptions) SetMin(min float64) *IndexOptions { + i.Min = &min + return i +} + +// SetBucketSize specifies number of units within which to group the location values in a geo haystack index. +func (i *IndexOptions) SetBucketSize(bucketSize int32) *IndexOptions { + i.BucketSize = &bucketSize + return i +} + +// SetPartialFilterExpression specifies a filter for use in a partial index. Only documents that match the filter +// expression are included in the index. +func (i *IndexOptions) SetPartialFilterExpression(expression interface{}) *IndexOptions { + i.PartialFilterExpression = expression + return i +} + +// SetCollation specifies a Collation to use for the operation. +// Valid for server versions >= 3.4 +func (i *IndexOptions) SetCollation(collation *Collation) *IndexOptions { + i.Collation = collation + return i +} + +// MergeIndexOptions combines the given *IndexOptions into a single *IndexOptions in a last one wins fashion. +func MergeIndexOptions(opts ...*IndexOptions) *IndexOptions { + i := Index() + + for _, opt := range opts { + if opt.Background != nil { + i.Background = opt.Background + } + if opt.ExpireAfterSeconds != nil { + i.ExpireAfterSeconds = opt.ExpireAfterSeconds + } + if opt.Name != nil { + i.Name = opt.Name + } + if opt.Sparse != nil { + i.Sparse = opt.Sparse + } + if opt.StorageEngine != nil { + i.StorageEngine = opt.StorageEngine + } + if opt.Unique != nil { + i.Unique = opt.Unique + } + if opt.Version != nil { + i.Version = opt.Version + } + if opt.DefaultLanguage != nil { + i.DefaultLanguage = opt.DefaultLanguage + } + if opt.LanguageOverride != nil { + i.LanguageOverride = opt.LanguageOverride + } + if opt.TextVersion != nil { + i.TextVersion = opt.TextVersion + } + if opt.Weights != nil { + i.Weights = opt.Weights + } + if opt.SphereVersion != nil { + i.SphereVersion = opt.SphereVersion + } + if opt.Bits != nil { + i.Bits = opt.Bits + } + if opt.Max != nil { + i.Max = opt.Max + } + if opt.Min != nil { + i.Min = opt.Min + } + if opt.BucketSize != nil { + i.BucketSize = opt.BucketSize + } + if opt.PartialFilterExpression != nil { + i.PartialFilterExpression = opt.PartialFilterExpression + } + if opt.Collation != nil { + i.Collation = opt.Collation + } + } + + return i +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/insertoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/insertoptions.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/options/insertoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/insertoptions.go index 064ede3..2734f15 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/insertoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/insertoptions.go @@ -6,7 +6,7 @@ package options -// InsertOneOptions represents all possible options to the insertOne() +// InsertOneOptions represents all possible options to the InsertOne() function. type InsertOneOptions struct { BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation } @@ -38,7 +38,7 @@ func MergeInsertOneOptions(opts ...*InsertOneOptions) *InsertOneOptions { return ioOpts } -// InsertManyOptions represents all possible options to the insertMany() +// InsertManyOptions represents all possible options to the InsertMany() function. type InsertManyOptions struct { BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation Ordered *bool // If true, when an insert fails, return without performing the remaining inserts. Defaults to true. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/listcollectionsoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/listcollectionsoptions.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/options/listcollectionsoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/listcollectionsoptions.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/listdatabasesoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/listdatabasesoptions.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/options/listdatabasesoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/listdatabasesoptions.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/mongooptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/mongooptions.go similarity index 67% rename from vendor/github.com/mongodb/mongo-go-driver/options/mongooptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/mongooptions.go index 5831593..cc9b462 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/mongooptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/mongooptions.go @@ -10,9 +10,9 @@ import ( "fmt" "reflect" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // Collation allows users to specify language-specific rules for string comparison, such as @@ -25,36 +25,41 @@ type Collation struct { NumericOrdering bool `bson:",omitempty"` // Whether to order numbers based on numerical order and not collation order Alternate string `bson:",omitempty"` // Whether spaces and punctuation are considered base characters MaxVariable string `bson:",omitempty"` // Which characters are affected by alternate: "shifted" + Normalization bool `bson:",omitempty"` // Causes text to be normalized into Unicode NFD Backwards bool `bson:",omitempty"` // Causes secondary differences to be considered in reverse order, as it is done in the French language } -// ToDocument converts the Collation to a *bsonx.Document -func (co *Collation) ToDocument() bsonx.Doc { - doc := bsonx.Doc{} +// ToDocument converts the Collation to a bson.Raw. +func (co *Collation) ToDocument() bson.Raw { + idx, doc := bsoncore.AppendDocumentStart(nil) if co.Locale != "" { - doc = append(doc, bsonx.Elem{"locale", bsonx.String(co.Locale)}) + doc = bsoncore.AppendStringElement(doc, "locale", co.Locale) } if co.CaseLevel { - doc = append(doc, bsonx.Elem{"caseLevel", bsonx.Boolean(true)}) + doc = bsoncore.AppendBooleanElement(doc, "caseLevel", true) } if co.CaseFirst != "" { - doc = append(doc, bsonx.Elem{"caseFirst", bsonx.String(co.CaseFirst)}) + doc = bsoncore.AppendStringElement(doc, "caseFirst", co.CaseFirst) } if co.Strength != 0 { - doc = append(doc, bsonx.Elem{"strength", bsonx.Int32(int32(co.Strength))}) + doc = bsoncore.AppendInt32Element(doc, "strength", int32(co.Strength)) } if co.NumericOrdering { - doc = append(doc, bsonx.Elem{"numericOrdering", bsonx.Boolean(true)}) + doc = bsoncore.AppendBooleanElement(doc, "numericOrdering", true) } if co.Alternate != "" { - doc = append(doc, bsonx.Elem{"alternate", bsonx.String(co.Alternate)}) + doc = bsoncore.AppendStringElement(doc, "alternate", co.Alternate) } if co.MaxVariable != "" { - doc = append(doc, bsonx.Elem{"maxVariable", bsonx.String(co.MaxVariable)}) + doc = bsoncore.AppendStringElement(doc, "maxVariable", co.MaxVariable) + } + if co.Normalization { + doc = bsoncore.AppendBooleanElement(doc, "normalization", true) } if co.Backwards { - doc = append(doc, bsonx.Elem{"backwards", bsonx.Boolean(true)}) + doc = bsoncore.AppendBooleanElement(doc, "backwards", true) } + doc, _ = bsoncore.AppendDocumentEnd(doc, idx) return doc } @@ -102,22 +107,21 @@ type ArrayFilters struct { Filters []interface{} // The filters to apply } -func (af *ArrayFilters) ToArray() (bsonx.Arr, error) { - docs := make([]bsonx.Doc, 0, len(af.Filters)) +// ToArray builds a []bson.Raw from the provided ArrayFilters. +func (af *ArrayFilters) ToArray() ([]bson.Raw, error) { + registry := af.Registry + if registry == nil { + registry = bson.DefaultRegistry + } + filters := make([]bson.Raw, 0, len(af.Filters)) for _, f := range af.Filters { - d, err := transformDocument(af.Registry, f) + filter, err := bson.MarshalWithRegistry(registry, f) if err != nil { return nil, err } - docs = append(docs, d) - } - - arr := bsonx.Arr{} - for _, doc := range docs { - arr = append(arr, bsonx.Document(doc)) + filters = append(filters, filter) } - - return arr, nil + return filters, nil } // MarshalError is returned when attempting to transform a value into a document @@ -129,30 +133,7 @@ type MarshalError struct { // Error implements the error interface. func (me MarshalError) Error() string { - return fmt.Sprintf("cannot transform type %s to a *bsonx.Document", reflect.TypeOf(me.Value)) + return fmt.Sprintf("cannot transform type %s to a bson.Raw", reflect.TypeOf(me.Value)) } var defaultRegistry = bson.DefaultRegistry - -func transformDocument(registry *bsoncodec.Registry, val interface{}) (bsonx.Doc, error) { - if val == nil { - return bsonx.Doc{}, nil - } - reg := defaultRegistry - if registry != nil { - reg = registry - } - - if bs, ok := val.([]byte); ok { - // Slight optimization so we'll just use MarshalBSON and not go through the codec machinery. - val = bson.Raw(bs) - } - - // TODO(skriptble): Use a pool of these instead. - buf := make([]byte, 0, 256) - b, err := bson.MarshalAppendWithRegistry(reg, buf, val) - if err != nil { - return nil, MarshalError{Value: val, Err: err} - } - return bsonx.ReadDoc(b) -} diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/replaceoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/replaceoptions.go similarity index 95% rename from vendor/github.com/mongodb/mongo-go-driver/options/replaceoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/replaceoptions.go index 7a8c2ba..9ff4f82 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/replaceoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/replaceoptions.go @@ -6,7 +6,7 @@ package options -// ReplaceOptions represents all possible options to the replaceOne() function +// ReplaceOptions represents all possible options to the ReplaceOne() function. type ReplaceOptions struct { BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation Collation *Collation // Specifies a collation diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/runcmdoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/runcmdoptions.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/options/runcmdoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/runcmdoptions.go index c7c696d..ec719d0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/runcmdoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/runcmdoptions.go @@ -6,7 +6,7 @@ package options -import "github.com/mongodb/mongo-go-driver/mongo/readpref" +import "go.mongodb.org/mongo-driver/mongo/readpref" // RunCmdOptions represents all possible options for a runCommand operation. type RunCmdOptions struct { diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/sessionoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/sessionoptions.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/options/sessionoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/sessionoptions.go index ffe45e6..6a7353e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/sessionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/sessionoptions.go @@ -7,9 +7,9 @@ package options import ( - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" ) // DefaultCausalConsistency is the default value for the CausalConsistency option. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/transactionoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/transactionoptions.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/options/transactionoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/transactionoptions.go index 5aec1b9..3fb502f 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/transactionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/transactionoptions.go @@ -7,9 +7,9 @@ package options import ( - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" ) // TransactionOptions represents all possible options for starting a transaction. diff --git a/vendor/github.com/mongodb/mongo-go-driver/options/updateoptions.go b/vendor/go.mongodb.org/mongo-driver/mongo/options/updateoptions.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/options/updateoptions.go rename to vendor/go.mongodb.org/mongo-driver/mongo/options/updateoptions.go index 468ccda..5c06522 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/options/updateoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/options/updateoptions.go @@ -6,7 +6,7 @@ package options -// UpdateOptions represents all possible options to the updateOne() and updateMany() functions +// UpdateOptions represents all possible options to the UpdateOne() and UpdateMany() functions. type UpdateOptions struct { ArrayFilters *ArrayFilters // A set of filters specifying to which array elements an update should apply BypassDocumentValidation *bool // If true, allows the write to opt-out of document level validation diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/readconcern/readconcern.go b/vendor/go.mongodb.org/mongo-driver/mongo/readconcern/readconcern.go similarity index 80% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/readconcern/readconcern.go rename to vendor/go.mongodb.org/mongo-driver/mongo/readconcern/readconcern.go index 3332342..bd1adfc 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/readconcern/readconcern.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/readconcern/readconcern.go @@ -4,10 +4,11 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package readconcern +package readconcern // import "go.mongodb.org/mongo-driver/mongo/readconcern" import ( - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // ReadConcern for replica sets and replica set shards determines which data to return from a query. @@ -64,13 +65,13 @@ func New(options ...Option) *ReadConcern { return concern } -// MarshalBSONElement implements the bsonx.ElementMarshaler interface. -func (rc *ReadConcern) MarshalBSONElement() (bsonx.Elem, error) { - doc := bsonx.Doc{} +// MarshalBSONValue implements the bson.ValueMarshaler interface. +func (rc *ReadConcern) MarshalBSONValue() (bsontype.Type, []byte, error) { + var elems []byte if len(rc.level) > 0 { - doc = doc.Append("level", bsonx.String(rc.level)) + elems = bsoncore.AppendStringElement(elems, "level", rc.level) } - return bsonx.Elem{"readConcern", bsonx.Document(doc)}, nil + return bsontype.EmbeddedDocument, bsoncore.BuildDocument(nil, elems), nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/mode.go b/vendor/go.mongodb.org/mongo-driver/mongo/readpref/mode.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/mode.go rename to vendor/go.mongodb.org/mongo-driver/mongo/readpref/mode.go index fe6ce38..e7030c6 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/mode.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/readpref/mode.go @@ -16,10 +16,11 @@ type Mode uint8 // Mode constants const ( + _ Mode = iota // PrimaryMode indicates that only a primary is // considered for reading. This is the default // mode. - PrimaryMode Mode = iota + PrimaryMode // PrimaryPreferredMode indicates that if a primary // is available, use it; otherwise, eligible // secondaries will be considered. @@ -51,5 +52,5 @@ func ModeFromString(mode string) (Mode, error) { case "nearest": return NearestMode, nil } - return Mode(uint8(0)), fmt.Errorf("unknown read preference %v", mode) + return Mode(0), fmt.Errorf("unknown read preference %v", mode) } diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/options.go b/vendor/go.mongodb.org/mongo-driver/mongo/readpref/options.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/options.go rename to vendor/go.mongodb.org/mongo-driver/mongo/readpref/options.go index bcd6a73..74ce61b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/options.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/readpref/options.go @@ -10,7 +10,7 @@ import ( "errors" "time" - "github.com/mongodb/mongo-go-driver/core/tag" + "go.mongodb.org/mongo-driver/tag" ) // ErrInvalidTagSet indicates that an invalid set of tags was specified. diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/readpref.go b/vendor/go.mongodb.org/mongo-driver/mongo/readpref/readpref.go similarity index 95% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/readpref.go rename to vendor/go.mongodb.org/mongo-driver/mongo/readpref/readpref.go index 2cb5f69..3fe4f3f 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/readpref/readpref.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/readpref/readpref.go @@ -4,13 +4,13 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package readpref +package readpref // import "go.mongodb.org/mongo-driver/mongo/readpref" import ( "errors" "time" - "github.com/mongodb/mongo-go-driver/core/tag" + "go.mongodb.org/mongo-driver/tag" ) var ( diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/results.go b/vendor/go.mongodb.org/mongo-driver/mongo/results.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/results.go rename to vendor/go.mongodb.org/mongo-driver/mongo/results.go index c4654c9..dfd7f3f 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/results.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/results.go @@ -9,8 +9,8 @@ package mongo import ( "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/result" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/network/result" ) // BulkWriteResult holds the result of a bulk write operation. @@ -78,6 +78,8 @@ type UpdateResult struct { MatchedCount int64 // The number of documents that were modified. ModifiedCount int64 + // The number of documents that were upserted. + UpsertedCount int64 // The identifier of the inserted document if an upsert took place. UpsertedID interface{} } diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/session.go b/vendor/go.mongodb.org/mongo-driver/mongo/session.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/session.go rename to vendor/go.mongodb.org/mongo-driver/mongo/session.go index c23908d..1d60a12 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/session.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/session.go @@ -10,14 +10,14 @@ import ( "context" "errors" - "github.com/mongodb/mongo-go-driver/bson/primitive" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/dispatch" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/mongo/driver" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // ErrWrongClient is returned when a user attempts to pass in a session created by a different client than @@ -26,7 +26,7 @@ var ErrWrongClient = errors.New("session was not created by this client") // SessionContext is a hybrid interface. It combines a context.Context with // a mongo.Session. This type can be used as a regular context.Context or -// Session type. +// Session type. It is not goroutine safe and should not be used in multiple goroutines concurrently. type SessionContext interface { context.Context Session @@ -48,8 +48,8 @@ type Session interface { StartTransaction(...*options.TransactionOptions) error AbortTransaction(context.Context) error CommitTransaction(context.Context) error - ClusterTime() bsonx.Doc - AdvanceClusterTime(bsonx.Doc) error + ClusterTime() bson.Raw + AdvanceClusterTime(bson.Raw) error OperationTime() *primitive.Timestamp AdvanceOperationTime(*primitive.Timestamp) error session() @@ -102,10 +102,10 @@ func (s *sessionImpl) AbortTransaction(ctx context.Context) error { } s.Aborting = true - _, err = dispatch.AbortTransaction(ctx, cmd, s.topo, description.WriteSelector()) + _, err = driver.AbortTransaction(ctx, cmd, s.topo, description.WriteSelector()) _ = s.Client.AbortTransaction() - return err + return replaceErrors(err) } // CommitTransaction commits the sesson's transaction. @@ -136,18 +136,18 @@ func (s *sessionImpl) CommitTransaction(ctx context.Context) error { s.Committing = false }() } - _, err = dispatch.CommitTransaction(ctx, cmd, s.topo, description.WriteSelector()) + _, err = driver.CommitTransaction(ctx, cmd, s.topo, description.WriteSelector()) if err == nil { return s.Client.CommitTransaction() } - return err + return replaceErrors(err) } -func (s *sessionImpl) ClusterTime() bsonx.Doc { +func (s *sessionImpl) ClusterTime() bson.Raw { return s.Client.ClusterTime } -func (s *sessionImpl) AdvanceClusterTime(d bsonx.Doc) error { +func (s *sessionImpl) AdvanceClusterTime(d bson.Raw) error { return s.Client.AdvanceClusterTime(d) } diff --git a/vendor/go.mongodb.org/mongo-driver/mongo/single_result.go b/vendor/go.mongodb.org/mongo-driver/mongo/single_result.go new file mode 100644 index 0000000..56a1f7c --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/mongo/single_result.go @@ -0,0 +1,93 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package mongo + +import ( + "context" + "errors" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" +) + +// ErrNoDocuments is returned by Decode when an operation that returns a +// SingleResult doesn't return any documents. +var ErrNoDocuments = errors.New("mongo: no documents in result") + +// SingleResult represents a single document returned from an operation. If +// the operation returned an error, the Err method of SingleResult will +// return that error. +type SingleResult struct { + err error + cur *Cursor + rdr bson.Raw + reg *bsoncodec.Registry +} + +// Decode will attempt to decode the first document into v. If there was an +// error from the operation that created this SingleResult then the error +// will be returned. If there were no returned documents, ErrNoDocuments is +// returned. +func (sr *SingleResult) Decode(v interface{}) error { + if sr.err != nil { + return sr.err + } + if sr.reg == nil { + return bson.ErrNilRegistry + } + switch { + case sr.rdr != nil: + if v == nil { + return nil + } + return bson.UnmarshalWithRegistry(sr.reg, sr.rdr, v) + case sr.cur != nil: + defer sr.cur.Close(context.TODO()) + if !sr.cur.Next(context.TODO()) { + if err := sr.cur.Err(); err != nil { + return err + } + return ErrNoDocuments + } + if v == nil { + return nil + } + return sr.cur.Decode(v) + } + + return ErrNoDocuments +} + +// DecodeBytes will return a copy of the document as a bson.Raw. If there was an +// error from the operation that created this SingleResult then the error +// will be returned. If there were no returned documents, ErrNoDocuments is +// returned. +func (sr *SingleResult) DecodeBytes() (bson.Raw, error) { + switch { + case sr.err != nil: + return nil, sr.err + case sr.rdr != nil: + return sr.rdr, nil + case sr.cur != nil: + defer sr.cur.Close(context.TODO()) + if !sr.cur.Next(context.TODO()) { + if err := sr.cur.Err(); err != nil { + return nil, err + } + return nil, ErrNoDocuments + } + return sr.cur.Current, nil + } + + return nil, ErrNoDocuments +} + +// Err will return the error from the operation that created this SingleResult. +// If there was no error, nil is returned. +func (sr *SingleResult) Err() error { + return sr.err +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/util.go b/vendor/go.mongodb.org/mongo-driver/mongo/util.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/util.go rename to vendor/go.mongodb.org/mongo-driver/mongo/util.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/mongo/writeconcern/writeconcern.go b/vendor/go.mongodb.org/mongo-driver/mongo/writeconcern/writeconcern.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/mongo/writeconcern/writeconcern.go rename to vendor/go.mongodb.org/mongo-driver/mongo/writeconcern/writeconcern.go index adf86d8..b2831bf 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/mongo/writeconcern/writeconcern.go +++ b/vendor/go.mongodb.org/mongo-driver/mongo/writeconcern/writeconcern.go @@ -4,20 +4,23 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package writeconcern +package writeconcern // import "go.mongodb.org/mongo-driver/mongo/writeconcern" import ( "errors" "time" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // ErrInconsistent indicates that an inconsistent write concern was specified. var ErrInconsistent = errors.New("a write concern cannot have both w=0 and j=true") +// ErrEmptyWriteConcern indicates that a write concern has no fields set. +var ErrEmptyWriteConcern = errors.New("a write concern must have at least one field set") + // ErrNegativeW indicates that a negative integer `w` field was specified. var ErrNegativeW = errors.New("write concern `w` field cannot be a negative number") @@ -32,7 +35,7 @@ type WriteConcern struct { wTimeout time.Duration } -// Option is an option to provide when creating a ReadConcern. +// Option is an option to provide when creating a WriteConcern. type Option func(concern *WriteConcern) // New constructs a new WriteConcern. @@ -85,58 +88,48 @@ func WTimeout(d time.Duration) Option { } } -// MarshalBSONElement marshals the write concern into a *bsonx.Element. -func (wc *WriteConcern) MarshalBSONElement() (bsonx.Elem, error) { +// MarshalBSONValue implements the bson.ValueMarshaler interface. +func (wc *WriteConcern) MarshalBSONValue() (bsontype.Type, []byte, error) { if !wc.IsValid() { - return bsonx.Elem{}, ErrInconsistent + return bsontype.Type(0), nil, ErrInconsistent } - elems := bsonx.Doc{} + var elems []byte if wc.w != nil { switch t := wc.w.(type) { case int: if t < 0 { - return bsonx.Elem{}, ErrNegativeW + return bsontype.Type(0), nil, ErrNegativeW } - elems = append(elems, bsonx.Elem{"w", bsonx.Int32(int32(t))}) + elems = bsoncore.AppendInt32Element(elems, "w", int32(t)) case string: - elems = append(elems, bsonx.Elem{"w", bsonx.String(t)}) + elems = bsoncore.AppendStringElement(elems, "w", string(t)) } } if wc.j { - elems = append(elems, bsonx.Elem{"j", bsonx.Boolean(wc.j)}) + elems = bsoncore.AppendBooleanElement(elems, "j", wc.j) } if wc.wTimeout < 0 { - return bsonx.Elem{}, ErrNegativeWTimeout + return bsontype.Type(0), nil, ErrNegativeWTimeout } if wc.wTimeout != 0 { - elems = append(elems, bsonx.Elem{"wtimeout", bsonx.Int64(int64(wc.wTimeout / time.Millisecond))}) + elems = bsoncore.AppendInt64Element(elems, "wtimeout", int64(wc.wTimeout/time.Millisecond)) } - return bsonx.Elem{"writeConcern", bsonx.Document(elems)}, nil -} - -// AcknowledgedElement returns true if a BSON element for a write concern represents an acknowledged write concern. -// The element's value must be a document representing a write concern. -func AcknowledgedElement(elem bsonx.Elem) bool { - wcDoc := elem.Value.Document() - wVal, err := wcDoc.LookupErr("w") - if err != nil { - // key w not found --> acknowledged - return true + if len(elems) == 0 { + return bsontype.Type(0), nil, ErrEmptyWriteConcern } - - return wVal.Int32() != 0 + return bsontype.EmbeddedDocument, bsoncore.BuildDocument(nil, elems), nil } -// AcknowledgedElementRaw returns true if a BSON RawValue for a write concern represents an acknowledged write concern. +// AcknowledgedValue returns true if a BSON RawValue for a write concern represents an acknowledged write concern. // The element's value must be a document representing a write concern. -func AcknowledgedElementRaw(rawv bson.RawValue) bool { +func AcknowledgedValue(rawv bson.RawValue) bool { doc, ok := bsoncore.Value{Type: rawv.Type, Data: rawv.Value}.DocumentOK() if !ok { return false @@ -187,6 +180,36 @@ func (wc *WriteConcern) IsValid() bool { return true } +// GetW returns the write concern w level. +func (wc *WriteConcern) GetW() interface{} { + return wc.w +} + +// GetJ returns the write concern journaling level. +func (wc *WriteConcern) GetJ() bool { + return wc.j +} + +// GetWTimeout returns the write concern timeout. +func (wc *WriteConcern) GetWTimeout() time.Duration { + return wc.wTimeout +} + +// WithOptions returns a copy of this WriteConcern with the options set. +func (wc *WriteConcern) WithOptions(options ...Option) *WriteConcern { + if wc == nil { + return New(options...) + } + newWC := &WriteConcern{} + *newWC = *wc + + for _, option := range options { + option(newWC) + } + + return newWC +} + // AckWrite returns true if a write concern represents an acknowledged write func AckWrite(wc *WriteConcern) bool { return wc == nil || wc.Acknowledged() diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/tag/tag.go b/vendor/go.mongodb.org/mongo-driver/tag/tag.go similarity index 95% rename from vendor/github.com/mongodb/mongo-go-driver/core/tag/tag.go rename to vendor/go.mongodb.org/mongo-driver/tag/tag.go index c10bd3e..13bf562 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/tag/tag.go +++ b/vendor/go.mongodb.org/mongo-driver/tag/tag.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package tag +package tag // import "go.mongodb.org/mongo-driver/tag" // Tag is a name/vlaue pair. type Tag struct { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/version/version.go b/vendor/go.mongodb.org/mongo-driver/version/version.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/core/version/version.go rename to vendor/go.mongodb.org/mongo-driver/version/version.go index 46e6bf6..5d71a11 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/version/version.go +++ b/vendor/go.mongodb.org/mongo-driver/version/version.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package version +package version // import "go.mongodb.org/mongo-driver/version" // Driver is the current version of the driver. -var Driver = "v0.0.18" +var Driver = "v1.0.1" diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/array.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/array.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/array.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/array.go index 8001d70..80359e8 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/array.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/array.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package bsonx +package bsonx // import "go.mongodb.org/mongo-driver/x/bsonx" import ( "bytes" @@ -12,8 +12,8 @@ import ( "fmt" "strconv" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // ErrNilArray indicates that an operation was attempted on a nil *Array. diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/bsoncore.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/bsoncore.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/bsoncore.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/bsoncore.go index 526c8d1..20b4667 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/bsoncore.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/bsoncore.go @@ -23,7 +23,7 @@ // given dst slice. If the slice has enough capacity, it will not grow the // slice. The Append*Element functions within this package operate in the same // way, but additionally append the BSON type and the key before the value. -package bsoncore +package bsoncore // import "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" import ( "bytes" @@ -31,9 +31,8 @@ import ( "math" "time" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // AppendType will append t to dst and return the extended buffer. @@ -222,6 +221,18 @@ func BuildDocument(dst []byte, elems []byte) []byte { return dst } +// BuildDocumentFromElements will create a document with the given slice of elements and will append +// it to dst and return the extended buffer. +func BuildDocumentFromElements(dst []byte, elems ...[]byte) []byte { + idx, dst := ReserveLength(dst) + for _, elem := range elems { + dst = append(dst, elem...) + } + dst = append(dst, 0x00) + dst = UpdateLength(dst, idx, int32(len(dst[idx:]))) + return dst +} + // ReadDocument will read a document from src. If there are not enough bytes it // will return false. func ReadDocument(src []byte) (doc Document, rem []byte, ok bool) { return readLengthBytes(src) } @@ -301,21 +312,21 @@ func AppendUndefinedElement(dst []byte, key string) []byte { } // AppendObjectID will append oid to dst and return the extended buffer. -func AppendObjectID(dst []byte, oid objectid.ObjectID) []byte { return append(dst, oid[:]...) } +func AppendObjectID(dst []byte, oid primitive.ObjectID) []byte { return append(dst, oid[:]...) } // AppendObjectIDElement will append a BSON ObjectID element using key and oid to dst // and return the extended buffer. -func AppendObjectIDElement(dst []byte, key string, oid objectid.ObjectID) []byte { +func AppendObjectIDElement(dst []byte, key string, oid primitive.ObjectID) []byte { return AppendObjectID(AppendHeader(dst, bsontype.ObjectID, key), oid) } // ReadObjectID will read an ObjectID from src. If there are not enough bytes it // will return false. -func ReadObjectID(src []byte) (objectid.ObjectID, []byte, bool) { +func ReadObjectID(src []byte) (primitive.ObjectID, []byte, bool) { if len(src) < 12 { - return objectid.ObjectID{}, src, false + return primitive.ObjectID{}, src, false } - var oid objectid.ObjectID + var oid primitive.ObjectID copy(oid[:], src[0:12]) return oid, src[12:], true } @@ -405,26 +416,26 @@ func ReadRegex(src []byte) (pattern, options string, rem []byte, ok bool) { } // AppendDBPointer will append ns and oid to dst and return the extended buffer. -func AppendDBPointer(dst []byte, ns string, oid objectid.ObjectID) []byte { +func AppendDBPointer(dst []byte, ns string, oid primitive.ObjectID) []byte { return append(appendstring(dst, ns), oid[:]...) } // AppendDBPointerElement will append a BSON DBPointer element using key, ns, // and oid to dst and return the extended buffer. -func AppendDBPointerElement(dst []byte, key, ns string, oid objectid.ObjectID) []byte { +func AppendDBPointerElement(dst []byte, key, ns string, oid primitive.ObjectID) []byte { return AppendDBPointer(AppendHeader(dst, bsontype.DBPointer, key), ns, oid) } // ReadDBPointer will read a ns and oid from src. If there are not enough bytes it // will return false. -func ReadDBPointer(src []byte) (ns string, oid objectid.ObjectID, rem []byte, ok bool) { +func ReadDBPointer(src []byte) (ns string, oid primitive.ObjectID, rem []byte, ok bool) { ns, rem, ok = readstring(src) if !ok { - return "", objectid.ObjectID{}, src, false + return "", primitive.ObjectID{}, src, false } oid, rem, ok = ReadObjectID(rem) if !ok { - return "", objectid.ObjectID{}, src, false + return "", primitive.ObjectID{}, src, false } return ns, oid, rem, true } @@ -542,31 +553,31 @@ func AppendInt64Element(dst []byte, key string, i64 int64) []byte { func ReadInt64(src []byte) (int64, []byte, bool) { return readi64(src) } // AppendDecimal128 will append d128 to dst and return the extended buffer. -func AppendDecimal128(dst []byte, d128 decimal.Decimal128) []byte { +func AppendDecimal128(dst []byte, d128 primitive.Decimal128) []byte { high, low := d128.GetBytes() return appendu64(appendu64(dst, low), high) } -// AppendDecimal128Element will append a BSON decimal128 element using key and +// AppendDecimal128Element will append a BSON primitive.28 element using key and // d128 to dst and return the extended buffer. -func AppendDecimal128Element(dst []byte, key string, d128 decimal.Decimal128) []byte { +func AppendDecimal128Element(dst []byte, key string, d128 primitive.Decimal128) []byte { return AppendDecimal128(AppendHeader(dst, bsontype.Decimal128, key), d128) } -// ReadDecimal128 will read a decimal.Decimal128 from src. If there are not enough bytes it +// ReadDecimal128 will read a primitive.Decimal128 from src. If there are not enough bytes it // will return false. -func ReadDecimal128(src []byte) (decimal.Decimal128, []byte, bool) { +func ReadDecimal128(src []byte) (primitive.Decimal128, []byte, bool) { l, rem, ok := readu64(src) if !ok { - return decimal.Decimal128{}, src, false + return primitive.Decimal128{}, src, false } h, rem, ok := readu64(rem) if !ok { - return decimal.Decimal128{}, src, false + return primitive.Decimal128{}, src, false } - return decimal.NewDecimal128(h, l), rem, true + return primitive.NewDecimal128(h, l), rem, true } // AppendMaxKeyElement will append a BSON max key element using key to dst diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/document.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/document.go similarity index 99% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/document.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/document.go index e655a51..ff7cdf9 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/document.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/document.go @@ -14,7 +14,7 @@ import ( "strconv" "github.com/go-stack/stack" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsontype" ) // DocumentValidationError is an error type returned when attempting to validate a document. diff --git a/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/document_sequence.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/document_sequence.go new file mode 100644 index 0000000..0751466 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/document_sequence.go @@ -0,0 +1,167 @@ +package bsoncore + +import ( + "errors" + "io" + + "go.mongodb.org/mongo-driver/bson/bsontype" +) + +// DocumentSequenceStyle is used to represent how a document sequence is laid out in a slice of +// bytes. +type DocumentSequenceStyle uint32 + +// These constants are the valid styles for a DocumentSequence. +const ( + _ DocumentSequenceStyle = iota + SequenceStyle + ArrayStyle +) + +// DocumentSequence represents a sequence of documents. The Style field indicates how the documents +// are laid out inside of the Data field. +type DocumentSequence struct { + Style DocumentSequenceStyle + Data []byte + Pos int +} + +// ErrCorruptedDocument is returned when a full document couldn't be read from the sequence. +var ErrCorruptedDocument = errors.New("invalid DocumentSequence: corrupted document") + +// ErrNonDocument is returned when a DocumentSequence contains a non-document BSON value. +var ErrNonDocument = errors.New("invalid DocumentSequence: a non-document value was found in sequence") + +// ErrInvalidDocumentSequenceStyle is returned when an unknown DocumentSequenceStyle is set on a +// DocumentSequence. +var ErrInvalidDocumentSequenceStyle = errors.New("invalid DocumentSequenceStyle") + +// DocumentCount returns the number of documents in the sequence. +func (ds *DocumentSequence) DocumentCount() int { + if ds == nil { + return 0 + } + switch ds.Style { + case SequenceStyle: + var count int + var ok bool + rem := ds.Data + for len(rem) > 0 { + _, rem, ok = ReadDocument(rem) + if !ok { + return 0 + } + count++ + } + return count + case ArrayStyle: + _, rem, ok := ReadLength(ds.Data) + if !ok { + return 0 + } + + var count int + for len(rem) > 1 { + _, rem, ok = ReadElement(rem) + if !ok { + return 0 + } + count++ + } + return count + default: + return 0 + } +} + +//ResetIterator resets the iteration point for the Next method to the beginning of the document +//sequence. +func (ds *DocumentSequence) ResetIterator() { + if ds == nil { + return + } + ds.Pos = 0 +} + +// documents returns a slice of the documents. If nil either the Data field is also nil or could not +// be properly read. +func (ds *DocumentSequence) documents() ([]Document, error) { + if ds == nil { + return nil, nil + } + switch ds.Style { + case SequenceStyle: + rem := ds.Data + var docs []Document + var doc Document + var ok bool + for { + doc, rem, ok = ReadDocument(rem) + if !ok { + if len(rem) == 0 { + break + } + return nil, ErrCorruptedDocument + } + docs = append(docs, doc) + } + return docs, nil + case ArrayStyle: + if len(ds.Data) == 0 { + return nil, nil + } + vals, err := Document(ds.Data).Values() + if err != nil { + return nil, ErrCorruptedDocument + } + docs := make([]Document, 0, len(vals)) + for _, v := range vals { + if v.Type != bsontype.EmbeddedDocument { + return nil, ErrNonDocument + } + docs = append(docs, v.Data) + } + return docs, nil + default: + return nil, ErrInvalidDocumentSequenceStyle + } +} + +// Next retrieves the next document from this sequence and returns it. This method will return +// io.EOF when it has reached the end of the sequence. +func (ds *DocumentSequence) Next() (Document, error) { + if ds == nil || ds.Pos >= len(ds.Data) { + return nil, io.EOF + } + switch ds.Style { + case SequenceStyle: + doc, _, ok := ReadDocument(ds.Data[ds.Pos:]) + if !ok { + return nil, ErrCorruptedDocument + } + ds.Pos += len(doc) + return doc, nil + case ArrayStyle: + if ds.Pos < 4 { + if len(ds.Data) < 4 { + return nil, ErrCorruptedDocument + } + ds.Pos = 4 // Skip the length of the document + } + if len(ds.Data[ds.Pos:]) == 1 && ds.Data[ds.Pos] == 0x00 { + return nil, io.EOF // At the end of the document + } + elem, _, ok := ReadElement(ds.Data[ds.Pos:]) + if !ok { + return nil, ErrCorruptedDocument + } + ds.Pos += len(elem) + val := elem.Value() + if val.Type != bsontype.EmbeddedDocument { + return nil, ErrNonDocument + } + return val.Data, nil + default: + return nil, ErrInvalidDocumentSequenceStyle + } +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/element.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/element.go similarity index 98% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/element.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/element.go index ccf9075..3acb422 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/element.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/element.go @@ -10,7 +10,7 @@ import ( "bytes" "fmt" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsontype" ) // MalformedElementError represents a class of errors that RawElement methods return. diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/tables.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/tables.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/tables.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/tables.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/value.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/value.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/value.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/value.go index e33133c..e5cdf8c 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore/value.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/bsoncore/value.go @@ -17,9 +17,8 @@ import ( "time" "unicode/utf8" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // ElementTypeError specifies that a method to obtain a BSON value an incorrect type was called on a bson.Value. @@ -151,7 +150,7 @@ func (v Value) String() string { if !ok { return "" } - return fmt.Sprintf(`{"$oid":%s}`, oid.Hex()) + return fmt.Sprintf(`{"$oid":"%s"}`, oid.Hex()) case bsontype.Boolean: b, ok := v.BooleanOK() if !ok { @@ -403,7 +402,7 @@ func (v Value) BinaryOK() (subtype byte, data []byte, ok bool) { // ObjectID returns the BSON objectid value the Value represents. It panics if the value is a BSON // type other than objectid. -func (v Value) ObjectID() objectid.ObjectID { +func (v Value) ObjectID() primitive.ObjectID { if v.Type != bsontype.ObjectID { panic(ElementTypeError{"bsoncore.Value.ObjectID", v.Type}) } @@ -416,13 +415,13 @@ func (v Value) ObjectID() objectid.ObjectID { // ObjectIDOK is the same as ObjectID, except it returns a boolean instead of // panicking. -func (v Value) ObjectIDOK() (objectid.ObjectID, bool) { +func (v Value) ObjectIDOK() (primitive.ObjectID, bool) { if v.Type != bsontype.ObjectID { - return objectid.ObjectID{}, false + return primitive.ObjectID{}, false } oid, _, ok := ReadObjectID(v.Data) if !ok { - return objectid.ObjectID{}, false + return primitive.ObjectID{}, false } return oid, true } @@ -533,7 +532,7 @@ func (v Value) RegexOK() (pattern, options string, ok bool) { // DBPointer returns the BSON dbpointer value the Value represents. It panics if the value is a BSON // type other than DBPointer. -func (v Value) DBPointer() (string, objectid.ObjectID) { +func (v Value) DBPointer() (string, primitive.ObjectID) { if v.Type != bsontype.DBPointer { panic(ElementTypeError{"bsoncore.Value.DBPointer", v.Type}) } @@ -546,13 +545,13 @@ func (v Value) DBPointer() (string, objectid.ObjectID) { // DBPointerOK is the same as DBPoitner, except that it returns a boolean // instead of panicking. -func (v Value) DBPointerOK() (string, objectid.ObjectID, bool) { +func (v Value) DBPointerOK() (string, primitive.ObjectID, bool) { if v.Type != bsontype.DBPointer { - return "", objectid.ObjectID{}, false + return "", primitive.ObjectID{}, false } ns, pointer, _, ok := ReadDBPointer(v.Data) if !ok { - return "", objectid.ObjectID{}, false + return "", primitive.ObjectID{}, false } return ns, pointer, true } @@ -715,7 +714,7 @@ func (v Value) Int64OK() (int64, bool) { // Decimal128 returns the decimal the Value represents. It panics if the value is a BSON type other than // decimal. -func (v Value) Decimal128() decimal.Decimal128 { +func (v Value) Decimal128() primitive.Decimal128 { if v.Type != bsontype.Decimal128 { panic(ElementTypeError{"bsoncore.Value.Decimal128", v.Type}) } @@ -728,13 +727,13 @@ func (v Value) Decimal128() decimal.Decimal128 { // Decimal128OK is the same as Decimal128, except that it returns a boolean // instead of panicking. -func (v Value) Decimal128OK() (decimal.Decimal128, bool) { +func (v Value) Decimal128OK() (primitive.Decimal128, bool) { if v.Type != bsontype.Decimal128 { - return decimal.Decimal128{}, false + return primitive.Decimal128{}, false } d128, _, ok := ReadDecimal128(v.Data) if !ok { - return decimal.Decimal128{}, false + return primitive.Decimal128{}, false } return d128, true } diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/constructor.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/constructor.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/constructor.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/constructor.go index b01c984..a8be859 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/constructor.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/constructor.go @@ -11,10 +11,8 @@ import ( "math" "time" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/bson/primitive" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" ) // IDoc is the interface implemented by Doc and MDoc. It allows either of these types to be provided @@ -75,7 +73,7 @@ func Binary(subtype byte, data []byte) Val { func Undefined() Val { return Val{t: bsontype.Undefined} } // ObjectID constructs a BSON objectid Value. -func ObjectID(oid objectid.ObjectID) Val { +func ObjectID(oid primitive.ObjectID) Val { v := Val{t: bsontype.ObjectID} copy(v.bootstrap[0:12], oid[:]) return v @@ -108,7 +106,7 @@ func Regex(pattern, options string) Val { } // DBPointer constructs a BSON dbpointer Value. -func DBPointer(ns string, ptr objectid.ObjectID) Val { +func DBPointer(ns string, ptr primitive.ObjectID) Val { dbptr := primitive.DBPointer{DB: ns, Pointer: ptr} return Val{t: bsontype.DBPointer, primitive: dbptr} } @@ -157,7 +155,7 @@ func Timestamp(t, i uint32) Val { func Int64(i64 int64) Val { return Val{t: bsontype.Int64}.writei64(i64) } // Decimal128 constructs a BSON decimal128 Value. -func Decimal128(d128 decimal.Decimal128) Val { +func Decimal128(d128 primitive.Decimal128) Val { return Val{t: bsontype.Decimal128, primitive: d128} } diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/document.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/document.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/document.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/document.go index a8e543b..6d2c6f3 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/document.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/document.go @@ -11,8 +11,8 @@ import ( "errors" "fmt" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // ErrNilDocument indicates that an operation was attempted on a nil *bson.Document. @@ -81,7 +81,7 @@ func (d Doc) Prepend(key string, val Val) Doc { // does not have an element with that key, the element is appended to the // document instead. func (d Doc) Set(key string, val Val) Doc { - idx := d.indexOf(key) + idx := d.IndexOf(key) if idx == -1 { return append(d, Elem{Key: key, Value: val}) } @@ -89,7 +89,9 @@ func (d Doc) Set(key string, val Val) Doc { return d } -func (d Doc) indexOf(key string) int { +// IndexOf returns the index of the first element with a key of key, or -1 if no element with a key +// was found. +func (d Doc) IndexOf(key string) int { for i, e := range d { if e.Key == key { return i @@ -100,7 +102,7 @@ func (d Doc) indexOf(key string) int { // Delete removes the element with key if it exists and returns the updated Doc. func (d Doc) Delete(key string) Doc { - idx := d.indexOf(key) + idx := d.IndexOf(key) if idx == -1 { return d } @@ -147,7 +149,7 @@ func (d Doc) LookupElementErr(key ...string) (Elem, error) { var elem Elem var err error - idx := d.indexOf(key[0]) + idx := d.IndexOf(key[0]) if idx == -1 { return Elem{}, KeyNotFound{Key: key} } @@ -240,6 +242,14 @@ func (d *Doc) UnmarshalBSON(b []byte) error { return nil } +// UnmarshalBSONValue implements the bson.ValueUnmarshaler interface. +func (d *Doc) UnmarshalBSONValue(t bsontype.Type, data []byte) error { + if t != bsontype.EmbeddedDocument { + return fmt.Errorf("cannot unmarshal %s into a bsonx.Doc", t) + } + return d.UnmarshalBSON(data) +} + // Equal compares this document to another, returning true if they are equal. func (d Doc) Equal(id IDoc) bool { switch tt := id.(type) { diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/element.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/element.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/element.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/element.go index b45dbea..66054b2 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/element.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/element.go @@ -9,7 +9,7 @@ package bsonx import ( "fmt" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsontype" ) const validateMaxDepthDefault = 2048 diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/mdocument.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/mdocument.go similarity index 98% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/mdocument.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/mdocument.go index e483556..380c862 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/mdocument.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/mdocument.go @@ -10,8 +10,8 @@ import ( "bytes" "fmt" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // MDoc is an unordered, type safe, concise BSON document representation. This type should not be diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/primitive_codecs.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/primitive_codecs.go similarity index 74% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/primitive_codecs.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/primitive_codecs.go index 5bd4d46..0992536 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/primitive_codecs.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/primitive_codecs.go @@ -11,30 +11,53 @@ import ( "fmt" "reflect" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/bson/bsonrw" - "github.com/mongodb/mongo-go-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/bsontype" ) +var primitiveCodecs PrimitiveCodecs + var tDocument = reflect.TypeOf((Doc)(nil)) var tMDoc = reflect.TypeOf((MDoc)(nil)) var tArray = reflect.TypeOf((Arr)(nil)) +var tValue = reflect.TypeOf(Val{}) +var tElementSlice = reflect.TypeOf(([]Elem)(nil)) // PrimitiveCodecs is a namespace for all of the default bsoncodec.Codecs for the primitive types // defined in this package. type PrimitiveCodecs struct{} +// RegisterPrimitiveCodecs will register the encode and decode methods attached to PrimitiveCodecs +// with the provided RegistryBuilder. if rb is nil, a new empty RegistryBuilder will be created. +func (pc PrimitiveCodecs) RegisterPrimitiveCodecs(rb *bsoncodec.RegistryBuilder) { + if rb == nil { + panic(errors.New("argument to RegisterPrimitiveCodecs must not be nil")) + } + + rb. + RegisterEncoder(tDocument, bsoncodec.ValueEncoderFunc(pc.DocumentEncodeValue)). + RegisterEncoder(tArray, bsoncodec.ValueEncoderFunc(pc.ArrayEncodeValue)). + RegisterEncoder(tValue, bsoncodec.ValueEncoderFunc(pc.ValueEncodeValue)). + RegisterEncoder(tElementSlice, bsoncodec.ValueEncoderFunc(pc.ElementSliceEncodeValue)). + RegisterDecoder(tDocument, bsoncodec.ValueDecoderFunc(pc.DocumentDecodeValue)). + RegisterDecoder(tArray, bsoncodec.ValueDecoderFunc(pc.ArrayDecodeValue)). + RegisterDecoder(tValue, bsoncodec.ValueDecoderFunc(pc.ValueDecodeValue)). + RegisterDecoder(tElementSlice, bsoncodec.ValueDecoderFunc(pc.ElementSliceDecodeValue)) +} + // DocumentEncodeValue is the ValueEncoderFunc for *Document. -func (pc PrimitiveCodecs) DocumentEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - doc, ok := i.(Doc) - if !ok { - return bsoncodec.ValueEncoderError{Name: "DocumentEncodeValue", Types: []interface{}{(Doc)(nil), (*Doc)(nil)}, Received: i} +func (pc PrimitiveCodecs) DocumentEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tDocument { + return bsoncodec.ValueEncoderError{Name: "DocumentEncodeValue", Types: []reflect.Type{tDocument}, Received: val} } - if doc == nil { + if val.IsNil() { return vw.WriteNull() } + doc := val.Interface().(Doc) + dw, err := vw.WriteDocument() if err != nil { return err @@ -44,15 +67,15 @@ func (pc PrimitiveCodecs) DocumentEncodeValue(ec bsoncodec.EncodeContext, vw bso } // DocumentDecodeValue is the ValueDecoderFunc for *Document. -func (pc PrimitiveCodecs) DocumentDecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - doc, ok := i.(*Doc) - if !ok { - return bsoncodec.ValueDecoderError{Name: "DocumentDecodeValue", Types: []interface{}{(*Doc)(nil)}, Received: i} +func (pc PrimitiveCodecs) DocumentDecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tDocument { + return bsoncodec.ValueDecoderError{Name: "DocumentDecodeValue", Types: []reflect.Type{tDocument}, Received: val} } - if doc == nil { - return errors.New("DocumentDecodeValue can only be used to decode non-nil *Doc") - } + return pc.documentDecodeValue(dctx, vr, val.Addr().Interface().(*Doc)) +} + +func (pc PrimitiveCodecs) documentDecodeValue(dctx bsoncodec.DecodeContext, vr bsonrw.ValueReader, doc *Doc) error { dr, err := vr.ReadDocument() if err != nil { @@ -63,23 +86,17 @@ func (pc PrimitiveCodecs) DocumentDecodeValue(dctx bsoncodec.DecodeContext, vr b } // ArrayEncodeValue is the ValueEncoderFunc for *Array. -func (pc PrimitiveCodecs) ArrayEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var arr Arr - switch tt := i.(type) { - case Arr: - if tt == nil { - return vw.WriteNull() - } - arr = tt - case *Arr: - if tt == nil { - return vw.WriteNull() - } - arr = *tt - default: - return bsoncodec.ValueEncoderError{Name: "ArrayEncodeValue", Types: []interface{}{(Arr)(nil), (*Arr)(nil)}, Received: i} +func (pc PrimitiveCodecs) ArrayEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tArray { + return bsoncodec.ValueEncoderError{Name: "ArrayEncodeValue", Types: []reflect.Type{tArray}, Received: val} } + if val.IsNil() { + return vw.WriteNull() + } + + arr := val.Interface().(Arr) + aw, err := vw.WriteArray() if err != nil { return err @@ -102,14 +119,9 @@ func (pc PrimitiveCodecs) ArrayEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw } // ArrayDecodeValue is the ValueDecoderFunc for *Array. -func (pc PrimitiveCodecs) ArrayDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - parr, ok := i.(*Arr) - if !ok { - return bsoncodec.ValueDecoderError{Name: "ArrayDecodeValue", Types: []interface{}{(*Arr)(nil)}, Received: i} - } - - if parr == nil { - return errors.New("ArrayDecodeValue can only be used to decode non-nil *Arr") +func (pc PrimitiveCodecs) ArrayDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tArray { + return bsoncodec.ValueDecoderError{Name: "ArrayDecodeValue", Types: []reflect.Type{tArray}, Received: val} } ar, err := vr.ReadArray() @@ -117,10 +129,11 @@ func (pc PrimitiveCodecs) ArrayDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw return err } - if *parr == nil { - *parr = make(Arr, 0) + if val.IsNil() { + val.Set(reflect.MakeSlice(tArray, 0, 0)) } - *parr = (*parr)[:0] + val.SetLen(0) + for { vr, err := ar.ReadValue() if err == bsonrw.ErrEOA { @@ -130,47 +143,48 @@ func (pc PrimitiveCodecs) ArrayDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw return err } - var val Val - err = pc.valueDecodeValue(dc, vr, &val) + var elem Val + err = pc.valueDecodeValue(dc, vr, &elem) if err != nil { return err } - *parr = append(*parr, val) + val.Set(reflect.Append(val, reflect.ValueOf(elem))) } return nil } // ElementSliceEncodeValue is the ValueEncoderFunc for []*Element. -func (pc PrimitiveCodecs) ElementSliceEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var slce []Elem - switch t := i.(type) { - case []Elem: - slce = t - case *[]Elem: - if t == nil { - return vw.WriteNull() - } - slce = *t - default: - return bsoncodec.ValueEncoderError{ - Name: "ElementSliceEncodeValue", - Types: []interface{}{[]Elem{}, (*[]Elem)(nil)}, - Received: i, - } +func (pc PrimitiveCodecs) ElementSliceEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tElementSlice { + return bsoncodec.ValueEncoderError{Name: "ElementSliceEncodeValue", Types: []reflect.Type{tElementSlice}, Received: val} } - return pc.DocumentEncodeValue(ec, vw, Doc(slce)) + if val.IsNil() { + return vw.WriteNull() + } + + return pc.DocumentEncodeValue(ec, vw, val.Convert(tDocument)) } // ElementSliceDecodeValue is the ValueDecoderFunc for []*Element. -func (pc PrimitiveCodecs) ElementSliceDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { +func (pc PrimitiveCodecs) ElementSliceDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tElementSlice { + return bsoncodec.ValueDecoderError{Name: "ElementSliceDecodeValue", Types: []reflect.Type{tElementSlice}, Received: val} + } + + if val.IsNil() { + val.Set(reflect.MakeSlice(val.Type(), 0, 0)) + } + + val.SetLen(0) + dr, err := vr.ReadDocument() if err != nil { return err } - elems := make([]Elem, 0) + elems := make([]reflect.Value, 0) for { key, vr, err := dr.ReadElement() if err == bsonrw.ErrEOD { @@ -186,52 +200,31 @@ func (pc PrimitiveCodecs) ElementSliceDecodeValue(dc bsoncodec.DecodeContext, vr return err } - elems = append(elems, elem) + elems = append(elems, reflect.ValueOf(elem)) } - target, ok := i.(*[]Elem) - if !ok || target == nil { - return bsoncodec.ValueDecoderError{Name: "ElementSliceDecodeValue", Types: []interface{}{(*[]Elem)(nil)}, Received: i} - } - - *target = elems + val.Set(reflect.Append(val, elems...)) return nil } // ValueEncodeValue is the ValueEncoderFunc for *Value. -func (pc PrimitiveCodecs) ValueEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, i interface{}) error { - var val Val - switch tt := i.(type) { - case Val: - val = tt - case *Val: - if tt == nil { - return vw.WriteNull() - } - val = *tt - default: - return bsoncodec.ValueEncoderError{ - Name: "ValueEncodeValue", - Types: []interface{}{Val{}, (*Val)(nil)}, - Received: i, - } +func (pc PrimitiveCodecs) ValueEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != tValue { + return bsoncodec.ValueEncoderError{Name: "ValueEncodeValue", Types: []reflect.Type{tValue}, Received: val} } - return pc.encodeValue(ec, vw, val) + v := val.Interface().(Val) + + return pc.encodeValue(ec, vw, v) } // ValueDecodeValue is the ValueDecoderFunc for *Value. -func (pc PrimitiveCodecs) ValueDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, i interface{}) error { - pval, ok := i.(*Val) - if !ok { - return bsoncodec.ValueDecoderError{Name: "ValueDecodeValue", Types: []interface{}{(*Val)(nil)}, Received: i} - } - - if pval == nil { - return errors.New("ValueDecodeValue can only be used to decode non-nil *Value") +func (pc PrimitiveCodecs) ValueDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != tValue { + return bsoncodec.ValueDecoderError{Name: "ValueDecodeValue", Types: []reflect.Type{tValue}, Received: val} } - return pc.valueDecodeValue(dc, vr, pval) + return pc.valueDecodeValue(dc, vr, val.Addr().Interface().(*Val)) } // encodeDocument is a separate function that we use because CodeWithScope @@ -301,18 +294,18 @@ func (pc PrimitiveCodecs) elementDecodeValue(dc bsoncodec.DecodeContext, vr bson val = String(str) case bsontype.EmbeddedDocument: var embeddedDoc Doc - err := pc.DocumentDecodeValue(dc, vr, &embeddedDoc) + err := pc.documentDecodeValue(dc, vr, &embeddedDoc) if err != nil { return err } val = Document(embeddedDoc) case bsontype.Array: - var arr Arr - err := pc.ArrayDecodeValue(dc, vr, &arr) + arr := reflect.New(tArray).Elem() + err := pc.ArrayDecodeValue(dc, vr, arr) if err != nil { return err } - val = Array(arr) + val = Array(arr.Interface().(Arr)) case bsontype.Binary: data, subtype, err := vr.ReadBinary() if err != nil { @@ -443,14 +436,14 @@ func (pc PrimitiveCodecs) encodeValue(ec bsoncodec.EncodeContext, vw bsonrw.Valu if err != nil { break } - err = encoder.EncodeValue(ec, vw, val.Document()) + err = encoder.EncodeValue(ec, vw, reflect.ValueOf(val.Document())) case bsontype.Array: var encoder bsoncodec.ValueEncoder encoder, err = ec.LookupEncoder(tArray) if err != nil { break } - err = encoder.EncodeValue(ec, vw, val.Array()) + err = encoder.EncodeValue(ec, vw, reflect.ValueOf(val.Array())) case bsontype.Binary: // TODO: FIX THIS (╯°□°)╯︵ ┻━┻ subtype, data := val.Binary() @@ -518,18 +511,18 @@ func (pc PrimitiveCodecs) valueDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw *val = String(str) case bsontype.EmbeddedDocument: var embeddedDoc Doc - err := pc.DocumentDecodeValue(dc, vr, &embeddedDoc) + err := pc.documentDecodeValue(dc, vr, &embeddedDoc) if err != nil { return err } *val = Document(embeddedDoc) case bsontype.Array: - var arr Arr - err := pc.ArrayDecodeValue(dc, vr, &arr) + arr := reflect.New(tArray).Elem() + err := pc.ArrayDecodeValue(dc, vr, arr) if err != nil { return err } - *val = Array(arr) + *val = Array(arr.Interface().(Arr)) case bsontype.Binary: data, subtype, err := vr.ReadBinary() if err != nil { diff --git a/vendor/go.mongodb.org/mongo-driver/x/bsonx/registry.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/registry.go new file mode 100644 index 0000000..ac21df2 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/registry.go @@ -0,0 +1,22 @@ +package bsonx + +import ( + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" +) + +// DefaultRegistry is the default bsoncodec.Registry. It contains the default codecs and the +// primitive codecs. +var DefaultRegistry = NewRegistryBuilder().Build() + +// NewRegistryBuilder creates a new RegistryBuilder configured with the default encoders and +// deocders from the bsoncodec.DefaultValueEncoders and bsoncodec.DefaultValueDecoders types and the +// PrimitiveCodecs type in this package. +func NewRegistryBuilder() *bsoncodec.RegistryBuilder { + rb := bsoncodec.NewRegistryBuilder() + bsoncodec.DefaultValueEncoders{}.RegisterDefaultEncoders(rb) + bsoncodec.DefaultValueDecoders{}.RegisterDefaultDecoders(rb) + bson.PrimitiveCodecs{}.RegisterPrimitiveCodecs(rb) + primitiveCodecs.RegisterPrimitiveCodecs(rb) + return rb +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/value.go b/vendor/go.mongodb.org/mongo-driver/x/bsonx/value.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/x/bsonx/value.go rename to vendor/go.mongodb.org/mongo-driver/x/bsonx/value.go index 91dfcf9..39a8736 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/x/bsonx/value.go +++ b/vendor/go.mongodb.org/mongo-driver/x/bsonx/value.go @@ -14,11 +14,9 @@ import ( "math" "time" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/decimal" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/bson/primitive" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" ) // Val represents a BSON value. @@ -162,64 +160,69 @@ func (v Val) Interface() interface{} { // MarshalBSONValue implements the bsoncodec.ValueMarshaler interface. func (v Val) MarshalBSONValue() (bsontype.Type, []byte, error) { + return v.MarshalAppendBSONValue(nil) +} + +// MarshalAppendBSONValue is similar to MarshalBSONValue, but allows the caller to specify a slice +// to add the bytes to. +func (v Val) MarshalAppendBSONValue(dst []byte) (bsontype.Type, []byte, error) { t := v.Type() - var data []byte switch v.Type() { case bsontype.Double: - data = bsoncore.AppendDouble(data, v.Double()) + dst = bsoncore.AppendDouble(dst, v.Double()) case bsontype.String: - data = bsoncore.AppendString(data, v.String()) + dst = bsoncore.AppendString(dst, v.String()) case bsontype.EmbeddedDocument: switch v.primitive.(type) { case Doc: - t, data, _ = v.primitive.(Doc).MarshalBSONValue() // Doc.MarshalBSONValue never returns an error. + t, dst, _ = v.primitive.(Doc).MarshalBSONValue() // Doc.MarshalBSONValue never returns an error. case MDoc: - t, data, _ = v.primitive.(MDoc).MarshalBSONValue() // MDoc.MarshalBSONValue never returns an error. + t, dst, _ = v.primitive.(MDoc).MarshalBSONValue() // MDoc.MarshalBSONValue never returns an error. } case bsontype.Array: - t, data, _ = v.Array().MarshalBSONValue() // Arr.MarshalBSON never returns an error. + t, dst, _ = v.Array().MarshalBSONValue() // Arr.MarshalBSON never returns an error. case bsontype.Binary: subtype, bindata := v.Binary() - data = bsoncore.AppendBinary(data, subtype, bindata) + dst = bsoncore.AppendBinary(dst, subtype, bindata) case bsontype.Undefined: case bsontype.ObjectID: - data = bsoncore.AppendObjectID(data, v.ObjectID()) + dst = bsoncore.AppendObjectID(dst, v.ObjectID()) case bsontype.Boolean: - data = bsoncore.AppendBoolean(data, v.Boolean()) + dst = bsoncore.AppendBoolean(dst, v.Boolean()) case bsontype.DateTime: - data = bsoncore.AppendDateTime(data, int64(v.DateTime())) + dst = bsoncore.AppendDateTime(dst, int64(v.DateTime())) case bsontype.Null: case bsontype.Regex: pattern, options := v.Regex() - data = bsoncore.AppendRegex(data, pattern, options) + dst = bsoncore.AppendRegex(dst, pattern, options) case bsontype.DBPointer: ns, ptr := v.DBPointer() - data = bsoncore.AppendDBPointer(data, ns, ptr) + dst = bsoncore.AppendDBPointer(dst, ns, ptr) case bsontype.JavaScript: - data = bsoncore.AppendJavaScript(data, string(v.JavaScript())) + dst = bsoncore.AppendJavaScript(dst, string(v.JavaScript())) case bsontype.Symbol: - data = bsoncore.AppendSymbol(data, string(v.Symbol())) + dst = bsoncore.AppendSymbol(dst, string(v.Symbol())) case bsontype.CodeWithScope: code, doc := v.CodeWithScope() var scope []byte scope, _ = doc.MarshalBSON() // Doc.MarshalBSON never returns an error. - data = bsoncore.AppendCodeWithScope(data, code, scope) + dst = bsoncore.AppendCodeWithScope(dst, code, scope) case bsontype.Int32: - data = bsoncore.AppendInt32(data, v.Int32()) + dst = bsoncore.AppendInt32(dst, v.Int32()) case bsontype.Timestamp: t, i := v.Timestamp() - data = bsoncore.AppendTimestamp(data, t, i) + dst = bsoncore.AppendTimestamp(dst, t, i) case bsontype.Int64: - data = bsoncore.AppendInt64(data, v.Int64()) + dst = bsoncore.AppendInt64(dst, v.Int64()) case bsontype.Decimal128: - data = bsoncore.AppendDecimal128(data, v.Decimal128()) + dst = bsoncore.AppendDecimal128(dst, v.Decimal128()) case bsontype.MinKey: case bsontype.MaxKey: default: panic(fmt.Errorf("invalid BSON type %v", t)) } - return t, data, nil + return t, dst, nil } // UnmarshalBSONValue implements the bsoncodec.ValueUnmarshaler interface. @@ -259,7 +262,7 @@ func (v *Val) UnmarshalBSONValue(t bsontype.Type, data []byte) error { case bsontype.Undefined: *v = Undefined() case bsontype.ObjectID: - var oid objectid.ObjectID + var oid primitive.ObjectID oid, rem, ok = bsoncore.ReadObjectID(data) *v = ObjectID(oid) case bsontype.Boolean: @@ -278,7 +281,7 @@ func (v *Val) UnmarshalBSONValue(t bsontype.Type, data []byte) error { *v = Regex(pattern, options) case bsontype.DBPointer: var ns string - var ptr objectid.ObjectID + var ptr primitive.ObjectID ns, ptr, rem, ok = bsoncore.ReadDBPointer(data) *v = DBPointer(ns, ptr) case bsontype.JavaScript: @@ -309,7 +312,7 @@ func (v *Val) UnmarshalBSONValue(t bsontype.Type, data []byte) error { i64, rem, ok = bsoncore.ReadInt64(data) *v = Int64(i64) case bsontype.Decimal128: - var d128 decimal.Decimal128 + var d128 primitive.Decimal128 d128, rem, ok = bsoncore.ReadDecimal128(data) *v = Decimal128(d128) case bsontype.MinKey: @@ -501,22 +504,22 @@ func (v Val) UndefinedOK() bool { // ObjectID returns the BSON ObjectID the Value represents. It panics if the value is a BSON type // other than ObjectID. -func (v Val) ObjectID() objectid.ObjectID { +func (v Val) ObjectID() primitive.ObjectID { if v.t != bsontype.ObjectID { panic(ElementTypeError{"bson.Value.ObjectID", v.t}) } - var oid objectid.ObjectID + var oid primitive.ObjectID copy(oid[:], v.bootstrap[:12]) return oid } // ObjectIDOK is the same as ObjectID, except it returns a boolean instead of // panicking. -func (v Val) ObjectIDOK() (objectid.ObjectID, bool) { +func (v Val) ObjectIDOK() (primitive.ObjectID, bool) { if v.t != bsontype.ObjectID { - return objectid.ObjectID{}, false + return primitive.ObjectID{}, false } - var oid objectid.ObjectID + var oid primitive.ObjectID copy(oid[:], v.bootstrap[:12]) return oid, true } @@ -617,7 +620,7 @@ func (v Val) RegexOK() (pattern, options string, ok bool) { // DBPointer returns the BSON dbpointer the Value represents. It panics if the value is a BSON type // other than dbpointer. -func (v Val) DBPointer() (string, objectid.ObjectID) { +func (v Val) DBPointer() (string, primitive.ObjectID) { if v.t != bsontype.DBPointer { panic(ElementTypeError{"bson.Value.DBPointer", v.t}) } @@ -627,9 +630,9 @@ func (v Val) DBPointer() (string, objectid.ObjectID) { // DBPointerOK is the same as DBPoitner, except that it returns a boolean // instead of panicking. -func (v Val) DBPointerOK() (string, objectid.ObjectID, bool) { +func (v Val) DBPointerOK() (string, primitive.ObjectID, bool) { if v.t != bsontype.DBPointer { - return "", objectid.ObjectID{}, false + return "", primitive.ObjectID{}, false } dbptr := v.primitive.(primitive.DBPointer) return dbptr.DB, dbptr.Pointer, true @@ -757,20 +760,20 @@ func (v Val) Int64OK() (int64, bool) { // Decimal128 returns the BSON decimal128 value the Value represents. It panics if the value is a // BSON type other than decimal128. -func (v Val) Decimal128() decimal.Decimal128 { +func (v Val) Decimal128() primitive.Decimal128 { if v.t != bsontype.Decimal128 { panic(ElementTypeError{"bson.Value.Decimal128", v.t}) } - return v.primitive.(decimal.Decimal128) + return v.primitive.(primitive.Decimal128) } // Decimal128OK is the same as Decimal128, except that it returns a boolean // instead of panicking. -func (v Val) Decimal128OK() (decimal.Decimal128, bool) { +func (v Val) Decimal128OK() (primitive.Decimal128, bool) { if v.t != bsontype.Decimal128 { - return decimal.Decimal128{}, false + return primitive.Decimal128{}, false } - return v.primitive.(decimal.Decimal128), true + return v.primitive.(primitive.Decimal128), true } // MinKey returns the BSON minkey the Value represents. It panics if the value is a BSON type diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/README.md b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/README.md new file mode 100644 index 0000000..7588f4a --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/README.md @@ -0,0 +1,11 @@ +MongoDB Go Driver Low-Level Driver Library +========================================== +The packages within this library allow users to build applications using a low-level driver +interface. Knowledge of the internals of a MongoDB driver are assumed, so this library contains +advanced features. The aim of this library is to provide an easy to use, high performance +implementation of a low-level driver. + +This Library's API is experimental and subject to change. Packages may be changed or removed without +notice. These APIs are not stable and do not guarantee backward compatibility. + +**THIS LIBRARY IS EXPERIMENTAL AND SUBJECT TO CHANGE.** diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/abort_transaction.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/abort_transaction.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/abort_transaction.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/abort_transaction.go index 7af7249..acfed55 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/abort_transaction.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/abort_transaction.go @@ -4,15 +4,15 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // AbortTransaction handles the full cycle dispatch and execution of abortting a transaction diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/aggregate.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/aggregate.go new file mode 100644 index 0000000..3c217e6 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/aggregate.go @@ -0,0 +1,200 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driver + +import ( + "context" + "fmt" + "time" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" +) + +// Aggregate handles the full cycle dispatch and execution of an aggregate command against the provided +// topology. +func Aggregate( + ctx context.Context, + cmd command.Aggregate, + topo *topology.Topology, + readSelector, writeSelector description.ServerSelector, + clientID uuid.UUID, + pool *session.Pool, + registry *bsoncodec.Registry, + opts ...*options.AggregateOptions, +) (*BatchCursor, error) { + + dollarOut := cmd.HasDollarOut() + + var ss *topology.SelectedServer + var err error + switch dollarOut { + case true: + ss, err = topo.SelectServer(ctx, writeSelector) + if err != nil { + return nil, err + } + case false: + ss, err = topo.SelectServer(ctx, readSelector) + if err != nil { + return nil, err + } + } + + desc := ss.Description() + conn, err := ss.Connection(ctx) + if err != nil { + return nil, err + } + + defer conn.Close() + + rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session) + if err != nil { + return nil, err + } + cmd.ReadPref = rp + + // If no explicit session and deployment supports sessions, start implicit session. + if cmd.Session == nil && topo.SupportsSessions() { + cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) + if err != nil { + return nil, err + } + } + + aggOpts := options.MergeAggregateOptions(opts...) + + if aggOpts.AllowDiskUse != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"allowDiskUse", bsonx.Boolean(*aggOpts.AllowDiskUse)}) + } + var batchSize int32 + if aggOpts.BatchSize != nil { + elem := bsonx.Elem{"batchSize", bsonx.Int32(*aggOpts.BatchSize)} + cmd.Opts = append(cmd.Opts, elem) + cmd.CursorOpts = append(cmd.CursorOpts, elem) + batchSize = *aggOpts.BatchSize + } + if aggOpts.BypassDocumentValidation != nil && desc.WireVersion.Includes(4) { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"bypassDocumentValidation", bsonx.Boolean(*aggOpts.BypassDocumentValidation)}) + } + if aggOpts.Collation != nil { + if desc.WireVersion.Max < 5 { + return nil, ErrCollation + } + collDoc, err := bsonx.ReadDoc(aggOpts.Collation.ToDocument()) + if err != nil { + return nil, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) + } + if aggOpts.MaxTime != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*aggOpts.MaxTime / time.Millisecond))}) + } + if aggOpts.MaxAwaitTime != nil { + // specified as maxTimeMS on getMore commands + cmd.CursorOpts = append(cmd.CursorOpts, bsonx.Elem{ + "maxTimeMS", bsonx.Int64(int64(*aggOpts.MaxAwaitTime / time.Millisecond)), + }) + } + if aggOpts.Comment != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"comment", bsonx.String(*aggOpts.Comment)}) + } + if aggOpts.Hint != nil { + hintElem, err := interfaceToElement("hint", aggOpts.Hint, registry) + if err != nil { + return nil, err + } + + cmd.Opts = append(cmd.Opts, hintElem) + } + + res, err := cmd.RoundTrip(ctx, desc, conn) + if err != nil { + if wce, ok := err.(result.WriteConcernError); ok { + ss.ProcessWriteConcernError(&wce) + } + closeImplicitSession(cmd.Session) + return nil, err + } + + if desc.WireVersion.Max < 4 { + return buildLegacyCommandBatchCursor(res, batchSize, ss.Server) + } + + return NewBatchCursor(bsoncore.Document(res), cmd.Session, cmd.Clock, ss.Server, cmd.CursorOpts...) +} + +func buildLegacyCommandBatchCursor(rdr bson.Raw, batchSize int32, server *topology.Server) (*BatchCursor, error) { + firstBatchDocs, ns, cursorID, err := getCursorValues(rdr) + if err != nil { + return nil, err + } + + return NewLegacyBatchCursor(ns, cursorID, firstBatchDocs, 0, batchSize, server) +} + +// get the firstBatch, cursor ID, and namespace from a bson.Raw +// +// TODO(GODRIVER-617): Change the documents return value into []bsoncore.Document. +func getCursorValues(result bson.Raw) (*bsoncore.DocumentSequence, command.Namespace, int64, error) { + cur, err := result.LookupErr("cursor") + if err != nil { + return nil, command.Namespace{}, 0, err + } + if cur.Type != bson.TypeEmbeddedDocument { + return nil, command.Namespace{}, 0, fmt.Errorf("cursor should be an embedded document but it is a BSON %s", cur.Type) + } + + elems, err := cur.Document().Elements() + if err != nil { + return nil, command.Namespace{}, 0, err + } + + var ok bool + var namespace command.Namespace + var cursorID int64 + batch := new(bsoncore.DocumentSequence) + + for _, elem := range elems { + switch elem.Key() { + case "firstBatch": + arr, ok := elem.Value().ArrayOK() + if !ok { + return nil, command.Namespace{}, 0, fmt.Errorf("firstBatch should be an array but it is a BSON %s", elem.Value().Type) + } + + batch.Style = bsoncore.ArrayStyle + batch.Data = arr + case "ns": + if elem.Value().Type != bson.TypeString { + return nil, command.Namespace{}, 0, fmt.Errorf("namespace should be a string but it is a BSON %s", elem.Value().Type) + } + namespace = command.ParseNamespace(elem.Value().StringValue()) + err = namespace.Validate() + if err != nil { + return nil, command.Namespace{}, 0, err + } + case "id": + cursorID, ok = elem.Value().Int64OK() + if !ok { + return nil, command.Namespace{}, 0, fmt.Errorf("id should be an int64 but it is a BSON %s", elem.Value().Type) + } + } + } + + return batch, namespace, cursorID, nil +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/auth.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/auth.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/auth.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/auth.go index 0e8c537..4464e38 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/auth.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/auth.go @@ -10,11 +10,11 @@ import ( "context" "fmt" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/connection" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // AuthenticatorFactory constructs an authenticator. @@ -95,10 +95,11 @@ func RegisterAuthenticatorFactory(name string, factory AuthenticatorFactory) { // function. DBUser is optional but must be of the form ; // if non-empty, then the connection will do SASL mechanism negotiation. type HandshakeOptions struct { - AppName string - Authenticator Authenticator - Compressors []string - DBUser string + AppName string + Authenticator Authenticator + Compressors []string + DBUser string + PerformAuthentication func(description.Server) bool } // Handshaker creates a connection handshaker for the given authenticator. @@ -114,9 +115,21 @@ func Handshaker(h connection.Handshaker, options *HandshakeOptions) connection.H return description.Server{}, newAuthError("handshake failure", err) } - err = options.Authenticator.Auth(ctx, desc, rw) - if err != nil { - return description.Server{}, newAuthError("auth error", err) + performAuth := options.PerformAuthentication + if performAuth == nil { + performAuth = func(serv description.Server) bool { + return serv.Kind == description.RSPrimary || + serv.Kind == description.RSSecondary || + serv.Kind == description.Mongos || + serv.Kind == description.Standalone + } + } + if performAuth(desc) && options.Authenticator != nil { + err = options.Authenticator.Auth(ctx, desc, rw) + if err != nil { + return description.Server{}, newAuthError("auth error", err) + } + } if h == nil { return desc, nil diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/cred.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/cred.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/cred.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/cred.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/default.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/default.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/default.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/default.go index 13fdd41..e251f90 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/default.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/default.go @@ -9,8 +9,8 @@ package auth import ( "context" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) func newDefaultAuthenticator(cred *Cred) (Authenticator, error) { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/doc.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/doc.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/doc.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/doc.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi.go similarity index 73% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi.go index c428bcb..918fe69 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi.go @@ -11,10 +11,12 @@ package auth import ( "context" + "fmt" + "net" - "github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // GSSAPI is the mechanism name for GSSAPI. @@ -43,7 +45,13 @@ type GSSAPIAuthenticator struct { // Auth authenticates the connection. func (a *GSSAPIAuthenticator) Auth(ctx context.Context, desc description.Server, rw wiremessage.ReadWriter) error { - client, err := gssapi.New(desc.Addr.String(), a.Username, a.Password, a.PasswordSet, a.Props) + target := desc.Addr.String() + hostname, _, err := net.SplitHostPort(target) + if err != nil { + return newAuthError(fmt.Sprintf("invalid endpoint (%s) specified: %s", target, err), nil) + } + + client, err := gssapi.New(hostname, a.Username, a.Password, a.PasswordSet, a.Props) if err != nil { return newAuthError("error creating gssapi", err) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi_not_enabled.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi_not_enabled.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi_not_enabled.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi_not_enabled.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi_not_supported.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi_not_supported.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/gssapi_not_supported.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/gssapi_not_supported.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss.go index 366ab7b..44faae4 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss.go @@ -19,13 +19,12 @@ package gssapi import "C" import ( "fmt" - "net" "runtime" "strings" "unsafe" ) -// New creates a new SaslClient. +// New creates a new SaslClient. The target parameter should be a hostname with no port. func New(target, username, password string, passwordSet bool, props map[string]string) (*SaslClient, error) { serviceName := "mongodb" @@ -37,17 +36,14 @@ func New(target, username, password string, passwordSet bool, props map[string]s return nil, fmt.Errorf("SERVICE_REALM is not supported when using gssapi on %s", runtime.GOOS) case "SERVICE_NAME": serviceName = value + case "SERVICE_HOST": + target = value default: return nil, fmt.Errorf("unknown mechanism property %s", key) } } - hostname, _, err := net.SplitHostPort(target) - if err != nil { - return nil, fmt.Errorf("invalid endpoint (%s) specified: %s", target, err) - } - - servicePrincipalName := fmt.Sprintf("%s@%s", serviceName, hostname) + servicePrincipalName := fmt.Sprintf("%s@%s", serviceName, target) return &SaslClient{ servicePrincipalName: servicePrincipalName, @@ -94,7 +90,9 @@ func (sc *SaslClient) Start() (string, []byte, error) { return mechName, nil, sc.getError("unable to initialize client") } - return mechName, nil, nil + payload, err := sc.Next(nil) + + return mechName, payload, err } func (sc *SaslClient) Next(challenge []byte) ([]byte, error) { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss_wrapper.c b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss_wrapper.c similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss_wrapper.c rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss_wrapper.c diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss_wrapper.h b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss_wrapper.h similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/gss_wrapper.h rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/gss_wrapper.h diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi.go similarity index 95% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi.go index dd547f3..f3c3c75 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi.go @@ -19,7 +19,7 @@ import ( "unsafe" ) -// New creates a new SaslClient. +// New creates a new SaslClient. The target parameter should be a hostname with no port. func New(target, username, password string, passwordSet bool, props map[string]string) (*SaslClient, error) { initOnce.Do(initSSPI) if initError != nil { @@ -30,6 +30,7 @@ func New(target, username, password string, passwordSet bool, props map[string]s serviceName := "mongodb" serviceRealm := "" canonicalizeHostName := false + var serviceHostSet bool for key, value := range props { switch strings.ToUpper(key) { @@ -43,25 +44,29 @@ func New(target, username, password string, passwordSet bool, props map[string]s serviceRealm = value case "SERVICE_NAME": serviceName = value + case "SERVICE_HOST": + serviceHostSet = true + target = value } } - hostname, _, err := net.SplitHostPort(target) - if err != nil { - return nil, fmt.Errorf("invalid endpoint (%s) specified: %s", target, err) - } if canonicalizeHostName { - names, err := net.LookupAddr(hostname) + // Should not canonicalize the SERVICE_HOST + if serviceHostSet { + return nil, fmt.Errorf("CANONICALIZE_HOST_NAME and SERVICE_HOST canonot both be specified") + } + + names, err := net.LookupAddr(target) if err != nil || len(names) == 0 { return nil, fmt.Errorf("unable to canonicalize hostname: %s", err) } - hostname = names[0] - if hostname[len(hostname)-1] == '.' { - hostname = hostname[:len(hostname)-1] + target = names[0] + if target[len(target)-1] == '.' { + target = target[:len(target)-1] } } - servicePrincipalName := fmt.Sprintf("%s/%s", serviceName, hostname) + servicePrincipalName := fmt.Sprintf("%s/%s", serviceName, target) if serviceRealm != "" { servicePrincipalName += "@" + serviceRealm } @@ -109,7 +114,9 @@ func (sc *SaslClient) Start() (string, []byte, error) { return mechName, nil, sc.getError("unable to intitialize client") } - return mechName, nil, nil + payload, err := sc.Next(nil) + + return mechName, payload, err } func (sc *SaslClient) Next(challenge []byte) ([]byte, error) { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi_wrapper.c b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi_wrapper.c similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi_wrapper.c rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi_wrapper.c diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi_wrapper.h b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi_wrapper.h similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/internal/gssapi/sspi_wrapper.h rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/internal/gssapi/sspi_wrapper.h diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/mongodbcr.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/mongodbcr.go similarity index 86% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/mongodbcr.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/mongodbcr.go index 41d12b9..ccc1b0f 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/mongodbcr.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/mongodbcr.go @@ -13,11 +13,11 @@ import ( "io" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // MONGODBCR is the mechanism name for MONGODB-CR. @@ -47,11 +47,6 @@ type MongoDBCRAuthenticator struct { // The MONGODB-CR authentication mechanism is deprecated in MongoDB 4.0. func (a *MongoDBCRAuthenticator) Auth(ctx context.Context, desc description.Server, rw wiremessage.ReadWriter) error { - // Arbiters cannot be authenticated - if desc.Kind == description.RSArbiter { - return nil - } - db := a.DB if db == "" { db = defaultAuthDB diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/plain.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/plain.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/plain.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/plain.go index 212bd2a..4f76eac 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/plain.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/plain.go @@ -9,8 +9,8 @@ package auth import ( "context" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // PLAIN is the mechanism name for PLAIN. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/sasl.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/sasl.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/sasl.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/sasl.go index 1f684e9..98ee4cf 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/sasl.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/sasl.go @@ -9,11 +9,11 @@ package auth import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // SaslClient is the client piece of a sasl conversation. @@ -31,10 +31,6 @@ type SaslClientCloser interface { // ConductSaslConversation handles running a sasl conversation with MongoDB. func ConductSaslConversation(ctx context.Context, desc description.Server, rw wiremessage.ReadWriter, db string, client SaslClient) error { - // Arbiters cannot be authenticated - if desc.Kind == description.RSArbiter { - return nil - } if db == "" { db = defaultAuthDB diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/scram.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/scram.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/scram.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/scram.go index 2480eb6..fa6d51e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/scram.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/scram.go @@ -16,10 +16,10 @@ import ( "context" "fmt" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" "github.com/xdg/scram" "github.com/xdg/stringprep" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // SCRAMSHA1 holds the mechanism name "SCRAM-SHA-1" diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/util.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/util.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/util.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/util.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/auth/x509.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/x509.go similarity index 86% rename from vendor/github.com/mongodb/mongo-go-driver/core/auth/x509.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/x509.go index aef495c..3a68142 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/auth/x509.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/auth/x509.go @@ -9,10 +9,10 @@ package auth import ( "context" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // MongoDBX509 is the mechanism name for MongoDBX509. diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/batch_cursor.go new file mode 100644 index 0000000..f9cd2d3 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/batch_cursor.go @@ -0,0 +1,428 @@ +package driver + +import ( + "context" + "errors" + "fmt" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/wiremessage" +) + +// BatchCursor is a batch implementation of a cursor. It returns documents in entire batches instead +// of one at a time. An individual document cursor can be built on top of this batch cursor. +type BatchCursor struct { + clientSession *session.Client + clock *session.ClusterClock + namespace command.Namespace + id int64 + err error + server *topology.Server + opts []bsonx.Elem + currentBatch *bsoncore.DocumentSequence + firstBatch bool + batchNumber int + + // legacy server (< 3.2) fields + batchSize int32 + limit int32 + numReturned int32 // number of docs returned by server +} + +// NewBatchCursor creates a new BatchCursor from the provided parameters. +func NewBatchCursor(result bsoncore.Document, clientSession *session.Client, clock *session.ClusterClock, server *topology.Server, opts ...bsonx.Elem) (*BatchCursor, error) { + cur, err := result.LookupErr("cursor") + if err != nil { + return nil, err + } + if cur.Type != bson.TypeEmbeddedDocument { + return nil, fmt.Errorf("cursor should be an embedded document but it is a BSON %s", cur.Type) + } + + elems, err := cur.Document().Elements() + if err != nil { + return nil, err + } + bc := &BatchCursor{ + clientSession: clientSession, + clock: clock, + server: server, + opts: opts, + firstBatch: true, + currentBatch: new(bsoncore.DocumentSequence), + } + + var ok bool + for _, elem := range elems { + switch elem.Key() { + case "firstBatch": + arr, ok := elem.Value().ArrayOK() + if !ok { + return nil, fmt.Errorf("firstBatch should be an array but it is a BSON %s", elem.Value().Type) + } + bc.currentBatch.Style = bsoncore.ArrayStyle + bc.currentBatch.Data = arr + case "ns": + if elem.Value().Type != bson.TypeString { + return nil, fmt.Errorf("namespace should be a string but it is a BSON %s", elem.Value().Type) + } + namespace := command.ParseNamespace(elem.Value().StringValue()) + err = namespace.Validate() + if err != nil { + return nil, err + } + bc.namespace = namespace + case "id": + bc.id, ok = elem.Value().Int64OK() + if !ok { + return nil, fmt.Errorf("id should be an int64 but it is a BSON %s", elem.Value().Type) + } + } + } + + // close session if everything fits in first batch + if bc.id == 0 { + bc.closeImplicitSession() + } + return bc, nil +} + +// NewEmptyBatchCursor returns a batch cursor that is empty. +func NewEmptyBatchCursor() *BatchCursor { + return &BatchCursor{currentBatch: new(bsoncore.DocumentSequence)} +} + +// NewLegacyBatchCursor creates a new BatchCursor for server versions 3.0 and below from the +// provided parameters. +// +// TODO(GODRIVER-617): The batch parameter here should be []bsoncore.Document. Change it to this +// once we have the new wiremessage package that uses bsoncore instead of bson. +func NewLegacyBatchCursor(ns command.Namespace, cursorID int64, ds *bsoncore.DocumentSequence, limit int32, batchSize int32, server *topology.Server) (*BatchCursor, error) { + dsCount := ds.DocumentCount() + bc := &BatchCursor{ + id: cursorID, + server: server, + namespace: ns, + limit: limit, + batchSize: batchSize, + numReturned: int32(dsCount), + firstBatch: true, + } + + // take as many documents from the batch as needed + if limit != 0 && limit < int32(dsCount) { + for i := int32(0); i < limit; i++ { + _, err := ds.Next() + if err != nil { + return nil, err + } + } + ds.Data = ds.Data[:ds.Pos] + ds.ResetIterator() + } + bc.currentBatch = ds + + return bc, nil +} + +// ID returns the cursor ID for this batch cursor. +func (bc *BatchCursor) ID() int64 { + return bc.id +} + +// Next indicates if there is another batch available. Returning false does not necessarily indicate +// that the cursor is closed. This method will return false when an empty batch is returned. +// +// If Next returns true, there is a valid batch of documents available. If Next returns false, there +// is not a valid batch of documents available. +func (bc *BatchCursor) Next(ctx context.Context) bool { + if ctx == nil { + ctx = context.Background() + } + + if bc.firstBatch { + bc.firstBatch = false + return true + } + + if bc.id == 0 || bc.server == nil { + return false + } + + if bc.legacy() { + bc.legacyGetMore(ctx) + } else { + bc.getMore(ctx) + } + + switch bc.currentBatch.Style { + case bsoncore.SequenceStyle: + return len(bc.currentBatch.Data) > 0 + case bsoncore.ArrayStyle: + return len(bc.currentBatch.Data) > 5 + default: + return false + } +} + +// Batch will return a DocumentSequence for the current batch of documents. The returned +// DocumentSequence is only valid until the next call to Next or Close. +func (bc *BatchCursor) Batch() *bsoncore.DocumentSequence { return bc.currentBatch } + +// Server returns a pointer to the cursor's server. +func (bc *BatchCursor) Server() *topology.Server { return bc.server } + +// Err returns the latest error encountered. +func (bc *BatchCursor) Err() error { return bc.err } + +// Close closes this batch cursor. +func (bc *BatchCursor) Close(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } + + if bc.server == nil { + return nil + } + + if bc.legacy() { + return bc.legacyKillCursor(ctx) + } + + defer bc.closeImplicitSession() + conn, err := bc.server.Connection(ctx) + if err != nil { + return err + } + + _, err = (&command.KillCursors{ + Clock: bc.clock, + NS: bc.namespace, + IDs: []int64{bc.id}, + }).RoundTrip(ctx, bc.server.SelectedDescription(), conn) + if err != nil { + _ = conn.Close() // The command response error is more important here + return err + } + + bc.id = 0 + bc.currentBatch.Data = nil + bc.currentBatch.Style = 0 + bc.currentBatch.ResetIterator() + + return conn.Close() +} + +func (bc *BatchCursor) closeImplicitSession() { + if bc.clientSession != nil && bc.clientSession.SessionType == session.Implicit { + bc.clientSession.EndSession() + } +} + +func (bc *BatchCursor) clearBatch() { + bc.currentBatch.Data = bc.currentBatch.Data[:0] +} + +func (bc *BatchCursor) getMore(ctx context.Context) { + bc.clearBatch() + if bc.id == 0 { + return + } + + conn, err := bc.server.Connection(ctx) + if err != nil { + bc.err = err + return + } + + response, err := (&command.GetMore{ + Clock: bc.clock, + ID: bc.id, + NS: bc.namespace, + Opts: bc.opts, + Session: bc.clientSession, + }).RoundTrip(ctx, bc.server.SelectedDescription(), conn) + if err != nil { + _ = conn.Close() // The command response error is more important here + bc.err = err + return + } + + err = conn.Close() + if err != nil { + bc.err = err + return + } + + id, err := response.LookupErr("cursor", "id") + if err != nil { + bc.err = err + return + } + var ok bool + bc.id, ok = id.Int64OK() + if !ok { + bc.err = fmt.Errorf("BSON Type %s is not %s", id.Type, bson.TypeInt64) + return + } + + // if this is the last getMore, close the session + if bc.id == 0 { + bc.closeImplicitSession() + } + + batch, err := response.LookupErr("cursor", "nextBatch") + if err != nil { + bc.err = err + return + } + var arr bson.Raw + arr, ok = batch.ArrayOK() + if !ok { + bc.err = fmt.Errorf("BSON Type %s is not %s", batch.Type, bson.TypeArray) + return + } + bc.currentBatch.Style = bsoncore.ArrayStyle + bc.currentBatch.Data = arr + bc.currentBatch.ResetIterator() + + return +} + +func (bc *BatchCursor) legacy() bool { + return bc.server.Description().WireVersion == nil || bc.server.Description().WireVersion.Max < 4 +} + +func (bc *BatchCursor) legacyKillCursor(ctx context.Context) error { + conn, err := bc.server.Connection(ctx) + if err != nil { + return err + } + + kc := wiremessage.KillCursors{ + NumberOfCursorIDs: 1, + CursorIDs: []int64{bc.id}, + CollectionName: bc.namespace.Collection, + DatabaseName: bc.namespace.DB, + } + + err = conn.WriteWireMessage(ctx, kc) + if err != nil { + _ = conn.Close() + return err + } + + err = conn.Close() // no reply from OP_KILL_CURSORS + if err != nil { + return err + } + + bc.id = 0 + bc.clearBatch() + return nil +} + +func (bc *BatchCursor) legacyGetMore(ctx context.Context) { + bc.clearBatch() + if bc.id == 0 { + return + } + + conn, err := bc.server.Connection(ctx) + if err != nil { + bc.err = err + return + } + + numToReturn := bc.batchSize + if bc.limit != 0 && bc.numReturned+bc.batchSize > bc.limit { + numToReturn = bc.limit - bc.numReturned + if numToReturn <= 0 { + err = bc.Close(ctx) + if err != nil { + bc.err = err + } + return + } + } + gm := wiremessage.GetMore{ + FullCollectionName: bc.namespace.DB + "." + bc.namespace.Collection, + CursorID: bc.id, + NumberToReturn: numToReturn, + } + + err = conn.WriteWireMessage(ctx, gm) + if err != nil { + _ = conn.Close() + bc.err = err + return + } + + response, err := conn.ReadWireMessage(ctx) + if err != nil { + _ = conn.Close() + bc.err = err + return + } + + err = conn.Close() + if err != nil { + bc.err = err + return + } + + reply, ok := response.(wiremessage.Reply) + if !ok { + bc.err = errors.New("did not receive OP_REPLY response") + return + } + + err = validateGetMoreReply(reply) + if err != nil { + bc.err = err + return + } + + bc.id = reply.CursorID + bc.numReturned += reply.NumberReturned + if bc.limit != 0 && bc.numReturned >= bc.limit { + err = bc.Close(ctx) + if err != nil { + bc.err = err + return + } + } + + // TODO(GODRIVER-617): When the wiremessage package is updated, we should ensure we can get all + // of the documents as a single slice instead of having to reslice. + bc.currentBatch.Style = bsoncore.SequenceStyle + for _, doc := range reply.Documents { + bc.currentBatch.Data = append(bc.currentBatch.Data, doc...) + } + bc.currentBatch.ResetIterator() +} + +func validateGetMoreReply(reply wiremessage.Reply) error { + if int(reply.NumberReturned) != len(reply.Documents) { + return command.NewCommandResponseError("malformed OP_REPLY: NumberReturned does not match number of returned documents", nil) + } + + if reply.ResponseFlags&wiremessage.CursorNotFound == wiremessage.CursorNotFound { + return command.QueryFailureError{ + Message: "query failure - cursor not found", + } + } + if reply.ResponseFlags&wiremessage.QueryFailure == wiremessage.QueryFailure { + return command.QueryFailureError{ + Message: "query failure", + Response: reply.Documents[0], + } + } + + return nil +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/bulk_write.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/bulk_write.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/bulk_write.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/bulk_write.go index e91e309..f0e99e1 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/bulk_write.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // BulkWriteError is an error from one operation in a bulk write. @@ -90,6 +90,7 @@ func BulkWrite( WriteErrors: make([]BulkWriteError, 0), } + var lastErr error var opIndex int64 // the operation index for the upsertedIDs map continueOnError := !ordered for _, batch := range batches { @@ -109,16 +110,26 @@ func BulkWrite( if !continueOnError && (err != nil || len(batchErr.WriteErrors) > 0 || batchErr.WriteConcernError != nil) { if err != nil { - return result.BulkWrite{}, err + return bwRes, err } - return result.BulkWrite{}, bwErr + return bwRes, bwErr + } + + if err != nil { + lastErr = err } opIndex += int64(len(batch.models)) } bwRes.MatchedCount -= bwRes.UpsertedCount + if lastErr != nil { + return bwRes, lastErr + } + if len(bwErr.WriteErrors) > 0 || bwErr.WriteConcernError != nil { + return bwRes, bwErr + } return bwRes, nil } @@ -225,28 +236,29 @@ func runInsert( WriteConcern: wc, } + cmd.Opts = []bsonx.Elem{{"ordered", bsonx.Boolean(!continueOnError)}} if bypassDocValidation != nil { - cmd.Opts = []bsonx.Elem{{"bypassDocumentValidation", bsonx.Boolean(*bypassDocValidation)}} + cmd.Opts = append(cmd.Opts, bsonx.Elem{"bypassDocumentValidation", bsonx.Boolean(*bypassDocValidation)}) } if !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) || !retryWrite || !batch.canRetry { if cmd.Session != nil { cmd.Session.RetryWrite = false } - return insert(ctx, cmd, ss, nil) + return insert(ctx, &cmd, ss, nil) } cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() - res, origErr := insert(ctx, cmd, ss, nil) + res, origErr := insert(ctx, &cmd, ss, nil) if shouldRetry(origErr, res.WriteConcernError) { newServer, err := topo.SelectServer(ctx, selector) if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { return res, origErr } - return insert(ctx, cmd, newServer, origErr) + return insert(ctx, &cmd, newServer, origErr) } return res, origErr @@ -295,25 +307,26 @@ func runDelete( Clock: clock, WriteConcern: wc, } + cmd.Opts = []bsonx.Elem{{"ordered", bsonx.Boolean(!continueOnError)}} if !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) || !retryWrite || !batch.canRetry { if cmd.Session != nil { cmd.Session.RetryWrite = false } - return delete(ctx, cmd, ss, nil) + return delete(ctx, &cmd, ss, nil) } cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() - res, origErr := delete(ctx, cmd, ss, nil) + res, origErr := delete(ctx, &cmd, ss, nil) if shouldRetry(origErr, res.WriteConcernError) { newServer, err := topo.SelectServer(ctx, selector) if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { return res, origErr } - return delete(ctx, cmd, newServer, origErr) + return delete(ctx, &cmd, newServer, origErr) } return res, origErr @@ -366,9 +379,11 @@ func runUpdate( Clock: clock, WriteConcern: wc, } + + cmd.Opts = []bsonx.Elem{{"ordered", bsonx.Boolean(!continueOnError)}} if bypassDocValidation != nil { // TODO this is temporary! - cmd.Opts = []bsonx.Elem{{"bypassDocumentValidation", bsonx.Boolean(*bypassDocValidation)}} + cmd.Opts = append(cmd.Opts, bsonx.Elem{"bypassDocumentValidation", bsonx.Boolean(*bypassDocValidation)}) //cmd.Opts = []option.UpdateOptioner{option.OptBypassDocumentValidation(bypassDocValidation)} } @@ -376,20 +391,20 @@ func runUpdate( if cmd.Session != nil { cmd.Session.RetryWrite = false } - return update(ctx, cmd, ss, nil) + return update(ctx, &cmd, ss, nil) } cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() - res, origErr := update(ctx, cmd, ss, nil) + res, origErr := update(ctx, &cmd, ss, nil) if shouldRetry(origErr, res.WriteConcernError) { newServer, err := topo.SelectServer(ctx, selector) if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { return res, origErr } - return update(ctx, cmd, newServer, origErr) + return update(ctx, &cmd, newServer, origErr) } return res, origErr @@ -568,15 +583,27 @@ func createUpdateDoc( } if arrayFiltersSet { - arr, err := arrayFilters.ToArray() + filters, err := arrayFilters.ToArray() if err != nil { return nil, err } + arr := make(bsonx.Arr, 0, len(filters)) + for _, filter := range filters { + doc, err := bsonx.ReadDoc(filter) + if err != nil { + return nil, err + } + arr = append(arr, bsonx.Document(doc)) + } doc = append(doc, bsonx.Elem{"arrayFilters", bsonx.Array(arr)}) } if updateModel.Collation != nil { - doc = append(doc, bsonx.Elem{"collation", bsonx.Document(updateModel.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(updateModel.Collation.ToDocument()) + if err != nil { + return nil, err + } + doc = append(doc, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if updateModel.UpsertSet { @@ -608,7 +635,11 @@ func createDeleteDoc( } if collation != nil { - doc = append(doc, bsonx.Elem{"collation", bsonx.Document(collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(collation.ToDocument()) + if err != nil { + return nil, err + } + doc = append(doc, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } return doc, nil diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/commit_transaction.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/commit_transaction.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/commit_transaction.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/commit_transaction.go index 3314b1f..7c890d5 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/commit_transaction.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/commit_transaction.go @@ -4,15 +4,17 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" + "time" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/topology" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // CommitTransaction handles the full cycle dispatch and execution of committing a transaction @@ -24,6 +26,15 @@ func CommitTransaction( selector description.ServerSelector, ) (result.TransactionResult, error) { res, err := commitTransaction(ctx, cmd, topo, selector, nil) + + // Apply majority write concern for retries + currWC := cmd.Session.CurrentWc + newTimeout := 10 * time.Second + if currWC != nil && currWC.GetWTimeout() != 0 { + newTimeout = currWC.GetWTimeout() + } + cmd.Session.CurrentWc = currWC.WithOptions(writeconcern.WMajority(), writeconcern.WTimeout(newTimeout)) + if cerr, ok := err.(command.Error); ok && err != nil { // Retry if appropriate if cerr.Retryable() { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/count.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/count.go similarity index 76% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/count.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/count.go index fd39a61..5de566c 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/count.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/count.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // Count handles the full cycle dispatch and execution of a count command against the provided @@ -68,7 +68,7 @@ func Count( } if countOpts.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{ - "maxTimeMS", bsonx.Int64(int64(time.Duration(*countOpts.MaxTime) / time.Millisecond)), + "maxTimeMS", bsonx.Int64(int64(*countOpts.MaxTime / time.Millisecond)), }) } if countOpts.Skip != nil { @@ -78,7 +78,11 @@ func Count( if desc.WireVersion.Max < 5 { return 0, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(countOpts.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(countOpts.Collation.ToDocument()) + if err != nil { + return 0, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if countOpts.Hint != nil { hintElem, err := interfaceToElement("hint", countOpts.Hint, registry) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/count_documents.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/count_documents.go similarity index 74% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/count_documents.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/count_documents.go index 8ee558c..5ff3c73 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/count_documents.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/count_documents.go @@ -4,21 +4,20 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/x/bsonx" - - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // CountDocuments handles the full cycle dispatch and execution of a countDocuments command against the provided @@ -66,14 +65,18 @@ func CountDocuments( // ignore Skip and Limit because we already have these options in the pipeline if countOpts.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{ - "maxTimeMS", bsonx.Int64(int64(time.Duration(*countOpts.MaxTime) / time.Millisecond)), + "maxTimeMS", bsonx.Int64(int64(*countOpts.MaxTime / time.Millisecond)), }) } if countOpts.Collation != nil { if desc.WireVersion.Max < 5 { return 0, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(countOpts.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(countOpts.Collation.ToDocument()) + if err != nil { + return 0, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if countOpts.Hint != nil { hintElem, err := interfaceToElement("hint", countOpts.Hint, registry) @@ -84,5 +87,5 @@ func CountDocuments( cmd.Opts = append(cmd.Opts, hintElem) } - return cmd.RoundTrip(ctx, desc, ss, conn) + return cmd.RoundTrip(ctx, desc, conn) } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/create_indexes.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/create_indexes.go similarity index 66% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/create_indexes.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/create_indexes.go index cfb0c34..2015920 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/create_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/create_indexes.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // CreateIndexes handles the full cycle dispatch and execution of a createIndexes @@ -38,6 +38,11 @@ func CreateIndexes( return result.CreateIndexes{}, err } + desc := ss.Description() + if desc.WireVersion.Max < 5 && hasCollation(cmd) { + return result.CreateIndexes{}, ErrCollation + } + conn, err := ss.Connection(ctx) if err != nil { return result.CreateIndexes{}, err @@ -60,3 +65,13 @@ func CreateIndexes( return cmd.RoundTrip(ctx, ss.Description(), conn) } + +func hasCollation(cmd command.CreateIndexes) bool { + for _, ind := range cmd.Indexes { + if _, err := ind.Document().LookupErr("collation"); err == nil { + return true + } + } + + return false +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/delete.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/delete.go similarity index 71% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/delete.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/delete.go index b1265d4..c64a8b0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/delete.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/delete.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // Delete handles the full cycle dispatch and execution of a delete command against the provided @@ -53,7 +53,11 @@ func Delete( if ss.Description().WireVersion.Max < 5 { return result.Delete{}, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(deleteOpts.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(deleteOpts.Collation.ToDocument()) + if err != nil { + return result.Delete{}, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } // Execute in a single trip if retry writes not supported, or retry not enabled @@ -61,17 +65,17 @@ func Delete( if cmd.Session != nil { cmd.Session.RetryWrite = false // explicitly set to false to prevent encoding transaction number } - return delete(ctx, cmd, ss, nil) + return delete(ctx, &cmd, ss, nil) } cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() - res, originalErr := delete(ctx, cmd, ss, nil) + res, originalErr := delete(ctx, &cmd, ss, nil) // Retry if appropriate - if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() || - res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError) { + if cerr, ok := originalErr.(command.Error); (ok && cerr.Retryable()) || + (res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError)) { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes @@ -79,14 +83,14 @@ func Delete( return res, originalErr } - return delete(ctx, cmd, ss, cerr) + return delete(ctx, &cmd, ss, cerr) } return res, originalErr } func delete( ctx context.Context, - cmd command.Delete, + cmd *command.Delete, ss *topology.SelectedServer, oldErr error, ) (result.Delete, error) { @@ -112,5 +116,7 @@ func delete( } defer conn.Close() - return cmd.RoundTrip(ctx, desc, conn) + res, err := cmd.RoundTrip(ctx, desc, conn) + ss.ProcessWriteConcernError(res.WriteConcernError) + return res, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/delete_indexes.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/delete_indexes.go similarity index 76% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/delete_indexes.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/delete_indexes.go index e537702..be6b9a1 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/delete_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/delete_indexes.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // DropIndexes handles the full cycle dispatch and execution of a dropIndexes diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/dispatch.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/dispatch.go similarity index 81% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/dispatch.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/dispatch.go index aa886af..fc2fcc0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/dispatch.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/dispatch.go @@ -4,14 +4,15 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver // import "go.mongodb.org/mongo-driver/x/mongo/driver" import ( "errors" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" ) // ErrCollation is caused if a collation is given for an invalid server version. @@ -58,3 +59,9 @@ func interfaceToElement(key string, i interface{}, registry *bsoncodec.Registry) return bsonx.Elem{key, bsonx.Document(doc)}, nil } } + +func closeImplicitSession(sess *session.Client) { + if sess != nil && sess.SessionType == session.Implicit { + sess.EndSession() + } +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/distinct.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/distinct.go similarity index 72% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/distinct.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/distinct.go index 9bf5bb9..f741fa9 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/distinct.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/distinct.go @@ -4,21 +4,20 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" - - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // Distinct handles the full cycle dispatch and execution of a distinct command against the provided @@ -64,14 +63,18 @@ func Distinct( if distinctOpts.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{ - "maxTimeMS", bsonx.Int64(int64(time.Duration(*distinctOpts.MaxTime) / time.Millisecond)), + "maxTimeMS", bsonx.Int64(int64(*distinctOpts.MaxTime / time.Millisecond)), }) } if distinctOpts.Collation != nil { if desc.WireVersion.Max < 5 { return result.Distinct{}, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(distinctOpts.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(distinctOpts.Collation.ToDocument()) + if err != nil { + return result.Distinct{}, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } return cmd.RoundTrip(ctx, desc, conn) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/drop_collection.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/drop_collection.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/drop_collection.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/drop_collection.go index 17cad7f..d5bf8ab 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/drop_collection.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/drop_collection.go @@ -4,17 +4,17 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // DropCollection handles the full cycle dispatch and execution of a dropCollection diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/drop_database.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/drop_database.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/drop_database.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/drop_database.go index 326291b..6e1ccf0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/drop_database.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/drop_database.go @@ -4,17 +4,17 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // DropDatabase handles the full cycle dispatch and execution of a dropDatabase diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/end_sessions.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/end_sessions.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/end_sessions.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/end_sessions.go index 3210c9c..9e345bf 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/end_sessions.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/end_sessions.go @@ -4,15 +4,15 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // EndSessions handles the full cycle dispatch and execution of an endSessions command against the provided diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find.go new file mode 100644 index 0000000..bd25297 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find.go @@ -0,0 +1,529 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driver + +import ( + "context" + + "time" + + "errors" + + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" +) + +// Find handles the full cycle dispatch and execution of a find command against the provided +// topology. +func Find( + ctx context.Context, + cmd command.Find, + topo *topology.Topology, + selector description.ServerSelector, + clientID uuid.UUID, + pool *session.Pool, + registry *bsoncodec.Registry, + opts ...*options.FindOptions, +) (*BatchCursor, error) { + + ss, err := topo.SelectServer(ctx, selector) + if err != nil { + return nil, err + } + + desc := ss.Description() + conn, err := ss.Connection(ctx) + if err != nil { + return nil, err + } + defer conn.Close() + + if desc.WireVersion.Max < 4 { + return legacyFind(ctx, cmd, registry, ss, conn, opts...) + } + + rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session) + if err != nil { + return nil, err + } + cmd.ReadPref = rp + + // If no explicit session and deployment supports sessions, start implicit session. + if cmd.Session == nil && topo.SupportsSessions() { + cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) + if err != nil { + return nil, err + } + } + + fo := options.MergeFindOptions(opts...) + if fo.AllowPartialResults != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"allowPartialResults", bsonx.Boolean(*fo.AllowPartialResults)}) + } + if fo.BatchSize != nil { + elem := bsonx.Elem{"batchSize", bsonx.Int32(*fo.BatchSize)} + cmd.Opts = append(cmd.Opts, elem) + cmd.CursorOpts = append(cmd.CursorOpts, elem) + + if fo.Limit != nil && *fo.BatchSize != 0 && *fo.Limit <= int64(*fo.BatchSize) { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"singleBatch", bsonx.Boolean(true)}) + } + } + if fo.Collation != nil { + if desc.WireVersion.Max < 5 { + return nil, ErrCollation + } + collDoc, err := bsonx.ReadDoc(fo.Collation.ToDocument()) + if err != nil { + return nil, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) + } + if fo.Comment != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"comment", bsonx.String(*fo.Comment)}) + } + if fo.CursorType != nil { + switch *fo.CursorType { + case options.Tailable: + cmd.Opts = append(cmd.Opts, bsonx.Elem{"tailable", bsonx.Boolean(true)}) + case options.TailableAwait: + cmd.Opts = append(cmd.Opts, bsonx.Elem{"tailable", bsonx.Boolean(true)}, bsonx.Elem{"awaitData", bsonx.Boolean(true)}) + } + } + if fo.Hint != nil { + hintElem, err := interfaceToElement("hint", fo.Hint, registry) + if err != nil { + return nil, err + } + + cmd.Opts = append(cmd.Opts, hintElem) + } + if fo.Limit != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"limit", bsonx.Int64(*fo.Limit)}) + } + if fo.Max != nil { + maxElem, err := interfaceToElement("max", fo.Max, registry) + if err != nil { + return nil, err + } + + cmd.Opts = append(cmd.Opts, maxElem) + } + if fo.MaxAwaitTime != nil { + // Specified as maxTimeMS on the in the getMore command and not given in initial find command. + cmd.CursorOpts = append(cmd.CursorOpts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*fo.MaxAwaitTime / time.Millisecond))}) + } + if fo.MaxTime != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*fo.MaxTime / time.Millisecond))}) + } + if fo.Min != nil { + minElem, err := interfaceToElement("min", fo.Min, registry) + if err != nil { + return nil, err + } + + cmd.Opts = append(cmd.Opts, minElem) + } + if fo.NoCursorTimeout != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"noCursorTimeout", bsonx.Boolean(*fo.NoCursorTimeout)}) + } + if fo.OplogReplay != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"oplogReplay", bsonx.Boolean(*fo.OplogReplay)}) + } + if fo.Projection != nil { + projElem, err := interfaceToElement("projection", fo.Projection, registry) + if err != nil { + return nil, err + } + + cmd.Opts = append(cmd.Opts, projElem) + } + if fo.ReturnKey != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"returnKey", bsonx.Boolean(*fo.ReturnKey)}) + } + if fo.ShowRecordID != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"showRecordId", bsonx.Boolean(*fo.ShowRecordID)}) + } + if fo.Skip != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"skip", bsonx.Int64(*fo.Skip)}) + } + if fo.Snapshot != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"snapshot", bsonx.Boolean(*fo.Snapshot)}) + } + if fo.Sort != nil { + sortElem, err := interfaceToElement("sort", fo.Sort, registry) + if err != nil { + return nil, err + } + + cmd.Opts = append(cmd.Opts, sortElem) + } + + res, err := cmd.RoundTrip(ctx, desc, conn) + if err != nil { + closeImplicitSession(cmd.Session) + return nil, err + } + + return NewBatchCursor(bsoncore.Document(res), cmd.Session, cmd.Clock, ss.Server, cmd.CursorOpts...) +} + +// legacyFind handles the dispatch and execution of a find operation against a pre-3.2 server. +func legacyFind( + ctx context.Context, + cmd command.Find, + registry *bsoncodec.Registry, + ss *topology.SelectedServer, + conn connection.Connection, + opts ...*options.FindOptions, +) (*BatchCursor, error) { + query := wiremessage.Query{ + FullCollectionName: cmd.NS.DB + "." + cmd.NS.Collection, + } + + fo := options.MergeFindOptions(opts...) + optsDoc, err := createLegacyOptionsDoc(fo, registry) + if err != nil { + return nil, err + } + if fo.Projection != nil { + projDoc, err := interfaceToDocument(fo.Projection, registry) + if err != nil { + return nil, err + } + + projRaw, err := projDoc.MarshalBSON() + if err != nil { + return nil, err + } + query.ReturnFieldsSelector = projRaw + } + if fo.Skip != nil { + query.NumberToSkip = int32(*fo.Skip) + query.SkipSet = true + } + // batch size of 1 not possible with OP_QUERY because the cursor will be closed immediately + if fo.BatchSize != nil && *fo.BatchSize == 1 { + query.NumberToReturn = 2 + } else { + query.NumberToReturn = calculateNumberToReturn(fo) + } + query.Flags = calculateLegacyFlags(fo) + + query.BatchSize = fo.BatchSize + if fo.Limit != nil { + i := int32(*fo.Limit) + query.Limit = &i + } + + // set read preference and/or slaveOK flag + desc := ss.SelectedDescription() + if slaveOkNeeded(cmd.ReadPref, desc) { + query.Flags |= wiremessage.SlaveOK + } + optsDoc = addReadPref(cmd.ReadPref, desc.Server.Kind, optsDoc) + + if cmd.Filter == nil { + cmd.Filter = bsonx.Doc{} + } + + // filter must be wrapped in $query if other $modifiers are used + var queryDoc bsonx.Doc + if len(optsDoc) == 0 { + queryDoc = cmd.Filter + } else { + filterDoc := bsonx.Doc{ + {"$query", bsonx.Document(cmd.Filter)}, + } + // $query should go first + queryDoc = append(filterDoc, optsDoc...) + } + + queryRaw, err := queryDoc.MarshalBSON() + if err != nil { + return nil, err + } + query.Query = queryRaw + + reply, err := roundTripQuery(ctx, query, conn) + if err != nil { + return nil, err + } + + var cursorLimit int32 + var cursorBatchSize int32 + if query.Limit != nil { + cursorLimit = int32(*query.Limit) + if cursorLimit < 0 { + cursorLimit *= -1 + } + } + if query.BatchSize != nil { + cursorBatchSize = int32(*query.BatchSize) + } + + // TODO(GODRIVER-617): When the wiremessage package is updated, we should ensure we can get all + // of the documents as a single slice instead of having to reslice. + ds := new(bsoncore.DocumentSequence) + ds.Style = bsoncore.SequenceStyle + for _, doc := range reply.Documents { + ds.Data = append(ds.Data, doc...) + } + + return NewLegacyBatchCursor(cmd.NS, reply.CursorID, ds, cursorLimit, cursorBatchSize, ss.Server) +} + +func createLegacyOptionsDoc(fo *options.FindOptions, registry *bsoncodec.Registry) (bsonx.Doc, error) { + var optsDoc bsonx.Doc + + if fo.Collation != nil { + return nil, ErrCollation + } + if fo.Comment != nil { + optsDoc = append(optsDoc, bsonx.Elem{"$comment", bsonx.String(*fo.Comment)}) + } + if fo.Hint != nil { + hintElem, err := interfaceToElement("$hint", fo.Hint, registry) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, hintElem) + } + if fo.Max != nil { + maxElem, err := interfaceToElement("$max", fo.Max, registry) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, maxElem) + } + if fo.MaxTime != nil { + optsDoc = append(optsDoc, bsonx.Elem{"$maxTimeMS", bsonx.Int64(int64(*fo.MaxTime / time.Millisecond))}) + } + if fo.Min != nil { + minElem, err := interfaceToElement("$min", fo.Min, registry) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, minElem) + } + if fo.ReturnKey != nil { + optsDoc = append(optsDoc, bsonx.Elem{"$returnKey", bsonx.Boolean(*fo.ReturnKey)}) + } + if fo.ShowRecordID != nil { + optsDoc = append(optsDoc, bsonx.Elem{"$showDiskLoc", bsonx.Boolean(*fo.ShowRecordID)}) + } + if fo.Snapshot != nil { + optsDoc = append(optsDoc, bsonx.Elem{"$snapshot", bsonx.Boolean(*fo.Snapshot)}) + } + if fo.Sort != nil { + sortElem, err := interfaceToElement("$orderby", fo.Sort, registry) + if err != nil { + return nil, err + } + + optsDoc = append(optsDoc, sortElem) + } + + return optsDoc, nil +} + +func calculateLegacyFlags(fo *options.FindOptions) wiremessage.QueryFlag { + var flags wiremessage.QueryFlag + + if fo.AllowPartialResults != nil { + flags |= wiremessage.Partial + } + if fo.CursorType != nil { + switch *fo.CursorType { + case options.Tailable: + flags |= wiremessage.TailableCursor + case options.TailableAwait: + flags |= wiremessage.TailableCursor + flags |= wiremessage.AwaitData + } + } + if fo.NoCursorTimeout != nil { + flags |= wiremessage.NoCursorTimeout + } + if fo.OplogReplay != nil { + flags |= wiremessage.OplogReplay + } + + return flags +} + +// calculate the number to return for the first find query +func calculateNumberToReturn(opts *options.FindOptions) int32 { + var numReturn int32 + var limit int32 + var batchSize int32 + + if opts.Limit != nil { + limit = int32(*opts.Limit) + } + if opts.BatchSize != nil { + batchSize = int32(*opts.BatchSize) + } + + if limit < 0 { + numReturn = limit + } else if limit == 0 { + numReturn = batchSize + } else if limit < batchSize { + numReturn = limit + } else { + numReturn = batchSize + } + + return numReturn +} + +func slaveOkNeeded(rp *readpref.ReadPref, desc description.SelectedServer) bool { + if desc.Kind == description.Single && desc.Server.Kind != description.Mongos { + return true + } + if rp == nil { + // assume primary + return false + } + + return rp.Mode() != readpref.PrimaryMode +} + +func addReadPref(rp *readpref.ReadPref, kind description.ServerKind, query bsonx.Doc) bsonx.Doc { + if !readPrefNeeded(rp, kind) { + return query + } + + doc := createReadPref(rp) + if doc == nil { + return query + } + + return query.Append("$readPreference", bsonx.Document(doc)) +} + +func readPrefNeeded(rp *readpref.ReadPref, kind description.ServerKind) bool { + if kind != description.Mongos || rp == nil { + return false + } + + // simple Primary or SecondaryPreferred is communicated via slaveOk to Mongos. + if rp.Mode() == readpref.PrimaryMode || rp.Mode() == readpref.SecondaryPreferredMode { + if _, ok := rp.MaxStaleness(); !ok && len(rp.TagSets()) == 0 { + return false + } + } + + return true +} + +func createReadPref(rp *readpref.ReadPref) bsonx.Doc { + if rp == nil { + return nil + } + + doc := bsonx.Doc{} + + switch rp.Mode() { + case readpref.PrimaryMode: + doc = append(doc, bsonx.Elem{"mode", bsonx.String("primary")}) + case readpref.PrimaryPreferredMode: + doc = append(doc, bsonx.Elem{"mode", bsonx.String("primaryPreferred")}) + case readpref.SecondaryPreferredMode: + doc = append(doc, bsonx.Elem{"mode", bsonx.String("secondaryPreferred")}) + case readpref.SecondaryMode: + doc = append(doc, bsonx.Elem{"mode", bsonx.String("secondary")}) + case readpref.NearestMode: + doc = append(doc, bsonx.Elem{"mode", bsonx.String("nearest")}) + } + + sets := make([]bsonx.Val, 0, len(rp.TagSets())) + for _, ts := range rp.TagSets() { + if len(ts) == 0 { + continue + } + set := bsonx.Doc{} + for _, t := range ts { + set = append(set, bsonx.Elem{t.Name, bsonx.String(t.Value)}) + } + sets = append(sets, bsonx.Document(set)) + } + if len(sets) > 0 { + doc = append(doc, bsonx.Elem{"tags", bsonx.Array(sets)}) + } + if d, ok := rp.MaxStaleness(); ok { + doc = append(doc, bsonx.Elem{"maxStalenessSeconds", bsonx.Int32(int32(d.Seconds()))}) + } + + return doc +} + +func roundTripQuery(ctx context.Context, query wiremessage.Query, conn connection.Connection) (wiremessage.Reply, error) { + err := conn.WriteWireMessage(ctx, query) + if err != nil { + if _, ok := err.(command.Error); ok { + return wiremessage.Reply{}, err + } + return wiremessage.Reply{}, command.Error{ + Message: err.Error(), + Labels: []string{command.NetworkError}, + } + } + + wm, err := conn.ReadWireMessage(ctx) + if err != nil { + if _, ok := err.(command.Error); ok { + return wiremessage.Reply{}, err + } + // Connection errors are transient + return wiremessage.Reply{}, command.Error{ + Message: err.Error(), + Labels: []string{command.NetworkError}, + } + } + + reply, ok := wm.(wiremessage.Reply) + if !ok { + return wiremessage.Reply{}, errors.New("did not receive OP_REPLY response") + } + + err = validateOpReply(reply) + if err != nil { + return wiremessage.Reply{}, err + } + + return reply, nil +} + +func validateOpReply(reply wiremessage.Reply) error { + if int(reply.NumberReturned) != len(reply.Documents) { + return command.NewCommandResponseError(command.ReplyDocumentMismatch, nil) + } + + if reply.ResponseFlags&wiremessage.QueryFailure == wiremessage.QueryFailure { + return command.QueryFailureError{ + Message: "query failure", + Response: reply.Documents[0], + } + } + + return nil +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_delete.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_delete.go similarity index 77% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_delete.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_delete.go index b884571..d128e0d 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_delete.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_delete.go @@ -4,23 +4,23 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // FindOneAndDelete handles the full cycle dispatch and execution of a FindOneAndDelete command against the provided @@ -56,7 +56,11 @@ func FindOneAndDelete( if ss.Description().WireVersion.Max < 5 { return result.FindAndModify{}, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(do.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(do.Collation.ToDocument()) + if err != nil { + return result.FindAndModify{}, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if do.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMs", bsonx.Int64(int64(*do.MaxTime / time.Millisecond))}) @@ -92,12 +96,13 @@ func FindOneAndDelete( res, originalErr := findOneAndDelete(ctx, cmd, ss, nil) // Retry if appropriate - if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() { + if cerr, ok := originalErr.(command.Error); (ok && cerr.Retryable()) || + (res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError)) { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { - return result.FindAndModify{}, originalErr + return res, originalErr } return findOneAndDelete(ctx, cmd, ss, cerr) @@ -133,5 +138,7 @@ func findOneAndDelete( } defer conn.Close() - return cmd.RoundTrip(ctx, desc, conn) + res, err := cmd.RoundTrip(ctx, desc, conn) + ss.ProcessWriteConcernError(res.WriteConcernError) + return res, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_replace.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_replace.go similarity index 79% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_replace.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_replace.go index 8998689..00df671 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_replace.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_replace.go @@ -4,23 +4,23 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // FindOneAndReplace handles the full cycle dispatch and execution of a FindOneAndReplace command against the provided @@ -59,7 +59,11 @@ func FindOneAndReplace( if ss.Description().WireVersion.Max < 5 { return result.FindAndModify{}, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(ro.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(ro.Collation.ToDocument()) + if err != nil { + return result.FindAndModify{}, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if ro.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*ro.MaxTime / time.Millisecond))}) @@ -101,12 +105,13 @@ func FindOneAndReplace( res, originalErr := findOneAndReplace(ctx, cmd, ss, nil) // Retry if appropriate - if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() { + if cerr, ok := originalErr.(command.Error); (ok && cerr.Retryable()) || + (res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError)) { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { - return result.FindAndModify{}, originalErr + return res, originalErr } return findOneAndReplace(ctx, cmd, ss, cerr) @@ -142,5 +147,7 @@ func findOneAndReplace( } defer conn.Close() - return cmd.RoundTrip(ctx, desc, conn) + res, err := cmd.RoundTrip(ctx, desc, conn) + ss.ProcessWriteConcernError(res.WriteConcernError) + return res, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_update.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_update.go similarity index 76% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_update.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_update.go index c330d50..0677455 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/find_one_and_update.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/find_one_and_update.go @@ -4,23 +4,23 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // FindOneAndUpdate handles the full cycle dispatch and execution of a FindOneAndUpdate command against the provided @@ -53,11 +53,19 @@ func FindOneAndUpdate( uo := options.MergeFindOneAndUpdateOptions(opts...) if uo.ArrayFilters != nil { - arr, err := uo.ArrayFilters.ToArray() + filters, err := uo.ArrayFilters.ToArray() if err != nil { return result.FindAndModify{}, err } + arr := make(bsonx.Arr, 0, len(filters)) + for _, filter := range filters { + doc, err := bsonx.ReadDoc(filter) + if err != nil { + return result.FindAndModify{}, err + } + arr = append(arr, bsonx.Document(doc)) + } cmd.Opts = append(cmd.Opts, bsonx.Elem{"arrayFilters", bsonx.Array(arr)}) } if uo.BypassDocumentValidation != nil { @@ -67,7 +75,11 @@ func FindOneAndUpdate( if ss.Description().WireVersion.Max < 5 { return result.FindAndModify{}, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(uo.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(uo.Collation.ToDocument()) + if err != nil { + return result.FindAndModify{}, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if uo.MaxTime != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*uo.MaxTime / time.Millisecond))}) @@ -109,12 +121,13 @@ func FindOneAndUpdate( res, originalErr := findOneAndUpdate(ctx, cmd, ss, nil) // Retry if appropriate - if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() { + if cerr, ok := originalErr.(command.Error); (ok && cerr.Retryable()) || + (res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError)) { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes if err != nil || !retrySupported(topo, ss.Description(), cmd.Session, cmd.WriteConcern) { - return result.FindAndModify{}, originalErr + return res, originalErr } return findOneAndUpdate(ctx, cmd, ss, cerr) @@ -150,5 +163,7 @@ func findOneAndUpdate( } defer conn.Close() - return cmd.RoundTrip(ctx, desc, conn) + res, err := cmd.RoundTrip(ctx, desc, conn) + ss.ProcessWriteConcernError(res.WriteConcernError) + return res, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/insert.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/insert.go similarity index 75% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/insert.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/insert.go index e64d7ec..18db12a 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/insert.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/insert.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // Insert handles the full cycle dispatch and execution of an insert command against the provided @@ -62,18 +62,18 @@ func Insert( if cmd.Session != nil { cmd.Session.RetryWrite = false // explicitly set to false to prevent encoding transaction number } - return insert(ctx, cmd, ss, nil) + return insert(ctx, &cmd, ss, nil) } // TODO figure out best place to put retry write. Command shouldn't have to know about this field. cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() - res, originalErr := insert(ctx, cmd, ss, nil) + res, originalErr := insert(ctx, &cmd, ss, nil) // Retry if appropriate - if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() || - res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError) { + if cerr, ok := originalErr.(command.Error); (ok && cerr.Retryable()) || + (res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError)) { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes @@ -81,7 +81,7 @@ func Insert( return res, originalErr } - return insert(ctx, cmd, ss, cerr) + return insert(ctx, &cmd, ss, cerr) } return res, originalErr @@ -89,7 +89,7 @@ func Insert( func insert( ctx context.Context, - cmd command.Insert, + cmd *command.Insert, ss *topology.SelectedServer, oldErr error, ) (result.Insert, error) { @@ -114,5 +114,7 @@ func insert( } defer conn.Close() - return cmd.RoundTrip(ctx, desc, conn) + res, err := cmd.RoundTrip(ctx, desc, conn) + ss.ProcessWriteConcernError(res.WriteConcernError) + return res, err } diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/kill_cursors.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/kill_cursors.go new file mode 100644 index 0000000..b3730c0 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/kill_cursors.go @@ -0,0 +1,56 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driver + +import ( + "context" + + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/wiremessage" + + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/result" +) + +// KillCursors handles the full cycle dispatch and execution of an aggregate command against the provided +// topology. +func KillCursors( + ctx context.Context, + ns command.Namespace, + server *topology.Server, + cursorID int64, +) (result.KillCursors, error) { + desc := server.SelectedDescription() + conn, err := server.Connection(ctx) + if err != nil { + return result.KillCursors{}, err + } + defer conn.Close() + + if desc.WireVersion.Max < 4 { + return result.KillCursors{}, legacyKillCursors(ctx, ns, cursorID, conn) + } + + cmd := command.KillCursors{ + NS: ns, + IDs: []int64{cursorID}, + } + + return cmd.RoundTrip(ctx, desc, conn) +} + +func legacyKillCursors(ctx context.Context, ns command.Namespace, cursorID int64, conn connection.Connection) error { + kc := wiremessage.KillCursors{ + NumberOfCursorIDs: 1, + CursorIDs: []int64{cursorID}, + CollectionName: ns.Collection, + DatabaseName: ns.DB, + } + + return conn.WriteWireMessage(ctx, kc) +} diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_collections.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_collections.go new file mode 100644 index 0000000..60b7ffb --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_collections.go @@ -0,0 +1,133 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driver + +import ( + "context" + + "errors" + + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/description" +) + +// ErrFilterType is thrown when a non-string filter is specified. +var ErrFilterType = errors.New("filter must be a string") + +// ListCollections handles the full cycle dispatch and execution of a listCollections command against the provided +// topology. +func ListCollections( + ctx context.Context, + cmd command.ListCollections, + topo *topology.Topology, + selector description.ServerSelector, + clientID uuid.UUID, + pool *session.Pool, + opts ...*options.ListCollectionsOptions, +) (*ListCollectionsBatchCursor, error) { + + ss, err := topo.SelectServer(ctx, selector) + if err != nil { + return nil, err + } + + conn, err := ss.Connection(ctx) + if err != nil { + return nil, err + } + defer conn.Close() + + if ss.Description().WireVersion.Max < 3 { + return legacyListCollections(ctx, cmd, ss, conn) + } + + rp, err := getReadPrefBasedOnTransaction(cmd.ReadPref, cmd.Session) + if err != nil { + return nil, err + } + cmd.ReadPref = rp + + // If no explicit session and deployment supports sessions, start implicit session. + if cmd.Session == nil && topo.SupportsSessions() { + cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) + if err != nil { + return nil, err + } + } + + lc := options.MergeListCollectionsOptions(opts...) + if lc.NameOnly != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"nameOnly", bsonx.Boolean(*lc.NameOnly)}) + } + + res, err := cmd.RoundTrip(ctx, ss.Description(), conn) + if err != nil { + closeImplicitSession(cmd.Session) + return nil, err + } + + batchCursor, err := NewBatchCursor(bsoncore.Document(res), cmd.Session, cmd.Clock, ss.Server, cmd.CursorOpts...) + if err != nil { + closeImplicitSession(cmd.Session) + return nil, err + } + + return NewListCollectionsBatchCursor(batchCursor) +} + +func legacyListCollections( + ctx context.Context, + cmd command.ListCollections, + ss *topology.SelectedServer, + conn connection.Connection, +) (*ListCollectionsBatchCursor, error) { + filter, err := transformFilter(cmd.Filter, cmd.DB) + if err != nil { + return nil, err + } + + findCmd := command.Find{ + NS: command.NewNamespace(cmd.DB, "system.namespaces"), + ReadPref: cmd.ReadPref, + Filter: filter, + } + + // don't need registry because it's used to create BSON docs for find options that don't exist in this case + batchCursor, err := legacyFind(ctx, findCmd, nil, ss, conn) + if err != nil { + return nil, err + } + + return NewLegacyListCollectionsBatchCursor(batchCursor) +} + +// modify the user-supplied filter to prefix the "name" field with the database name. +// returns the original filter if the name field is not present or a copy with the modified name field if it is +func transformFilter(filter bsonx.Doc, dbName string) (bsonx.Doc, error) { + if filter == nil { + return filter, nil + } + + if nameVal, err := filter.LookupErr("name"); err == nil { + name, ok := nameVal.StringValueOK() + if !ok { + return nil, ErrFilterType + } + + filterCopy := filter.Copy() + filterCopy.Set("name", bsonx.String(dbName+"."+name)) + return filterCopy, nil + } + return filter, nil +} diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_collections_batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_collections_batch_cursor.go new file mode 100644 index 0000000..b3fc7e8 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_collections_batch_cursor.go @@ -0,0 +1,124 @@ +package driver + +import ( + "context" + "errors" + "io" + "strings" + + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" +) + +// ListCollectionsBatchCursor is a special batch cursor returned from ListCollections that properly +// handles current and legacy ListCollections operations. +type ListCollectionsBatchCursor struct { + legacy bool + bc *BatchCursor + currentBatch *bsoncore.DocumentSequence + err error +} + +// NewListCollectionsBatchCursor creates a new non-legacy ListCollectionsCursor. +func NewListCollectionsBatchCursor(bc *BatchCursor) (*ListCollectionsBatchCursor, error) { + if bc == nil { + return nil, errors.New("batch cursor must not be nil") + } + return &ListCollectionsBatchCursor{bc: bc, currentBatch: new(bsoncore.DocumentSequence)}, nil +} + +// NewLegacyListCollectionsBatchCursor creates a new legacy ListCollectionsCursor. +func NewLegacyListCollectionsBatchCursor(bc *BatchCursor) (*ListCollectionsBatchCursor, error) { + if bc == nil { + return nil, errors.New("batch cursor must not be nil") + } + return &ListCollectionsBatchCursor{legacy: true, bc: bc, currentBatch: new(bsoncore.DocumentSequence)}, nil +} + +// ID returns the cursor ID for this batch cursor. +func (lcbc *ListCollectionsBatchCursor) ID() int64 { + return lcbc.bc.ID() +} + +// Next indicates if there is another batch available. Returning false does not necessarily indicate +// that the cursor is closed. This method will return false when an empty batch is returned. +// +// If Next returns true, there is a valid batch of documents available. If Next returns false, there +// is not a valid batch of documents available. +func (lcbc *ListCollectionsBatchCursor) Next(ctx context.Context) bool { + if !lcbc.bc.Next(ctx) { + return false + } + + if !lcbc.legacy { + lcbc.currentBatch.Style = lcbc.bc.currentBatch.Style + lcbc.currentBatch.Data = lcbc.bc.currentBatch.Data + lcbc.currentBatch.ResetIterator() + return true + } + + lcbc.currentBatch.Style = bsoncore.SequenceStyle + lcbc.currentBatch.Data = lcbc.currentBatch.Data[:0] + + var doc bsoncore.Document + for { + doc, lcbc.err = lcbc.bc.currentBatch.Next() + if lcbc.err != nil { + if lcbc.err == io.EOF { + lcbc.err = nil + break + } + return false + } + doc, lcbc.err = lcbc.projectNameElement(doc) + if lcbc.err != nil { + return false + } + lcbc.currentBatch.Data = append(lcbc.currentBatch.Data, doc...) + } + + return true +} + +// Batch will return a DocumentSequence for the current batch of documents. The returned +// DocumentSequence is only valid until the next call to Next or Close. +func (lcbc *ListCollectionsBatchCursor) Batch() *bsoncore.DocumentSequence { return lcbc.currentBatch } + +// Server returns a pointer to the cursor's server. +func (lcbc *ListCollectionsBatchCursor) Server() *topology.Server { return lcbc.bc.server } + +// Err returns the latest error encountered. +func (lcbc *ListCollectionsBatchCursor) Err() error { + if lcbc.err != nil { + return lcbc.err + } + return lcbc.bc.Err() +} + +// Close closes this batch cursor. +func (lcbc *ListCollectionsBatchCursor) Close(ctx context.Context) error { return lcbc.bc.Close(ctx) } + +// project out the database name for a legacy server +func (*ListCollectionsBatchCursor) projectNameElement(rawDoc bsoncore.Document) (bsoncore.Document, error) { + elems, err := rawDoc.Elements() + if err != nil { + return nil, err + } + + var filteredElems []byte + for _, elem := range elems { + key := elem.Key() + if key != "name" { + filteredElems = append(filteredElems, elem...) + continue + } + + name := elem.Value().StringValue() + collName := name[strings.Index(name, ".")+1:] + filteredElems = bsoncore.AppendStringElement(filteredElems, "name", collName) + } + + var filteredDoc []byte + filteredDoc = bsoncore.BuildDocument(filteredDoc, filteredElems) + return filteredDoc, nil +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_databases.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_databases.go similarity index 77% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_databases.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_databases.go index c83f41b..6c2fed7 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/list_databases.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_databases.go @@ -4,19 +4,19 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // ListDatabases handles the full cycle dispatch and execution of a listDatabases command against the provided diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_indexes.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_indexes.go new file mode 100644 index 0000000..956aebc --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/list_indexes.go @@ -0,0 +1,105 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driver + +import ( + "context" + + "time" + + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/description" +) + +// ListIndexes handles the full cycle dispatch and execution of a listIndexes command against the provided +// topology. +func ListIndexes( + ctx context.Context, + cmd command.ListIndexes, + topo *topology.Topology, + selector description.ServerSelector, + clientID uuid.UUID, + pool *session.Pool, + opts ...*options.ListIndexesOptions, +) (*BatchCursor, error) { + + ss, err := topo.SelectServer(ctx, selector) + if err != nil { + return nil, err + } + + conn, err := ss.Connection(ctx) + if err != nil { + return nil, err + } + defer conn.Close() + + if ss.Description().WireVersion.Max < 3 { + return legacyListIndexes(ctx, cmd, ss, conn, opts...) + } + + lio := options.MergeListIndexesOptions(opts...) + if lio.BatchSize != nil { + elem := bsonx.Elem{"batchSize", bsonx.Int32(*lio.BatchSize)} + cmd.Opts = append(cmd.Opts, elem) + cmd.CursorOpts = append(cmd.CursorOpts, elem) + } + if lio.MaxTime != nil { + cmd.Opts = append(cmd.Opts, bsonx.Elem{"maxTimeMS", bsonx.Int64(int64(*lio.MaxTime / time.Millisecond))}) + } + + // If no explicit session and deployment supports sessions, start implicit session. + if cmd.Session == nil && topo.SupportsSessions() { + cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) + if err != nil { + return nil, err + } + } + + res, err := cmd.RoundTrip(ctx, ss.Description(), conn) + if err != nil { + closeImplicitSession(cmd.Session) + return nil, err + } + + return NewBatchCursor(bsoncore.Document(res), cmd.Session, cmd.Clock, ss.Server, cmd.CursorOpts...) +} + +func legacyListIndexes( + ctx context.Context, + cmd command.ListIndexes, + ss *topology.SelectedServer, + conn connection.Connection, + opts ...*options.ListIndexesOptions, +) (*BatchCursor, error) { + lio := options.MergeListIndexesOptions(opts...) + ns := cmd.NS.DB + "." + cmd.NS.Collection + + findCmd := command.Find{ + NS: command.NewNamespace(cmd.NS.DB, "system.indexes"), + Filter: bsonx.Doc{ + {"ns", bsonx.String(ns)}, + }, + } + + findOpts := options.Find() + if lio.BatchSize != nil { + findOpts.SetBatchSize(*lio.BatchSize) + } + if lio.MaxTime != nil { + findOpts.SetMaxTime(*lio.MaxTime) + } + + return legacyFind(ctx, findCmd, nil, ss, conn, findOpts) +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/models.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/models.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/models.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/models.go index 50205ae..3dcb622 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/models.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/models.go @@ -4,10 +4,10 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( - "github.com/mongodb/mongo-go-driver/options" + "go.mongodb.org/mongo-driver/mongo/options" ) // WriteModel is the interface satisfied by all models for bulk writes. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/read.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/read.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/read.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/read.go index cf137ea..55ba927 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/read.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/read.go @@ -4,18 +4,18 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // Read handles the full cycle dispatch and execution of a read command against the provided diff --git a/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/read_cursor.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/read_cursor.go new file mode 100644 index 0000000..49211a2 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/read_cursor.go @@ -0,0 +1,69 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package driver + +import ( + "context" + + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" +) + +// ReadCursor handles the full dispatch cycle and execution of a read command against the provided topology and returns +// a Cursor over the resulting BSON reader. +func ReadCursor( + ctx context.Context, + cmd command.Read, + topo *topology.Topology, + selecctor description.ServerSelector, + clientID uuid.UUID, + pool *session.Pool, + cursorOpts ...bsonx.Elem, +) (*BatchCursor, error) { + + ss, err := topo.SelectServer(ctx, selecctor) + if err != nil { + return nil, err + } + + desc := ss.Description() + conn, err := ss.Connection(ctx) + if err != nil { + return nil, err + } + defer conn.Close() + + if cmd.Session == nil && topo.SupportsSessions() { + cmd.Session, err = session.NewClientSession(pool, clientID, session.Implicit) + if err != nil { + return nil, err + } + } + + rdr, err := cmd.RoundTrip(ctx, desc, conn) + if err != nil { + if cmd.Session != nil && cmd.Session.SessionType == session.Implicit { + cmd.Session.EndSession() + } + return nil, err + } + + cursor, err := NewBatchCursor(bsoncore.Document(rdr), cmd.Session, cmd.Clock, ss.Server, cursorOpts...) + if err != nil { + if cmd.Session != nil && cmd.Session.SessionType == session.Implicit { + cmd.Session.EndSession() + } + return nil, err + } + + return cursor, nil +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/session/client_session.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/client_session.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/core/session/client_session.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/client_session.go index ae2828a..4bc6571 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/session/client_session.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/client_session.go @@ -4,17 +4,17 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package session +package session // import "go.mongodb.org/mongo-driver/x/mongo/driver/session" import ( "errors" - "github.com/mongodb/mongo-go-driver/bson/primitive" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" ) // ErrSessionEnded is returned when a client session is used after a call to endSession(). @@ -63,7 +63,7 @@ const ( type Client struct { *Server ClientID uuid.UUID - ClusterTime bsonx.Doc + ClusterTime bson.Raw Consistent bool // causal consistency OperationTime *primitive.Timestamp SessionType Type @@ -88,7 +88,7 @@ type Client struct { state state } -func getClusterTime(clusterTime bsonx.Doc) (uint32, uint32) { +func getClusterTime(clusterTime bson.Raw) (uint32, uint32) { if clusterTime == nil { return 0, 0 } @@ -98,7 +98,7 @@ func getClusterTime(clusterTime bsonx.Doc) (uint32, uint32) { return 0, 0 } - timestampVal, err := clusterTimeVal.Document().LookupErr("clusterTime") + timestampVal, err := bson.Raw(clusterTimeVal.Value).LookupErr("clusterTime") if err != nil { return 0, 0 } @@ -107,7 +107,7 @@ func getClusterTime(clusterTime bsonx.Doc) (uint32, uint32) { } // MaxClusterTime compares 2 clusterTime documents and returns the document representing the highest cluster time. -func MaxClusterTime(ct1 bsonx.Doc, ct2 bsonx.Doc) bsonx.Doc { +func MaxClusterTime(ct1, ct2 bson.Raw) bson.Raw { epoch1, ord1 := getClusterTime(ct1) epoch2, ord2 := getClusterTime(ct2) @@ -158,7 +158,7 @@ func NewClientSession(pool *Pool, clientID uuid.UUID, sessionType Type, opts ... } // AdvanceClusterTime updates the session's cluster time. -func (c *Client) AdvanceClusterTime(clusterTime bsonx.Doc) error { +func (c *Client) AdvanceClusterTime(clusterTime bson.Raw) error { if c.Terminated { return ErrSessionEnded } @@ -221,7 +221,7 @@ func (c *Client) TransactionStarting() bool { // TransactionRunning returns true if the client session has started the transaction // and it hasn't been committed or aborted func (c *Client) TransactionRunning() bool { - return c.state == Starting || c.state == InProgress + return c != nil && (c.state == Starting || c.state == InProgress) } // TransactionCommitted returns true of the client session just committed a transaciton. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/session/cluster_clock.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/cluster_clock.go similarity index 77% rename from vendor/github.com/mongodb/mongo-go-driver/core/session/cluster_clock.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/cluster_clock.go index 126efd1..961f227 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/session/cluster_clock.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/cluster_clock.go @@ -9,18 +9,18 @@ package session import ( "sync" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" ) // ClusterClock represents a logical clock for keeping track of cluster time. type ClusterClock struct { - clusterTime bsonx.Doc + clusterTime bson.Raw lock sync.Mutex } // GetClusterTime returns the cluster's current time. -func (cc *ClusterClock) GetClusterTime() bsonx.Doc { - var ct bsonx.Doc +func (cc *ClusterClock) GetClusterTime() bson.Raw { + var ct bson.Raw cc.lock.Lock() ct = cc.clusterTime cc.lock.Unlock() @@ -29,7 +29,7 @@ func (cc *ClusterClock) GetClusterTime() bsonx.Doc { } // AdvanceClusterTime updates the cluster's current time. -func (cc *ClusterClock) AdvanceClusterTime(clusterTime bsonx.Doc) { +func (cc *ClusterClock) AdvanceClusterTime(clusterTime bson.Raw) { cc.lock.Lock() cc.clusterTime = MaxClusterTime(cc.clusterTime, clusterTime) cc.lock.Unlock() diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/session/options.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/options.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/session/options.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/options.go index ac10518..faedaa4 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/session/options.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/options.go @@ -7,9 +7,9 @@ package session import ( - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" ) // ClientOptions represents all possible options for creating a client session. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/session/server_session.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/server_session.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/core/session/server_session.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/server_session.go index 081d624..5cd8401 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/session/server_session.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/server_session.go @@ -11,8 +11,8 @@ import ( "crypto/rand" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" ) var rander = rand.Reader diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/session/session_pool.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/session_pool.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/core/session/session_pool.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/session_pool.go index bb8aa69..b471112 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/session/session_pool.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/session/session_pool.go @@ -9,8 +9,8 @@ package session import ( "sync" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/description" ) // Node represents a server session in a linked list diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/connection.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/connection.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/core/topology/connection.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/connection.go index a6b226c..9d16428 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/connection.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/connection.go @@ -12,10 +12,10 @@ import ( "strings" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/connection" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // sconn is a wrapper around a connection.Connection. This type is returned by @@ -48,7 +48,6 @@ func (sc *sconn) WriteWireMessage(ctx context.Context, wm wiremessage.WireMessag } func (sc *sconn) processErr(err error) { - // TODO(GODRIVER-524) handle the rest of sdam error handling // Invalidate server description if not master or node recovering error occurs if cerr, ok := err.(command.Error); ok && (isRecoveringError(cerr) || isNotMasterError(cerr)) { desc := sc.s.Description() @@ -56,9 +55,12 @@ func (sc *sconn) processErr(err error) { desc.LastError = err // updates description to unknown sc.s.updateDescription(desc, false) + sc.s.RequestImmediateCheck() + _ = sc.s.pool.Drain() + return } - ne, ok := err.(connection.NetworkError) + ne, ok := err.(connection.Error) if !ok { return } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/fsm.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/fsm.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/topology/fsm.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/fsm.go index 23a580f..6875f55 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/fsm.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/fsm.go @@ -10,9 +10,9 @@ import ( "bytes" "fmt" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/description" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/description" ) var supportedWireVersions = description.NewVersionRange(2, 6) @@ -21,7 +21,7 @@ var minSupportedMongoDBVersion = "2.6" type fsm struct { description.Topology SetName string - maxElectionID objectid.ObjectID + maxElectionID primitive.ObjectID maxSetVersion uint32 } @@ -196,7 +196,7 @@ func (f *fsm) updateRSFromPrimary(s description.Server) { return } - if s.SetVersion != 0 && !bytes.Equal(s.ElectionID[:], objectid.NilObjectID[:]) { + if s.SetVersion != 0 && !bytes.Equal(s.ElectionID[:], primitive.NilObjectID[:]) { if f.maxSetVersion > s.SetVersion || bytes.Compare(f.maxElectionID[:], s.ElectionID[:]) == 1 { f.replaceServer(description.Server{ Addr: s.Addr, diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/server.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/core/topology/server.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server.go index e267d95..906b636 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/server.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server.go @@ -9,25 +9,27 @@ package topology import ( "context" "errors" + "fmt" "math" + "strings" "sync" "sync/atomic" "time" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/auth" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/connection" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/event" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/event" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) const minHeartbeatInterval = 500 * time.Millisecond const connectionSemaphoreSize = math.MaxInt64 +var isMasterOrRecoveringCodes = []int32{11600, 11602, 10107, 13435, 13436, 189, 91} + // ErrServerClosed occurs when an attempt to get a connection is made after // the server has been closed. var ErrServerClosed = errors.New("server is closed") @@ -37,7 +39,7 @@ var ErrServerClosed = errors.New("server is closed") var ErrServerConnected = errors.New("server is connected") // SelectedServer represents a specific server that was selected during server selection. -// It contains the kind of the typology it was selected from. +// It contains the kind of the topology it was selected from. type SelectedServer struct { *Server @@ -61,6 +63,21 @@ const ( connecting ) +func connectionStateString(state int32) string { + switch state { + case 0: + return "Disconnected" + case 1: + return "Disconnecting" + case 2: + return "Connected" + case 3: + return "Connecting" + } + + return "" +} + // Server is a single server within a topology. type Server struct { cfg *serverConfig @@ -82,12 +99,14 @@ type Server struct { currentSubscriberID uint64 subscriptionsClosed bool + + updateTopologyCallback atomic.Value } // ConnectServer creates a new Server and then initializes it using the // Connect method. -func ConnectServer(ctx context.Context, addr address.Address, opts ...ServerOption) (*Server, error) { - srvr, err := NewServer(addr, opts...) +func ConnectServer(ctx context.Context, addr address.Address, topo func(description.Server), opts ...ServerOption) (*Server, error) { + srvr, err := NewServer(addr, topo, opts...) if err != nil { return nil, err } @@ -100,7 +119,7 @@ func ConnectServer(ctx context.Context, addr address.Address, opts ...ServerOpti // NewServer creates a new server. The mongodb server at the address will be monitored // on an internal monitoring goroutine. -func NewServer(addr address.Address, opts ...ServerOption) (*Server, error) { +func NewServer(addr address.Address, topo func(description.Server), opts ...ServerOption) (*Server, error) { cfg, err := newServerConfig(opts...) if err != nil { return nil, err @@ -116,6 +135,7 @@ func NewServer(addr address.Address, opts ...ServerOption) (*Server, error) { subscribers: make(map[uint64]chan description.Server), } s.desc.Store(description.Server{Addr: addr}) + s.updateTopologyCallback.Store(topo) var maxConns uint64 if cfg.maxConns == 0 { @@ -158,6 +178,8 @@ func (s *Server) Disconnect(ctx context.Context) error { return ErrServerClosed } + s.updateTopologyCallback.Store((func(description.Server))(nil)) + // For every call to Connect there must be at least 1 goroutine that is // waiting on the done channel. s.done <- struct{}{} @@ -255,6 +277,33 @@ func (s *Server) RequestImmediateCheck() { } } +// ProcessWriteConcernError checks if a WriteConcernError is an isNotMaster or +// isRecovering error, and if so updates the server accordingly. +func (s *Server) ProcessWriteConcernError(err *result.WriteConcernError) { + if err == nil || !wceIsNotMasterOrRecovering(err) { + return + } + desc := s.Description() + desc.Kind = description.Unknown + desc.LastError = err + // updates description to unknown + s.updateDescription(desc, false) + s.RequestImmediateCheck() + _ = s.pool.Drain() +} + +func wceIsNotMasterOrRecovering(wce *result.WriteConcernError) bool { + for _, code := range isMasterOrRecoveringCodes { + if int32(wce.Code) == code { + return true + } + } + if strings.Contains(wce.ErrMsg, "not master") || strings.Contains(wce.ErrMsg, "node is recovering") { + return true + } + return false +} + // update handles performing heartbeats and updating any subscribers of the // newest description.Server retrieved. func (s *Server) update() { @@ -329,6 +378,11 @@ func (s *Server) updateDescription(desc description.Server, initial bool) { }() s.desc.Store(desc) + topo := s.updateTopologyCallback.Load().(func(description.Server)) + if topo != nil { + topo(desc) + } + s.subLock.Lock() for _, c := range s.subscribers { select { @@ -370,6 +424,7 @@ func (s *Server) heartbeat(conn connection.Connection) (description.Server, conn opts := []connection.Option{ connection.WithConnectTimeout(func(time.Duration) time.Duration { return s.cfg.heartbeatTimeout }), connection.WithReadTimeout(func(time.Duration) time.Duration { return s.cfg.heartbeatTimeout }), + connection.WithWriteTimeout(func(time.Duration) time.Duration { return s.cfg.heartbeatTimeout }), } opts = append(opts, s.cfg.connectionOpts...) // We override whatever handshaker is currently attached to the options with an empty @@ -389,6 +444,13 @@ func (s *Server) heartbeat(conn connection.Connection) (description.Server, conn conn.Close() } conn = nil + if _, ok := err.(*connection.NetworkError); ok { + _ = s.pool.Drain() + // If the server is not connected, give up and exit loop + if s.Description().Kind == description.Unknown { + break + } + } continue } } @@ -397,10 +459,18 @@ func (s *Server) heartbeat(conn connection.Connection) (description.Server, conn isMasterCmd := &command.IsMaster{Compressors: s.cfg.compressionOpts} isMaster, err := isMasterCmd.RoundTrip(ctx, conn) + // we do a retry if the server is connected, if succeed return new server desc (see below) if err != nil { saved = err conn.Close() conn = nil + if _, ok := err.(connection.NetworkError); ok { + _ = s.pool.Drain() + // If the server is not connected, give up and exit loop + if s.Description().Kind == description.Unknown { + break + } + } continue } @@ -421,6 +491,7 @@ func (s *Server) heartbeat(conn connection.Connection) (description.Server, conn desc = description.Server{ Addr: s.address, LastError: saved, + Kind: description.Unknown, } } @@ -445,9 +516,23 @@ func (s *Server) updateAverageRTT(delay time.Duration) time.Duration { // logic for handling errors in the Client type. func (s *Server) Drain() error { return s.pool.Drain() } -// BuildCursor implements the command.CursorBuilder interface for the Server type. -func (s *Server) BuildCursor(result bson.Raw, clientSession *session.Client, clock *session.ClusterClock, opts ...bsonx.Elem) (command.Cursor, error) { - return newCursor(result, clientSession, clock, s, opts...) +// String implements the Stringer interface. +func (s *Server) String() string { + desc := s.Description() + connState := atomic.LoadInt32(&s.connectionstate) + str := fmt.Sprintf("Addr: %s, Type: %s, State: %s", + s.address, desc.Kind, connectionStateString(connState)) + if len(desc.Tags) != 0 { + str += fmt.Sprintf(", Tag sets: %s", desc.Tags) + } + if connState == connected { + str += fmt.Sprintf(", Average RTT: %d", desc.AverageRTT) + } + if desc.LastError != nil { + str += fmt.Sprintf(", Last error: %s", desc.LastError) + } + + return str } // ServerSubscription represents a subscription to the description.Server updates for diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/server_options.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server_options.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/core/topology/server_options.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server_options.go index 994dfce..1acf573 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/server_options.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server_options.go @@ -9,10 +9,10 @@ package topology import ( "time" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/connection" - "github.com/mongodb/mongo-go-driver/core/session" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/connection" ) var defaultRegistry = bson.NewRegistryBuilder().Build() @@ -32,7 +32,7 @@ type serverConfig struct { func newServerConfig(opts ...ServerOption) (*serverConfig, error) { cfg := &serverConfig{ heartbeatInterval: 10 * time.Second, - heartbeatTimeout: 30 * time.Second, + heartbeatTimeout: 10 * time.Second, maxConns: 100, maxIdleConns: 100, registry: defaultRegistry, diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/topology.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/core/topology/topology.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology.go index 8ab7149..52f1019 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/topology.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology.go @@ -8,7 +8,7 @@ // of servers. This package is designed to expose enough inner workings of service discovery // and monitoring to allow low level applications to have fine grained control, while hiding // most of the detailed implementation of the algorithms. -package topology +package topology // import "go.mongodb.org/mongo-driver/x/mongo/driver/topology" import ( "context" @@ -18,10 +18,12 @@ import ( "sync/atomic" "time" - "github.com/mongodb/mongo-go-driver/bson/bsoncodec" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" + "fmt" + + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/description" ) // ErrSubscribeAfterClosed is returned when a user attempts to subscribe to a @@ -61,9 +63,7 @@ type Topology struct { done chan struct{} - fsm *fsm - changes chan description.Server - changeswg sync.WaitGroup + fsm *fsm SessionPool *session.Pool @@ -82,8 +82,6 @@ type Topology struct { serversLock sync.Mutex serversClosed bool servers map[address.Address]*Server - - wg sync.WaitGroup } // New creates a new topology. @@ -97,7 +95,6 @@ func New(opts ...Option) (*Topology, error) { cfg: cfg, done: make(chan struct{}), fsm: newFSM(), - changes: make(chan description.Server), subscribers: make(map[uint64]chan description.Topology), servers: make(map[address.Address]*Server), } @@ -132,9 +129,6 @@ func (t *Topology) Connect(ctx context.Context) error { } t.serversLock.Unlock() - go t.update() - t.changeswg.Add(1) - t.subscriptionsClosed = false // explicitly set in case topology was disconnected and then reconnected atomic.StoreInt32(&t.connectionstate, connected) @@ -152,16 +146,25 @@ func (t *Topology) Disconnect(ctx context.Context) error { return ErrTopologyClosed } + servers := make(map[address.Address]*Server) t.serversLock.Lock() t.serversClosed = true for addr, server := range t.servers { - t.removeServer(ctx, addr, server) + servers[addr] = server } t.serversLock.Unlock() - t.wg.Wait() - t.done <- struct{}{} - t.changeswg.Wait() + for _, server := range servers { + _ = server.Disconnect(ctx) + } + + t.subLock.Lock() + for id, ch := range t.subscribers { + close(ch) + delete(t.subscribers, id) + } + t.subscriptionsClosed = true + t.subLock.Unlock() t.desc.Store(description.Topology{}) @@ -289,6 +292,10 @@ func (t *Topology) FindServer(selected description.Server) (*SelectedServer, err }, nil } +func wrapServerSelectionError(err error, t *Topology) error { + return fmt.Errorf("server selection error: %v\ncurrent topology: %s", err, t.String()) +} + // selectServer is the core piece of server selection. It handles getting // topology descriptions and running sever selection on those descriptions. func (t *Topology) selectServer(ctx context.Context, subscriptionCh <-chan description.Topology, ss description.ServerSelector, timeoutCh <-chan time.Time) ([]description.Server, error) { @@ -298,7 +305,7 @@ func (t *Topology) selectServer(ctx context.Context, subscriptionCh <-chan descr case <-ctx.Done(): return nil, ctx.Err() case <-timeoutCh: - return nil, ErrServerSelectionTimeout + return nil, wrapServerSelectionError(ErrServerSelectionTimeout, t) case current = <-subscriptionCh: } @@ -311,7 +318,7 @@ func (t *Topology) selectServer(ctx context.Context, subscriptionCh <-chan descr suitable, err := ss.SelectServer(current, allowed) if err != nil { - return nil, err + return nil, wrapServerSelectionError(err, t) } if len(suitable) > 0 { @@ -322,74 +329,53 @@ func (t *Topology) selectServer(ctx context.Context, subscriptionCh <-chan descr } } -func (t *Topology) update() { - defer t.changeswg.Done() - defer func() { - // ¯\_(ツ)_/¯ - if r := recover(); r != nil { - <-t.done - } - }() +func (t *Topology) apply(ctx context.Context, desc description.Server) { + var err error - for { - select { - case change := <-t.changes: - current, err := t.apply(context.TODO(), change) - if err != nil { - continue - } + t.serversLock.Lock() + defer t.serversLock.Unlock() - t.desc.Store(current) - t.subLock.Lock() - for _, ch := range t.subscribers { - // We drain the description if there's one in the channel - select { - case <-ch: - default: - } - ch <- current - } - t.subLock.Unlock() - case <-t.done: - t.subLock.Lock() - for id, ch := range t.subscribers { - close(ch) - delete(t.subscribers, id) - } - t.subscriptionsClosed = true - t.subLock.Unlock() - return - } + if _, ok := t.servers[desc.Addr]; t.serversClosed || !ok { + return } -} -func (t *Topology) apply(ctx context.Context, desc description.Server) (description.Topology, error) { - var err error prev := t.fsm.Topology current, err := t.fsm.apply(desc) if err != nil { - return description.Topology{}, err + return } diff := description.DiffTopology(prev, current) - t.serversLock.Lock() - if t.serversClosed { - t.serversLock.Unlock() - return description.Topology{}, nil - } for _, removed := range diff.Removed { if s, ok := t.servers[removed.Addr]; ok { - t.removeServer(ctx, removed.Addr, s) + go func() { + cancelCtx, cancel := context.WithCancel(ctx) + cancel() + _ = s.Disconnect(cancelCtx) + }() + delete(t.servers, removed.Addr) } } for _, added := range diff.Added { _ = t.addServer(ctx, added.Addr) } - t.serversLock.Unlock() - return current, nil + + t.desc.Store(current) + + t.subLock.Lock() + for _, ch := range t.subscribers { + // We drain the description if there's one in the channel + select { + case <-ch: + default: + } + ch <- current + } + t.subLock.Unlock() + } func (t *Topology) addServer(ctx context.Context, addr address.Address) error { @@ -397,33 +383,27 @@ func (t *Topology) addServer(ctx context.Context, addr address.Address) error { return nil } - svr, err := ConnectServer(ctx, addr, t.cfg.serverOpts...) - if err != nil { - return err + topoFunc := func(desc description.Server) { + t.apply(context.TODO(), desc) } - - t.servers[addr] = svr - var sub *ServerSubscription - sub, err = svr.Subscribe() + svr, err := ConnectServer(ctx, addr, topoFunc, t.cfg.serverOpts...) if err != nil { return err } - t.wg.Add(1) - go func() { - for c := range sub.C { - t.changes <- c - } - - t.wg.Done() - }() + t.servers[addr] = svr return nil } -func (t *Topology) removeServer(ctx context.Context, addr address.Address, server *Server) { - _ = server.Disconnect(ctx) - delete(t.servers, addr) +// String implements the Stringer interface +func (t *Topology) String() string { + desc := t.Description() + str := fmt.Sprintf("Type: %s\nServers:\n", desc.Kind) + for _, s := range t.servers { + str += s.String() + "\n" + } + return str } // Subscription is a subscription to updates to the description of the Topology that created this diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/topology/topology_options.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology_options.go similarity index 86% rename from vendor/github.com/mongodb/mongo-go-driver/core/topology/topology_options.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology_options.go index 12650e5..0abb24e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/topology/topology_options.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/topology/topology_options.go @@ -11,11 +11,10 @@ import ( "strings" "time" - "github.com/mongodb/mongo-go-driver/core/auth" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/compressor" - "github.com/mongodb/mongo-go-driver/core/connection" - "github.com/mongodb/mongo-go-driver/core/connstring" + "go.mongodb.org/mongo-driver/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/connection" + "go.mongodb.org/mongo-driver/x/network/connstring" ) // Option is a configuration option for a topology. @@ -70,6 +69,7 @@ func WithConnString(fn func(connstring.ConnString) connstring.ConnString) Option c.seedList = cs.Hosts if cs.ConnectTimeout > 0 { + c.serverOpts = append(c.serverOpts, WithHeartbeatTimeout(func(time.Duration) time.Duration { return cs.ConnectTimeout })) connOpts = append(connOpts, connection.WithConnectTimeout(func(time.Duration) time.Duration { return cs.ConnectTimeout })) } @@ -89,16 +89,9 @@ func WithConnString(fn func(connstring.ConnString) connstring.ConnString) Option connOpts = append(connOpts, connection.WithIdleTimeout(func(time.Duration) time.Duration { return cs.MaxConnIdleTime })) } - if cs.MaxConnLifeTime > 0 { - connOpts = append(connOpts, connection.WithIdleTimeout(func(time.Duration) time.Duration { return cs.MaxConnLifeTime })) - } - - if cs.MaxConnsPerHostSet { - c.serverOpts = append(c.serverOpts, WithMaxConnections(func(uint16) uint16 { return cs.MaxConnsPerHost })) - } - - if cs.MaxIdleConnsPerHostSet { - c.serverOpts = append(c.serverOpts, WithMaxIdleConnections(func(uint16) uint16 { return cs.MaxIdleConnsPerHost })) + if cs.MaxPoolSizeSet { + c.serverOpts = append(c.serverOpts, WithMaxConnections(func(uint16) uint16 { return cs.MaxPoolSize })) + c.serverOpts = append(c.serverOpts, WithMaxIdleConnections(func(uint16) uint16 { return cs.MaxPoolSize })) } if cs.ReplicaSet != "" { @@ -197,26 +190,18 @@ func WithConnString(fn func(connstring.ConnString) connstring.ConnString) Option } if len(cs.Compressors) > 0 { - comp := make([]compressor.Compressor, 0, len(cs.Compressors)) - - for _, c := range cs.Compressors { - switch c { - case "snappy": - comp = append(comp, compressor.CreateSnappy()) - case "zlib": - zlibComp, err := compressor.CreateZlib(cs.ZlibLevel) - if err != nil { - return err - } + connOpts = append(connOpts, connection.WithCompressors(func(compressors []string) []string { + return append(compressors, cs.Compressors...) + })) - comp = append(comp, zlibComp) + for _, comp := range cs.Compressors { + if comp == "zlib" { + connOpts = append(connOpts, connection.WithZlibLevel(func(level *int) *int { + return &cs.ZlibLevel + })) } } - connOpts = append(connOpts, connection.WithCompressors(func(compressors []compressor.Compressor) []compressor.Compressor { - return append(compressors, comp...) - })) - c.serverOpts = append(c.serverOpts, WithCompressionOptions(func(opts ...string) []string { return append(opts, cs.Compressors...) })) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/update.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/update.go similarity index 70% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/update.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/update.go index 792ceab..18be34b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/update.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/update.go @@ -4,21 +4,21 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/options" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/mongo/options" + "go.mongodb.org/mongo-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" ) // Update handles the full cycle dispatch and execution of an update command against the provided @@ -54,10 +54,18 @@ func Update( if ss.Description().WireVersion.Max < 6 { return result.Update{}, ErrArrayFilters } - arr, err := updateOpts.ArrayFilters.ToArray() + filters, err := updateOpts.ArrayFilters.ToArray() if err != nil { return result.Update{}, err } + arr := make(bsonx.Arr, 0, len(filters)) + for _, filter := range filters { + doc, err := bsonx.ReadDoc(filter) + if err != nil { + return result.Update{}, err + } + arr = append(arr, bsonx.Document(doc)) + } cmd.Opts = append(cmd.Opts, bsonx.Elem{"arrayFilters", bsonx.Array(arr)}) } if updateOpts.BypassDocumentValidation != nil && ss.Description().WireVersion.Includes(4) { @@ -67,7 +75,11 @@ func Update( if ss.Description().WireVersion.Max < 5 { return result.Update{}, ErrCollation } - cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(updateOpts.Collation.ToDocument())}) + collDoc, err := bsonx.ReadDoc(updateOpts.Collation.ToDocument()) + if err != nil { + return result.Update{}, err + } + cmd.Opts = append(cmd.Opts, bsonx.Elem{"collation", bsonx.Document(collDoc)}) } if updateOpts.Upsert != nil { cmd.Opts = append(cmd.Opts, bsonx.Elem{"upsert", bsonx.Boolean(*updateOpts.Upsert)}) @@ -78,17 +90,17 @@ func Update( if cmd.Session != nil { cmd.Session.RetryWrite = false // explicitly set to false to prevent encoding transaction number } - return update(ctx, cmd, ss, nil) + return update(ctx, &cmd, ss, nil) } cmd.Session.RetryWrite = retryWrite cmd.Session.IncrementTxnNumber() - res, originalErr := update(ctx, cmd, ss, nil) + res, originalErr := update(ctx, &cmd, ss, nil) // Retry if appropriate - if cerr, ok := originalErr.(command.Error); ok && cerr.Retryable() || - res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError) { + if cerr, ok := originalErr.(command.Error); (ok && cerr.Retryable()) || + (res.WriteConcernError != nil && command.IsWriteConcernErrorRetryable(res.WriteConcernError)) { ss, err := topo.SelectServer(ctx, selector) // Return original error if server selection fails or new server does not support retryable writes @@ -96,7 +108,7 @@ func Update( return res, originalErr } - return update(ctx, cmd, ss, cerr) + return update(ctx, &cmd, ss, cerr) } return res, originalErr @@ -104,7 +116,7 @@ func Update( func update( ctx context.Context, - cmd command.Update, + cmd *command.Update, ss *topology.SelectedServer, oldErr error, ) (result.Update, error) { @@ -130,5 +142,7 @@ func update( } defer conn.Close() - return cmd.RoundTrip(ctx, desc, conn) + res, err := cmd.RoundTrip(ctx, desc, conn) + ss.ProcessWriteConcernError(res.WriteConcernError) + return res, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/uuid/uuid.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/uuid/uuid.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/core/uuid/uuid.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/uuid/uuid.go index 7ad5eea..83a6785 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/uuid/uuid.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/uuid/uuid.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package uuid +package uuid // import "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" import ( "bytes" diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/write.go b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/write.go similarity index 82% rename from vendor/github.com/mongodb/mongo-go-driver/core/dispatch/write.go rename to vendor/go.mongodb.org/mongo-driver/x/mongo/driver/write.go index 0b43f0d..d4c81a4 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/dispatch/write.go +++ b/vendor/go.mongodb.org/mongo-driver/x/mongo/driver/write.go @@ -4,18 +4,18 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package dispatch +package driver import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/command" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/topology" - "github.com/mongodb/mongo-go-driver/core/uuid" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/mongo/driver/topology" + "go.mongodb.org/mongo-driver/x/mongo/driver/uuid" + "go.mongodb.org/mongo-driver/x/network/command" + "go.mongodb.org/mongo-driver/x/network/description" ) // Write handles the full cycle dispatch and execution of a write command against the provided diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/address/addr.go b/vendor/go.mongodb.org/mongo-driver/x/network/address/addr.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/core/address/addr.go rename to vendor/go.mongodb.org/mongo-driver/x/network/address/addr.go index c2a3bb7..1244a8b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/address/addr.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/address/addr.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package address +package address // import "go.mongodb.org/mongo-driver/x/network/address" import ( "net" diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/abort_transaction.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/abort_transaction.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/abort_transaction.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/abort_transaction.go index b766c9d..439cc66 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/abort_transaction.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/abort_transaction.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // AbortTransaction represents the abortTransaction() command diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/aggregate.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/aggregate.go similarity index 69% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/aggregate.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/aggregate.go index 42b5df2..f3a68e5 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/aggregate.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/aggregate.go @@ -9,14 +9,15 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Aggregate represents the aggregate command. @@ -33,7 +34,7 @@ type Aggregate struct { Clock *session.ClusterClock Session *session.Client - result Cursor + result bson.Raw err error } @@ -58,11 +59,12 @@ func (a *Aggregate) encode(desc description.SelectedServer) (*Read, error) { } cursor := bsonx.Doc{} + hasOutStage := a.HasDollarOut() for _, opt := range a.Opts { switch opt.Key { case "batchSize": - if opt.Value.Int32() == 0 && a.HasDollarOut() { + if opt.Value.Int32() == 0 && hasOutStage { continue } cursor = append(cursor, opt) @@ -73,13 +75,17 @@ func (a *Aggregate) encode(desc description.SelectedServer) (*Read, error) { command = append(command, bsonx.Elem{"cursor", bsonx.Document(cursor)}) // add write concern because it won't be added by the Read command's Encode() - if a.WriteConcern != nil { - element, err := a.WriteConcern.MarshalBSONElement() + if desc.WireVersion.Max >= 5 && hasOutStage && a.WriteConcern != nil { + t, data, err := a.WriteConcern.MarshalBSONValue() if err != nil { return nil, err } - - command = append(command, element) + var xval bsonx.Val + err = xval.UnmarshalBSONValue(t, data) + if err != nil { + return nil, err + } + command = append(command, bsonx.Elem{Key: "writeConcern", Value: xval}) } return &Read{ @@ -112,30 +118,28 @@ func (a *Aggregate) HasDollarOut() bool { // Decode will decode the wire message using the provided server description. Errors during decoding // are deferred until either the Result or Err methods are called. -func (a *Aggregate) Decode(desc description.SelectedServer, cb CursorBuilder, wm wiremessage.WireMessage) *Aggregate { +func (a *Aggregate) Decode(desc description.SelectedServer, wm wiremessage.WireMessage) *Aggregate { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { a.err = err return a } - return a.decode(desc, cb, rdr) + return a.decode(desc, rdr) } -func (a *Aggregate) decode(desc description.SelectedServer, cb CursorBuilder, rdr bson.Raw) *Aggregate { - labels, err := getErrorLabels(&rdr) - a.err = err - - res, err := cb.BuildCursor(rdr, a.Session, a.Clock, a.CursorOpts...) - a.result = res - if err != nil { - a.err = Error{Message: err.Error(), Labels: labels} +func (a *Aggregate) decode(desc description.SelectedServer, rdr bson.Raw) *Aggregate { + a.result = rdr + if val, err := rdr.LookupErr("writeConcernError"); err == nil { + var wce result.WriteConcernError + _ = val.Unmarshal(&wce) + a.err = wce } return a } // Result returns the result of a decoded wire message and server description. -func (a *Aggregate) Result() (Cursor, error) { +func (a *Aggregate) Result() (bson.Raw, error) { if a.err != nil { return nil, a.err } @@ -146,7 +150,7 @@ func (a *Aggregate) Result() (Cursor, error) { func (a *Aggregate) Err() error { return a.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. -func (a *Aggregate) RoundTrip(ctx context.Context, desc description.SelectedServer, cb CursorBuilder, rw wiremessage.ReadWriter) (Cursor, error) { +func (a *Aggregate) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (bson.Raw, error) { cmd, err := a.encode(desc) if err != nil { return nil, err @@ -157,5 +161,5 @@ func (a *Aggregate) RoundTrip(ctx context.Context, desc description.SelectedServ return nil, err } - return a.decode(desc, cb, rdr).Result() + return a.decode(desc, rdr).Result() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/buildinfo.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/buildinfo.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/buildinfo.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/buildinfo.go index c053593..550fb3d 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/buildinfo.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/buildinfo.go @@ -10,10 +10,10 @@ import ( "context" "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // BuildInfo represents the buildInfo command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/command.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/command.go similarity index 82% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/command.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/command.go index 6d0c5eb..e05b69e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/command.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/command.go @@ -4,24 +4,26 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package command +package command // import "go.mongodb.org/mongo-driver/x/network/command" import ( "errors" "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/bson/primitive" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "fmt" + + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // WriteBatch represents a single batch for a write operation. @@ -131,20 +133,17 @@ func extractError(rdr bson.Raw) error { } } -func responseClusterTime(response bson.Raw) bsonx.Doc { +func responseClusterTime(response bson.Raw) bson.Raw { clusterTime, err := response.LookupErr("$clusterTime") if err != nil { // $clusterTime not included by the server return nil } - - val := bsonx.Val{} - err = val.UnmarshalBSONValue(clusterTime.Type, clusterTime.Value) - if err != nil { - return nil - } - - return bsonx.Doc{{"$clusterTime", val}} + idx, doc := bsoncore.AppendDocumentStart(nil) + doc = bsoncore.AppendHeader(doc, clusterTime.Type, "$clusterTime") + doc = append(doc, clusterTime.Value...) + doc, _ = bsoncore.AppendDocumentEnd(doc, idx) + return doc } func updateClusterTimes(sess *session.Client, clock *session.ClusterClock, response bson.Raw) error { @@ -234,7 +233,7 @@ func addClusterTime(cmd bsonx.Doc, desc description.SelectedServer, sess *sessio return cmd } - var clusterTime bsonx.Doc + var clusterTime bson.Raw if clock != nil { clusterTime = clock.GetClusterTime() } @@ -251,9 +250,14 @@ func addClusterTime(cmd bsonx.Doc, desc description.SelectedServer, sess *sessio return cmd } + d, err := bsonx.ReadDoc(clusterTime) + if err != nil { + return cmd // broken clusterTime + } + cmd = cmd.Delete("$clusterTime") - return append(cmd, clusterTime...) + return append(cmd, d...) } // add a read concern to a BSON doc representing a command @@ -272,17 +276,21 @@ func addReadConcern(cmd bsonx.Doc, desc description.SelectedServer, rc *readconc return cmd, nil } - element, err := rc.MarshalBSONElement() + t, data, err := rc.MarshalBSONValue() if err != nil { return cmd, err } - rcDoc := element.Value.Document() + var rcDoc bsonx.Doc + err = rcDoc.UnmarshalBSONValue(t, data) + if err != nil { + return cmd, err + } if description.SessionsSupported(desc.WireVersion) && sess != nil && sess.Consistent && sess.OperationTime != nil { rcDoc = append(rcDoc, bsonx.Elem{"afterClusterTime", bsonx.Timestamp(sess.OperationTime.T, sess.OperationTime.I)}) } - cmd = cmd.Delete(element.Key) + cmd = cmd.Delete("readConcern") if len(rcDoc) != 0 { cmd = append(cmd, bsonx.Elem{"readConcern", bsonx.Document(rcDoc)}) @@ -296,15 +304,24 @@ func addWriteConcern(cmd bsonx.Doc, wc *writeconcern.WriteConcern) (bsonx.Doc, e return cmd, nil } - element, err := wc.MarshalBSONElement() + t, data, err := wc.MarshalBSONValue() + if err != nil { + if err == writeconcern.ErrEmptyWriteConcern { + return cmd, nil + } + return cmd, err + } + + var xval bsonx.Val + err = xval.UnmarshalBSONValue(t, data) if err != nil { return cmd, err } // delete if doc already has write concern - cmd = cmd.Delete(element.Key) + cmd = cmd.Delete("writeConcern") - return append(cmd, element), nil + return append(cmd, bsonx.Elem{Key: "writeConcern", Value: xval}), nil } // Get the error labels from a command response @@ -611,6 +628,71 @@ func roundTripBatches( return res, batches, nil } +// get the firstBatch, cursor ID, and namespace from a bson.Raw +func getCursorValues(result bson.Raw) ([]bson.RawValue, Namespace, int64, error) { + cur, err := result.LookupErr("cursor") + if err != nil { + return nil, Namespace{}, 0, err + } + if cur.Type != bson.TypeEmbeddedDocument { + return nil, Namespace{}, 0, fmt.Errorf("cursor should be an embedded document but it is a BSON %s", cur.Type) + } + + elems, err := cur.Document().Elements() + if err != nil { + return nil, Namespace{}, 0, err + } + + var ok bool + var arr bson.Raw + var namespace Namespace + var cursorID int64 + + for _, elem := range elems { + switch elem.Key() { + case "firstBatch": + arr, ok = elem.Value().ArrayOK() + if !ok { + return nil, Namespace{}, 0, fmt.Errorf("firstBatch should be an array but it is a BSON %s", elem.Value().Type) + } + if err != nil { + return nil, Namespace{}, 0, err + } + case "ns": + if elem.Value().Type != bson.TypeString { + return nil, Namespace{}, 0, fmt.Errorf("namespace should be a string but it is a BSON %s", elem.Value().Type) + } + namespace = ParseNamespace(elem.Value().StringValue()) + err = namespace.Validate() + if err != nil { + return nil, Namespace{}, 0, err + } + case "id": + cursorID, ok = elem.Value().Int64OK() + if !ok { + return nil, Namespace{}, 0, fmt.Errorf("id should be an int64 but it is a BSON %s", elem.Value().Type) + } + } + } + + vals, err := arr.Values() + if err != nil { + return nil, Namespace{}, 0, err + } + + return vals, namespace, cursorID, nil +} + +func getBatchSize(opts []bsonx.Elem) int32 { + for _, opt := range opts { + if opt.Key == "batchSize" { + return opt.Value.Int32() + } + } + + return 0 +} + // ErrUnacknowledgedWrite is returned from functions that have an unacknowledged // write concern. var ErrUnacknowledgedWrite = errors.New("unacknowledged write") diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/commit_transaction.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/commit_transaction.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/commit_transaction.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/commit_transaction.go index 9a46fed..2051bc0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/commit_transaction.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/commit_transaction.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // CommitTransaction represents the commitTransaction() command diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/count.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/count.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/count.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/count.go index d07c7e2..0d5404b 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/count.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/count.go @@ -10,14 +10,14 @@ import ( "context" "errors" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Count represents the count command. @@ -92,6 +92,8 @@ func (c *Count) decode(desc description.SelectedServer, rdr bson.Raw) *Count { c.result = int64(val.Int32()) case bson.TypeInt64: c.result = val.Int64() + case bson.TypeDouble: + c.result = int64(val.Double()) default: c.err = errors.New("invalid response from server, value field is not a number") } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/count_documents.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/count_documents.go similarity index 62% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/count_documents.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/count_documents.go index eafe9db..d69a9e4 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/count_documents.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/count_documents.go @@ -10,13 +10,13 @@ import ( "context" "errors" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // CountDocuments represents the CountDocuments command. @@ -45,53 +45,50 @@ func (c *CountDocuments) Encode(desc description.SelectedServer) (wiremessage.Wi command = append(command, bsonx.Elem{"cursor", bsonx.Document(bsonx.Doc{})}) command = append(command, c.Opts...) - return (&Read{DB: c.NS.DB, ReadPref: c.ReadPref, Command: command}).Encode(desc) + return (&Read{DB: c.NS.DB, ReadPref: c.ReadPref, Command: command, Session: c.Session}).Encode(desc) } // Decode will decode the wire message using the provided server description. Errors during decoding // are deferred until either the Result or Err methods are called. -func (c *CountDocuments) Decode(ctx context.Context, desc description.SelectedServer, cb CursorBuilder, wm wiremessage.WireMessage) *CountDocuments { +func (c *CountDocuments) Decode(ctx context.Context, desc description.SelectedServer, wm wiremessage.WireMessage) *CountDocuments { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { c.err = err return c } - cur, err := cb.BuildCursor(rdr, c.Session, c.Clock) - if err != nil { - c.err = err + + cursor, err := rdr.LookupErr("cursor") + if err != nil || cursor.Type != bsontype.EmbeddedDocument { + c.err = errors.New("Invalid response from server, no 'cursor' field") + return c + } + batch, err := cursor.Document().LookupErr("firstBatch") + if err != nil || batch.Type != bsontype.Array { + c.err = errors.New("Invalid response from server, no 'firstBatch' field") return c } - var doc bsonx.Doc - if cur.Next(ctx) { - err = cur.Decode(&doc) - if err != nil { - c.err = err - return c - } - val, err := doc.LookupErr("n") - switch err.(type) { - case bsonx.KeyNotFound: - c.err = errors.New("Invalid response from server, no 'n' field") - return c - case nil: - default: - c.err = err - return c - } - switch val.Type() { - case bson.TypeInt32: - c.result = int64(val.Int32()) - case bson.TypeInt64: - c.result = val.Int64() - default: - c.err = errors.New("Invalid response from server, value field is not a number") - } + elem, err := batch.Array().IndexErr(0) + if err != nil || elem.Value().Type != bsontype.EmbeddedDocument { + c.result = 0 + return c + } + val, err := elem.Value().Document().LookupErr("n") + if err != nil { + c.err = errors.New("Invalid response from server, no 'n' field") return c } - c.result = 0 + switch val.Type { + case bsontype.Int32: + c.result = int64(val.Int32()) + case bsontype.Int64: + c.result = val.Int64() + default: + c.err = errors.New("Invalid response from server, value field is not a number") + } + return c } @@ -107,7 +104,7 @@ func (c *CountDocuments) Result() (int64, error) { func (c *CountDocuments) Err() error { return c.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. -func (c *CountDocuments) RoundTrip(ctx context.Context, desc description.SelectedServer, cb CursorBuilder, rw wiremessage.ReadWriter) (int64, error) { +func (c *CountDocuments) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (int64, error) { wm, err := c.Encode(desc) if err != nil { return 0, err @@ -121,5 +118,5 @@ func (c *CountDocuments) RoundTrip(ctx context.Context, desc description.Selecte if err != nil { return 0, err } - return c.Decode(ctx, desc, cb, wm).Result() + return c.Decode(ctx, desc, wm).Result() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/create_indexes.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/create_indexes.go similarity index 82% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/create_indexes.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/create_indexes.go index 4bdcdb1..06c632a 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/create_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/create_indexes.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // CreateIndexes represents the createIndexes command. @@ -50,13 +50,16 @@ func (ci *CreateIndexes) encode(desc description.SelectedServer) (*Write, error) } cmd = append(cmd, ci.Opts...) - return &Write{ - Clock: ci.Clock, - DB: ci.NS.DB, - Command: cmd, - WriteConcern: ci.WriteConcern, - Session: ci.Session, - }, nil + write := &Write{ + Clock: ci.Clock, + DB: ci.NS.DB, + Command: cmd, + Session: ci.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 5 { + write.WriteConcern = ci.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/delete.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/delete.go similarity index 90% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/delete.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/delete.go index f453ad6..effbbce 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/delete.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/delete.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Delete represents the delete command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/distinct.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/distinct.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/distinct.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/distinct.go index 31267fb..0360152 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/distinct.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/distinct.go @@ -9,14 +9,14 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Distinct represents the disctinct command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/doc.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/doc.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/doc.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/doc.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/drop_collection.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/drop_collection.go similarity index 82% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/drop_collection.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/drop_collection.go index ce61f67..7719a41 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/drop_collection.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/drop_collection.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // DropCollection represents the drop command. @@ -44,13 +44,16 @@ func (dc *DropCollection) Encode(desc description.SelectedServer) (wiremessage.W func (dc *DropCollection) encode(desc description.SelectedServer) (*Write, error) { cmd := bsonx.Doc{{"drop", bsonx.String(dc.Collection)}} - return &Write{ - Clock: dc.Clock, - WriteConcern: dc.WriteConcern, - DB: dc.DB, - Command: cmd, - Session: dc.Session, - }, nil + write := &Write{ + Clock: dc.Clock, + DB: dc.DB, + Command: cmd, + Session: dc.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 5 { + write.WriteConcern = dc.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/drop_database.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/drop_database.go similarity index 81% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/drop_database.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/drop_database.go index 503b415..5c81ae5 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/drop_database.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/drop_database.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // DropDatabase represents the DropDatabase command. @@ -43,13 +43,16 @@ func (dd *DropDatabase) Encode(desc description.SelectedServer) (wiremessage.Wir func (dd *DropDatabase) encode(desc description.SelectedServer) (*Write, error) { cmd := bsonx.Doc{{"dropDatabase", bsonx.Int32(1)}} - return &Write{ - Clock: dd.Clock, - DB: dd.DB, - Command: cmd, - WriteConcern: dd.WriteConcern, - Session: dd.Session, - }, nil + write := &Write{ + Clock: dd.Clock, + DB: dd.DB, + Command: cmd, + Session: dd.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 5 { + write.WriteConcern = dd.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/drop_indexes.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/drop_indexes.go similarity index 82% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/drop_indexes.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/drop_indexes.go index 378c5d8..0c916b0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/drop_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/drop_indexes.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // DropIndexes represents the dropIndexes command. @@ -49,13 +49,16 @@ func (di *DropIndexes) encode(desc description.SelectedServer) (*Write, error) { } cmd = append(cmd, di.Opts...) - return &Write{ - Clock: di.Clock, - DB: di.NS.DB, - Command: cmd, - WriteConcern: di.WriteConcern, - Session: di.Session, - }, nil + write := &Write{ + Clock: di.Clock, + DB: di.NS.DB, + Command: cmd, + Session: di.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 5 { + write.WriteConcern = di.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/end_sessions.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/end_sessions.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/end_sessions.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/end_sessions.go index cffe7fa..e402878 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/end_sessions.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/end_sessions.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // must be sent to admin db diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/errors.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/errors.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/errors.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/errors.go index a3c827c..ab424ef 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/errors.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/errors.go @@ -12,8 +12,8 @@ import ( "strings" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/result" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/network/result" ) var ( @@ -36,6 +36,8 @@ var ( TransientTransactionError = "TransientTransactionError" // NetworkError is an error label for network errors. NetworkError = "NetworkError" + // ReplyDocumentMismatch is an error label for OP_QUERY field mismatch errors. + ReplyDocumentMismatch = "malformed OP_REPLY: NumberReturned does not match number of documents returned" ) var retryableCodes = []int32{11600, 11602, 10107, 13435, 13436, 189, 91, 7, 6, 89, 9001} @@ -134,5 +136,6 @@ func IsWriteConcernErrorRetryable(wce *result.WriteConcernError) bool { // IsNotFound indicates if the error is from a namespace not being found. func IsNotFound(err error) bool { e, ok := err.(Error) - return ok && (e.Code == 26) + // need message check because legacy servers don't include the error code + return ok && (e.Code == 26 || e.Message == "ns not found") } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/find.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/find.go similarity index 70% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/find.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/find.go index e1e30d8..711e8e0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/find.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/find.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Find represents the find command. @@ -31,7 +31,7 @@ type Find struct { Clock *session.ClusterClock Session *session.Client - result Cursor + result bson.Raw err error } @@ -70,30 +70,23 @@ func (f *Find) encode(desc description.SelectedServer) (*Read, error) { // Decode will decode the wire message using the provided server description. Errors during decoding // are deferred until either the Result or Err methods are called. -func (f *Find) Decode(desc description.SelectedServer, cb CursorBuilder, wm wiremessage.WireMessage) *Find { +func (f *Find) Decode(desc description.SelectedServer, wm wiremessage.WireMessage) *Find { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { f.err = err return f } - return f.decode(desc, cb, rdr) + return f.decode(desc, rdr) } -func (f *Find) decode(desc description.SelectedServer, cb CursorBuilder, rdr bson.Raw) *Find { - labels, err := getErrorLabels(&rdr) - f.err = err - - res, err := cb.BuildCursor(rdr, f.Session, f.Clock, f.CursorOpts...) - f.result = res - if err != nil { - f.err = Error{Message: err.Error(), Labels: labels} - } +func (f *Find) decode(desc description.SelectedServer, rdr bson.Raw) *Find { + f.result = rdr return f } // Result returns the result of a decoded wire message and server description. -func (f *Find) Result() (Cursor, error) { +func (f *Find) Result() (bson.Raw, error) { if f.err != nil { return nil, f.err } @@ -105,7 +98,7 @@ func (f *Find) Result() (Cursor, error) { func (f *Find) Err() error { return f.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. -func (f *Find) RoundTrip(ctx context.Context, desc description.SelectedServer, cb CursorBuilder, rw wiremessage.ReadWriter) (Cursor, error) { +func (f *Find) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (bson.Raw, error) { cmd, err := f.encode(desc) if err != nil { return nil, err @@ -116,5 +109,5 @@ func (f *Find) RoundTrip(ctx context.Context, desc description.SelectedServer, c return nil, err } - return f.decode(desc, cb, rdr).Result() + return f.decode(desc, rdr).Result() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_and_modify.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_and_modify.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/find_and_modify.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/find_and_modify.go index bf9f70d..604fe67 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_and_modify.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_and_modify.go @@ -9,9 +9,9 @@ package command import ( "errors" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/network/result" ) // unmarshalFindAndModifyResult turns the provided bson.Reader into a findAndModify result. @@ -47,5 +47,8 @@ func unmarshalFindAndModifyResult(rdr bson.Raw) (result.FindAndModify, error) { res.LastErrorObject.Upserted = oid } } + if val, err := rdr.LookupErr("writeConcernError"); err == nil { + _ = val.Unmarshal(&res.WriteConcernError) + } return res, nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_delete.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_delete.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_delete.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_delete.go index 5aff1f6..195ebce 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_delete.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_delete.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // FindOneAndDelete represents the findOneAndDelete operation. @@ -55,13 +55,16 @@ func (f *FindOneAndDelete) encode(desc description.SelectedServer) (*Write, erro } command = append(command, f.Opts...) - return &Write{ - Clock: f.Clock, - DB: f.NS.DB, - Command: command, - WriteConcern: f.WriteConcern, - Session: f.Session, - }, nil + write := &Write{ + Clock: f.Clock, + DB: f.NS.DB, + Command: command, + Session: f.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 4 { + write.WriteConcern = f.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_replace.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_replace.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_replace.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_replace.go index 4beae01..e64823a 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_replace.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_replace.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // FindOneAndReplace represents the findOneAndReplace operation. @@ -56,13 +56,16 @@ func (f *FindOneAndReplace) encode(desc description.SelectedServer) (*Write, err } command = append(command, f.Opts...) - return &Write{ - Clock: f.Clock, - DB: f.NS.DB, - Command: command, - WriteConcern: f.WriteConcern, - Session: f.Session, - }, nil + write := &Write{ + Clock: f.Clock, + DB: f.NS.DB, + Command: command, + Session: f.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 4 { + write.WriteConcern = f.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_update.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_update.go similarity index 83% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_update.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_update.go index 0221584..97749b0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/find_one_update.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/find_one_update.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // FindOneAndUpdate represents the findOneAndUpdate operation. @@ -56,13 +56,16 @@ func (f *FindOneAndUpdate) encode(desc description.SelectedServer) (*Write, erro } command = append(command, f.Opts...) - return &Write{ - Clock: f.Clock, - DB: f.NS.DB, - Command: command, - WriteConcern: f.WriteConcern, - Session: f.Session, - }, nil + write := &Write{ + Clock: f.Clock, + DB: f.NS.DB, + Command: command, + Session: f.Session, + } + if desc.WireVersion != nil && desc.WireVersion.Max >= 4 { + write.WriteConcern = f.WriteConcern + } + return write, nil } // Decode will decode the wire message using the provided server description. Errors during decoding diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/get_more.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/get_more.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/get_more.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/get_more.go index fc08b96..0b04d26 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/get_more.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/get_more.go @@ -9,11 +9,11 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // GetMore represents the getMore command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/getlasterror.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/getlasterror.go similarity index 88% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/getlasterror.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/getlasterror.go index 269e792..f5f3b47 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/getlasterror.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/getlasterror.go @@ -11,13 +11,13 @@ import ( "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // GetLastError represents the getLastError command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/handshake.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/handshake.go similarity index 90% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/handshake.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/handshake.go index c6dfdca..122c39e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/handshake.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/handshake.go @@ -10,12 +10,12 @@ import ( "context" "runtime" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/version" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/version" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Handshake represents a generic MongoDB Handshake. It calls isMaster and diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/insert.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/insert.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/insert.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/insert.go index 7786da5..dc8a0bd 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/insert.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/insert.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // this is the amount of reserved buffer space in a message that the diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/ismaster.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/ismaster.go similarity index 90% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/ismaster.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/ismaster.go index 49561dd..9fdae6c 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/ismaster.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/ismaster.go @@ -10,10 +10,11 @@ import ( "context" "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // IsMaster represents the isMaster command. @@ -84,7 +85,7 @@ func (im *IsMaster) Decode(wm wiremessage.WireMessage) *IsMaster { // Reconstructs the $clusterTime doc after decode if im.res.ClusterTime != nil { - im.res.ClusterTime = bsonx.Doc{{"$clusterTime", bsonx.Document(im.res.ClusterTime)}} + im.res.ClusterTime = bsoncore.BuildDocument(nil, bsoncore.AppendDocumentElement(nil, "$clusterTime", im.res.ClusterTime)) } return im } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/kill_cursors.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/kill_cursors.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/kill_cursors.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/kill_cursors.go index 3b30676..289ff54 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/kill_cursors.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/kill_cursors.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // KillCursors represents the killCursors command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/list_collections.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/list_collections.go similarity index 72% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/list_collections.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/list_collections.go index c63492f..e29daba 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/list_collections.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/list_collections.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // ListCollections represents the listCollections command. @@ -29,7 +29,7 @@ type ListCollections struct { ReadPref *readpref.ReadPref Session *session.Client - result Cursor + result bson.Raw err error } @@ -61,30 +61,22 @@ func (lc *ListCollections) encode(desc description.SelectedServer) (*Read, error // Decode will decode the wire message using the provided server description. Errors during decolcng // are deferred until either the Result or Err methods are called. -func (lc *ListCollections) Decode(desc description.SelectedServer, cb CursorBuilder, wm wiremessage.WireMessage) *ListCollections { +func (lc *ListCollections) Decode(desc description.SelectedServer, wm wiremessage.WireMessage) *ListCollections { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { lc.err = err return lc } - return lc.decode(desc, cb, rdr) + return lc.decode(desc, rdr) } -func (lc *ListCollections) decode(desc description.SelectedServer, cb CursorBuilder, rdr bson.Raw) *ListCollections { - labels, err := getErrorLabels(&rdr) - lc.err = err - - res, err := cb.BuildCursor(rdr, lc.Session, lc.Clock, lc.CursorOpts...) - lc.result = res - if err != nil { - lc.err = Error{Message: err.Error(), Labels: labels} - } - +func (lc *ListCollections) decode(desc description.SelectedServer, rdr bson.Raw) *ListCollections { + lc.result = rdr return lc } // Result returns the result of a decoded wire message and server description. -func (lc *ListCollections) Result() (Cursor, error) { +func (lc *ListCollections) Result() (bson.Raw, error) { if lc.err != nil { return nil, lc.err } @@ -95,7 +87,7 @@ func (lc *ListCollections) Result() (Cursor, error) { func (lc *ListCollections) Err() error { return lc.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. -func (lc *ListCollections) RoundTrip(ctx context.Context, desc description.SelectedServer, cb CursorBuilder, rw wiremessage.ReadWriter) (Cursor, error) { +func (lc *ListCollections) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (bson.Raw, error) { cmd, err := lc.encode(desc) if err != nil { return nil, err @@ -106,5 +98,5 @@ func (lc *ListCollections) RoundTrip(ctx context.Context, desc description.Selec return nil, err } - return lc.decode(desc, cb, rdr).Result() + return lc.decode(desc, rdr).Result() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/list_databases.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/list_databases.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/list_databases.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/list_databases.go index efa9b77..79cb2c6 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/list_databases.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/list_databases.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // ListDatabases represents the listDatabases command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/list_indexes.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/list_indexes.go similarity index 67% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/list_indexes.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/list_indexes.go index 69f007a..b8ada7c 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/list_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/list_indexes.go @@ -8,14 +8,18 @@ package command import ( "context" + "errors" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) +// ErrEmptyCursor is a signaling error when a cursor for list indexes is empty. +var ErrEmptyCursor = errors.New("empty cursor") + // ListIndexes represents the listIndexes command. // // The listIndexes command lists the indexes for a namespace. @@ -26,7 +30,7 @@ type ListIndexes struct { Opts []bsonx.Elem Session *session.Client - result Cursor + result bson.Raw err error } @@ -53,35 +57,27 @@ func (li *ListIndexes) encode(desc description.SelectedServer) (*Read, error) { // Decode will decode the wire message using the provided server description. Errors during decoling // are deferred until either the Result or Err methods are called. -func (li *ListIndexes) Decode(desc description.SelectedServer, cb CursorBuilder, wm wiremessage.WireMessage) *ListIndexes { +func (li *ListIndexes) Decode(desc description.SelectedServer, wm wiremessage.WireMessage) *ListIndexes { rdr, err := (&Read{}).Decode(desc, wm).Result() if err != nil { if IsNotFound(err) { - li.result = emptyCursor{} + li.err = ErrEmptyCursor return li } li.err = err return li } - return li.decode(desc, cb, rdr) + return li.decode(desc, rdr) } -func (li *ListIndexes) decode(desc description.SelectedServer, cb CursorBuilder, rdr bson.Raw) *ListIndexes { - labels, err := getErrorLabels(&rdr) - li.err = err - - res, err := cb.BuildCursor(rdr, li.Session, li.Clock, li.CursorOpts...) - li.result = res - if err != nil { - li.err = Error{Message: err.Error(), Labels: labels} - } - +func (li *ListIndexes) decode(desc description.SelectedServer, rdr bson.Raw) *ListIndexes { + li.result = rdr return li } // Result returns the result of a decoded wire message and server description. -func (li *ListIndexes) Result() (Cursor, error) { +func (li *ListIndexes) Result() (bson.Raw, error) { if li.err != nil { return nil, li.err } @@ -92,7 +88,7 @@ func (li *ListIndexes) Result() (Cursor, error) { func (li *ListIndexes) Err() error { return li.err } // RoundTrip handles the execution of this command using the provided wiremessage.ReadWriter. -func (li *ListIndexes) RoundTrip(ctx context.Context, desc description.SelectedServer, cb CursorBuilder, rw wiremessage.ReadWriter) (Cursor, error) { +func (li *ListIndexes) RoundTrip(ctx context.Context, desc description.SelectedServer, rw wiremessage.ReadWriter) (bson.Raw, error) { cmd, err := li.encode(desc) if err != nil { return nil, err @@ -101,10 +97,10 @@ func (li *ListIndexes) RoundTrip(ctx context.Context, desc description.SelectedS rdr, err := cmd.RoundTrip(ctx, desc, rw) if err != nil { if IsNotFound(err) { - return emptyCursor{}, nil + return nil, ErrEmptyCursor } return nil, err } - return li.decode(desc, cb, rdr).Result() + return li.decode(desc, rdr).Result() } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/namespace.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/namespace.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/namespace.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/namespace.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/opmsg.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/opmsg.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/opmsg.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/opmsg.go index 1ac0db1..969cd01 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/opmsg.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/opmsg.go @@ -7,9 +7,9 @@ package command import ( - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) func decodeCommandOpMsg(msg wiremessage.Msg) (bson.Raw, error) { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/opreply.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/opreply.go similarity index 92% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/opreply.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/opreply.go index fc06db1..e709c8c 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/opreply.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/opreply.go @@ -7,8 +7,8 @@ package command import ( - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // decodeCommandOpReply handles decoding the OP_REPLY response to an OP_QUERY diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/read.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/read.go similarity index 82% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/read.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/read.go index 3848bff..bda6d23 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/read.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/read.go @@ -11,13 +11,13 @@ import ( "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/readconcern" - "github.com/mongodb/mongo-go-driver/mongo/readpref" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/readconcern" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Read represents a generic database read command. @@ -33,19 +33,33 @@ type Read struct { err error } -func (r *Read) createReadPref(kind description.ServerKind) bsonx.Doc { - if r.ReadPref == nil { +func (r *Read) createReadPref(serverKind description.ServerKind, topologyKind description.TopologyKind, isOpQuery bool) bsonx.Doc { + doc := bsonx.Doc{} + rp := r.ReadPref + + if rp == nil { + if topologyKind == description.Single && serverKind != description.Mongos { + return append(doc, bsonx.Elem{"mode", bsonx.String("primaryPreferred")}) + } return nil } - doc := bsonx.Doc{} - - switch r.ReadPref.Mode() { + switch rp.Mode() { case readpref.PrimaryMode: + if serverKind == description.Mongos { + return nil + } + if topologyKind == description.Single { + return append(doc, bsonx.Elem{"mode", bsonx.String("primaryPreferred")}) + } doc = append(doc, bsonx.Elem{"mode", bsonx.String("primary")}) case readpref.PrimaryPreferredMode: doc = append(doc, bsonx.Elem{"mode", bsonx.String("primaryPreferred")}) case readpref.SecondaryPreferredMode: + _, ok := r.ReadPref.MaxStaleness() + if serverKind == description.Mongos && isOpQuery && !ok && len(r.ReadPref.TagSets()) == 0 { + return nil + } doc = append(doc, bsonx.Elem{"mode", bsonx.String("secondaryPreferred")}) case readpref.SecondaryMode: doc = append(doc, bsonx.Elem{"mode", bsonx.String("secondary")}) @@ -78,8 +92,8 @@ func (r *Read) createReadPref(kind description.ServerKind) bsonx.Doc { // addReadPref will add a read preference to the query document. // // NOTE: This method must always return either a valid bson.Reader or an error. -func (r *Read) addReadPref(rp *readpref.ReadPref, kind description.ServerKind, query bson.Raw) (bson.Raw, error) { - doc := r.createReadPref(kind) +func (r *Read) addReadPref(rp *readpref.ReadPref, serverKind description.ServerKind, topologyKind description.TopologyKind, query bson.Raw) (bson.Raw, error) { + doc := r.createReadPref(serverKind, topologyKind, true) if doc == nil { return query, nil } @@ -102,7 +116,7 @@ func (r *Read) encodeOpMsg(desc description.SelectedServer, cmd bsonx.Doc) (wire Sections: make([]wiremessage.Section, 0), } - readPrefDoc := r.createReadPref(desc.Server.Kind) + readPrefDoc := r.createReadPref(desc.Server.Kind, desc.Kind, false) fullDocRdr, err := opmsgAddGlobals(cmd, r.DB, readPrefDoc) if err != nil { return nil, err @@ -136,22 +150,6 @@ func (r *Read) slaveOK(desc description.SelectedServer) wiremessage.QueryFlag { return 0 } -// return true if a read preference needs to be added when encoding r as a OP_QUERY message -func (r *Read) queryNeedsReadPref(kind description.ServerKind) bool { - if kind != description.Mongos || r.ReadPref == nil { - return false - } - - // simple Primary or SecondaryPreferred is communicated via slaveOk to Mongos. - if r.ReadPref.Mode() == readpref.PrimaryMode || r.ReadPref.Mode() == readpref.SecondaryPreferredMode { - if _, ok := r.ReadPref.MaxStaleness(); !ok && len(r.ReadPref.TagSets()) == 0 { - return false - } - } - - return true -} - // Encode c as OP_QUERY func (r *Read) encodeOpQuery(desc description.SelectedServer, cmd bsonx.Doc) (wiremessage.WireMessage, error) { rdr, err := marshalCommand(cmd) @@ -159,8 +157,8 @@ func (r *Read) encodeOpQuery(desc description.SelectedServer, cmd bsonx.Doc) (wi return nil, err } - if r.queryNeedsReadPref(desc.Server.Kind) { - rdr, err = r.addReadPref(r.ReadPref, desc.Server.Kind, rdr) + if desc.Server.Kind == description.Mongos { + rdr, err = r.addReadPref(r.ReadPref, desc.Server.Kind, desc.Kind, rdr) if err != nil { return nil, err } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/start_session.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/start_session.go similarity index 87% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/start_session.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/start_session.go index 1d0eb45..c925f63 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/start_session.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/start_session.go @@ -9,12 +9,12 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // StartSession represents a startSession command diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/update.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/update.go similarity index 91% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/update.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/update.go index f362715..5ec03e4 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/update.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/update.go @@ -9,13 +9,13 @@ package command import ( "context" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/result" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Update represents the update command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/command/write.go b/vendor/go.mongodb.org/mongo-driver/x/network/command/write.go similarity index 95% rename from vendor/github.com/mongodb/mongo-go-driver/core/command/write.go rename to vendor/go.mongodb.org/mongo-driver/x/network/command/write.go index 2097498..8ed3693 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/command/write.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/command/write.go @@ -12,12 +12,12 @@ import ( "errors" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/session" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/mongo/driver/session" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Write represents a generic write database command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/compressor/compression.go b/vendor/go.mongodb.org/mongo-driver/x/network/compressor/compression.go similarity index 84% rename from vendor/github.com/mongodb/mongo-go-driver/core/compressor/compression.go rename to vendor/go.mongodb.org/mongo-driver/x/network/compressor/compression.go index 5bd8f6f..3bcf3b8 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/compressor/compression.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/compressor/compression.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package compressor +package compressor // import "go.mongodb.org/mongo-driver/x/network/compressor" import ( "bytes" @@ -13,7 +13,7 @@ import ( "io" "github.com/golang/snappy" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Compressor is the interface implemented by types that can compress and decompress wire messages. This is used @@ -83,22 +83,23 @@ func (s *SnappyCompressor) Name() string { // CompressBytes uses zlib to compress a slice of bytes. func (z *ZlibCompressor) CompressBytes(src, dest []byte) ([]byte, error) { - dest = dest[:0] - z.zlibWriter.Reset(&writer{ - buf: dest, - }) + output := &writer{ + buf: dest[:0], + } + + z.zlibWriter.Reset(output) _, err := z.zlibWriter.Write(src) if err != nil { _ = z.zlibWriter.Close() - return dest, err + return output.buf, err } err = z.zlibWriter.Close() if err != nil { - return dest, err + return output.buf, err } - return dest, nil + return output.buf, nil } // UncompressBytes uses zlib to uncompress a slice of bytes. It assumes dest is empty and is the exact size that it @@ -138,20 +139,32 @@ func CreateSnappy() Compressor { } // CreateZlib creates a zlib compressor -func CreateZlib(level int) (Compressor, error) { - if level < 0 { - level = wiremessage.DefaultZlibLevel +func CreateZlib(level *int) (Compressor, error) { + var l int + + if level == nil { + l = wiremessage.DefaultZlibLevel + } else { + l = *level + } + + if l < zlib.NoCompression { + l = wiremessage.DefaultZlibLevel + } + + if l > zlib.BestCompression { + l = zlib.BestCompression } var compressBuf bytes.Buffer - zlibWriter, err := zlib.NewWriterLevel(&compressBuf, level) + zlibWriter, err := zlib.NewWriterLevel(&compressBuf, l) if err != nil { return &ZlibCompressor{}, err } return &ZlibCompressor{ - level: level, + level: l, zlibWriter: zlibWriter, }, nil } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/addr.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/addr.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/addr.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/addr.go diff --git a/vendor/go.mongodb.org/mongo-driver/x/network/connection/command_metadata.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/command_metadata.go new file mode 100644 index 0000000..222f6f7 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/command_metadata.go @@ -0,0 +1,28 @@ +package connection + +import "time" + +// commandMetadata contains metadata about a command sent to the server. +type commandMetadata struct { + Name string + Time time.Time + Legacy bool + FullCollectionName string +} + +// createMetadata creates metadata for a command. +func createMetadata(name string, legacy bool, fullCollName string) *commandMetadata { + return &commandMetadata{ + Name: name, + Time: time.Now(), + Legacy: legacy, + FullCollectionName: fullCollName, + } +} + +// TimeDifference returns the difference between now and the time a command was sent in nanoseconds. +func (cm *commandMetadata) TimeDifference() int64 { + t := time.Now() + duration := t.Sub(cm.Time) + return duration.Nanoseconds() +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/connection.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/connection.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/connection.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/connection.go index c8beda6..04c0bb2 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/connection/connection.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/connection.go @@ -11,7 +11,7 @@ // writing to and reading from a connection to wireops.Op's. This package also provides types for // listening for and accepting Connections, as well as some types for handling connections and // proxying connections to another server. -package connection +package connection // import "go.mongodb.org/mongo-driver/x/network/connection" import ( "context" @@ -24,17 +24,19 @@ import ( "sync/atomic" "time" - "github.com/mongodb/mongo-go-driver/bson/bsontype" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/compressor" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/event" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsontype" + "go.mongodb.org/mongo-driver/event" + "go.mongodb.org/mongo-driver/x/bsonx" + "go.mongodb.org/mongo-driver/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/compressor" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) var globalClientConnectionID uint64 -var emptyDoc = bsonx.Doc{} +var emptyDoc bson.Raw func nextClientConnectionID() uint64 { return atomic.AddUint64(&globalClientConnectionID, 1) @@ -93,7 +95,7 @@ type connection struct { compressor compressor.Compressor // use for compressing messages // server can compress response with any compressor supported by driver compressorMap map[wiremessage.CompressorID]compressor.Compressor - commandMap map[int64]*event.CommandMetadata // map for monitoring commands sent to server + commandMap map[int64]*commandMetadata // map for monitoring commands sent to server dead bool idleTimeout time.Duration idleDeadline time.Time @@ -138,7 +140,18 @@ func New(ctx context.Context, addr address.Address, opts ...Option) (Connection, compressorMap := make(map[wiremessage.CompressorID]compressor.Compressor) for _, comp := range cfg.compressors { - compressorMap[comp.CompressorID()] = comp + switch comp { + case "snappy": + snappyComp := compressor.CreateSnappy() + compressorMap[snappyComp.CompressorID()] = snappyComp + case "zlib": + zlibComp, err := compressor.CreateZlib(cfg.zlibLevel) + if err != nil { + return nil, nil, err + } + + compressorMap[zlibComp.CompressorID()] = zlibComp + } } c := &connection{ @@ -146,7 +159,7 @@ func New(ctx context.Context, addr address.Address, opts ...Option) (Connection, conn: nc, compressBuf: make([]byte, 256), compressorMap: compressorMap, - commandMap: make(map[int64]*event.CommandMetadata), + commandMap: make(map[int64]*commandMetadata), addr: addr, idleTimeout: cfg.idleTimeout, lifetimeDeadline: lifetimeDeadline, @@ -169,7 +182,7 @@ func New(ctx context.Context, addr address.Address, opts ...Option) (Connection, if len(d.Compression) > 0 { clientMethodLoop: - for _, comp := range cfg.compressors { + for _, comp := range c.compressorMap { method := comp.Name() for _, serverMethod := range d.Compression { @@ -323,7 +336,7 @@ func (c *connection) uncompressMessage(compressed wiremessage.Compressed) ([]byt c.uncompressBuf = make([]byte, 0, compressed.UncompressedSize) } - uncompressedMessage, err := uncompressor.UncompressBytes(compressed.CompressedMessage, c.uncompressBuf) + uncompressedMessage, err := uncompressor.UncompressBytes(compressed.CompressedMessage, c.uncompressBuf[:compressed.UncompressedSize]) if err != nil { return nil, 0, err @@ -370,23 +383,22 @@ func (c *connection) commandStartedEvent(ctx context.Context, wm wiremessage.Wir var cmd bsonx.Doc var err error + var legacy bool + var fullCollName string var acknowledged bool switch converted := wm.(type) { case wiremessage.Query: - cmd, err = bsonx.ReadDoc([]byte(converted.Query)) + cmd, err = converted.CommandDocument() if err != nil { return err } acknowledged = converted.AcknowledgedWrite() - startedEvent.DatabaseName = converted.FullCollectionName[:len(converted.FullCollectionName)-5] // remove $.cmd + startedEvent.DatabaseName = converted.DatabaseName() startedEvent.RequestID = int64(converted.MsgHeader.RequestID) - - cmdElem := cmd[0] - if cmdElem.Key == "$query" { - cmd = cmdElem.Value.Document() - } + legacy = converted.Legacy() + fullCollName = converted.FullCollectionName case wiremessage.Msg: cmd, err = converted.GetMainDocument() if err != nil { @@ -410,9 +422,22 @@ func (c *connection) commandStartedEvent(ctx context.Context, wm wiremessage.Wir startedEvent.DatabaseName = dbVal.StringValue() startedEvent.RequestID = int64(converted.MsgHeader.RequestID) + case wiremessage.GetMore: + cmd = converted.CommandDocument() + startedEvent.DatabaseName = converted.DatabaseName() + startedEvent.RequestID = int64(converted.MsgHeader.RequestID) + acknowledged = true + legacy = true + fullCollName = converted.FullCollectionName + case wiremessage.KillCursors: + cmd = converted.CommandDocument() + startedEvent.DatabaseName = converted.DatabaseName + startedEvent.RequestID = int64(converted.MsgHeader.RequestID) + legacy = true } - startedEvent.Command = cmd + rawcmd, _ := cmd.MarshalBSON() + startedEvent.Command = rawcmd startedEvent.CommandName = cmd[0].Key if !canMonitor(startedEvent.CommandName) { startedEvent.Command = emptyDoc @@ -435,13 +460,13 @@ func (c *connection) commandStartedEvent(ctx context.Context, wm wiremessage.Wir c.cmdMonitor.Succeeded(ctx, &event.CommandSucceededEvent{ CommandFinishedEvent: finishedEvent, - Reply: bsonx.Doc{{"ok", bsonx.Int32(1)}}, + Reply: bsoncore.BuildDocument(nil, bsoncore.AppendInt32Element(nil, "ok", 1)), }) return nil } - c.commandMap[startedEvent.RequestID] = event.CreateMetadata(startedEvent.CommandName) + c.commandMap[startedEvent.RequestID] = createMetadata(startedEvent.CommandName, legacy, fullCollName) return nil } @@ -498,18 +523,26 @@ func (c *connection) commandFinishedEvent(ctx context.Context, wm wiremessage.Wi switch converted := wm.(type) { case wiremessage.Reply: requestID = int64(converted.MsgHeader.ResponseTo) - reply, err = converted.GetMainDocument() case wiremessage.Msg: requestID = int64(converted.MsgHeader.ResponseTo) - reply, err = converted.GetMainDocument() } + cmdMetadata := c.commandMap[requestID] + delete(c.commandMap, requestID) + switch converted := wm.(type) { + case wiremessage.Reply: + if cmdMetadata.Legacy { + reply, err = converted.GetMainLegacyDocument(cmdMetadata.FullCollectionName) + } else { + reply, err = converted.GetMainDocument() + } + case wiremessage.Msg: + reply, err = converted.GetMainDocument() + } if err != nil { return err } - cmdMetadata := c.commandMap[requestID] - delete(c.commandMap, requestID) success, errmsg := processReply(reply) if (success && c.cmdMonitor.Succeeded == nil) || (!success && c.cmdMonitor.Failed == nil) { @@ -545,8 +578,9 @@ func (c *connection) commandFinishedEvent(ctx context.Context, wm wiremessage.Wi } } + replyraw, _ := reply.MarshalBSON() successEvent := &event.CommandSucceededEvent{ - Reply: reply, + Reply: replyraw, CommandFinishedEvent: finishedEvent, } diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/error.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/error.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/error.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/error.go diff --git a/vendor/go.mongodb.org/mongo-driver/x/network/connection/keepalive_300.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/keepalive_300.go new file mode 100644 index 0000000..554e38d --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/keepalive_300.go @@ -0,0 +1,13 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +//+build !go1.12 + +package connection + +import "time" + +const tcpKeepalive = 300 * time.Second diff --git a/vendor/go.mongodb.org/mongo-driver/x/network/connection/keepalive_default.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/keepalive_default.go new file mode 100644 index 0000000..9eeeb69 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/keepalive_default.go @@ -0,0 +1,11 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +//+build go1.12 + +package connection + +const tcpKeepalive = 0 // will be set by default on Go 1.12 and higher diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/listener.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/listener.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/listener.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/listener.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/options.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/options.go similarity index 89% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/options.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/options.go index 5f6a219..e3c8fe7 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/connection/options.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/options.go @@ -10,8 +10,7 @@ import ( "net" "time" - "github.com/mongodb/mongo-go-driver/core/compressor" - "github.com/mongodb/mongo-go-driver/core/event" + "go.mongodb.org/mongo-driver/event" ) type config struct { @@ -25,7 +24,8 @@ type config struct { readTimeout time.Duration writeTimeout time.Duration tlsConfig *TLSConfig - compressors []compressor.Compressor + compressors []string + zlibLevel *int } func newConfig(opts ...Option) (*config, error) { @@ -44,7 +44,10 @@ func newConfig(opts ...Option) (*config, error) { } if cfg.dialer == nil { - cfg.dialer = &net.Dialer{Timeout: cfg.connectTimeout} + cfg.dialer = &net.Dialer{ + KeepAlive: tcpKeepalive, + Timeout: cfg.connectTimeout, + } } return cfg, nil @@ -63,7 +66,7 @@ func WithAppName(fn func(string) string) Option { } // WithCompressors sets the compressors that can be used for communication. -func WithCompressors(fn func([]compressor.Compressor) []compressor.Compressor) Option { +func WithCompressors(fn func([]string) []string) Option { return func(c *config) error { c.compressors = fn(c.compressors) return nil @@ -143,3 +146,11 @@ func WithMonitor(fn func(*event.CommandMonitor) *event.CommandMonitor) Option { return nil } } + +// WithZlibLevel sets the zLib compression level. +func WithZlibLevel(fn func(*int) *int) Option { + return func(c *config) error { + c.zlibLevel = fn(c.zlibLevel) + return nil + } +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/pool.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/pool.go similarity index 98% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/pool.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/pool.go index e4a58e8..823a110 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/connection/pool.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/pool.go @@ -11,9 +11,9 @@ import ( "sync" "sync/atomic" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/description" - "github.com/mongodb/mongo-go-driver/core/wiremessage" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/description" + "go.mongodb.org/mongo-driver/x/network/wiremessage" "golang.org/x/sync/semaphore" ) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/proxy.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/proxy.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/proxy.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/proxy.go index a0d6846..eafd905 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/connection/proxy.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connection/proxy.go @@ -6,7 +6,7 @@ package connection -import "github.com/mongodb/mongo-go-driver/core/wiremessage" +import "go.mongodb.org/mongo-driver/x/network/wiremessage" // Proxy implements a MongoDB proxy. It will use the given pool to connect to a // MongoDB server and proxy the traffic between connections it is given and the diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/server.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/server.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/server.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/server.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/tlsconfig.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/tlsconfig.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/tlsconfig.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/tlsconfig.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connection/tlsconfig_clone_17.go b/vendor/go.mongodb.org/mongo-driver/x/network/connection/tlsconfig_clone_17.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/connection/tlsconfig_clone_17.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connection/tlsconfig_clone_17.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/connstring/connstring.go b/vendor/go.mongodb.org/mongo-driver/x/network/connstring/connstring.go similarity index 94% rename from vendor/github.com/mongodb/mongo-go-driver/core/connstring/connstring.go rename to vendor/go.mongodb.org/mongo-driver/x/network/connstring/connstring.go index b517952..56b198c 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/connstring/connstring.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/connstring/connstring.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package connstring +package connstring // import "go.mongodb.org/mongo-driver/x/network/connstring" import ( "errors" @@ -16,9 +16,9 @@ import ( "strings" "time" - "github.com/mongodb/mongo-go-driver/core/wiremessage" - "github.com/mongodb/mongo-go-driver/internal" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/internal" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/network/wiremessage" ) // Parse parses the provided uri and returns a URI object. @@ -53,11 +53,8 @@ type ConnString struct { LocalThresholdSet bool MaxConnIdleTime time.Duration MaxConnIdleTimeSet bool - MaxConnLifeTime time.Duration - MaxConnsPerHost uint16 - MaxConnsPerHostSet bool - MaxIdleConnsPerHost uint16 - MaxIdleConnsPerHostSet bool + MaxPoolSize uint16 + MaxPoolSizeSet bool Password string PasswordSet bool ReadConcernLevel string @@ -87,6 +84,7 @@ type ConnString struct { WNumberSet bool Username string ZlibLevel int + ZlibLevelSet bool WTimeout time.Duration WTimeoutSet bool @@ -489,8 +487,8 @@ func (p *parser) addOption(pair string) error { p.Compressors = compressors case "connect": switch strings.ToLower(value) { - case "auto", "automatic": - case "direct", "single": + case "automatic": + case "direct": p.Connect = SingleConnect default: return fmt.Errorf("invalid 'connect' value: %s", value) @@ -529,20 +527,6 @@ func (p *parser) addOption(pair string) error { } p.LocalThreshold = time.Duration(n) * time.Millisecond p.LocalThresholdSet = true - case "maxconnsperhost": - n, err := strconv.Atoi(value) - if err != nil || n < 0 { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - p.MaxConnsPerHost = uint16(n) - p.MaxConnsPerHostSet = true - case "maxidleconnsperhost": - n, err := strconv.Atoi(value) - if err != nil || n < 0 { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - p.MaxIdleConnsPerHost = uint16(n) - p.MaxIdleConnsPerHostSet = true case "maxidletimems": n, err := strconv.Atoi(value) if err != nil || n < 0 { @@ -550,21 +534,13 @@ func (p *parser) addOption(pair string) error { } p.MaxConnIdleTime = time.Duration(n) * time.Millisecond p.MaxConnIdleTimeSet = true - case "maxlifetimems": - n, err := strconv.Atoi(value) - if err != nil || n < 0 { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - p.MaxConnLifeTime = time.Duration(n) * time.Millisecond case "maxpoolsize": n, err := strconv.Atoi(value) if err != nil || n < 0 { return fmt.Errorf("invalid value for %s: %s", key, value) } - p.MaxConnsPerHost = uint16(n) - p.MaxConnsPerHostSet = true - p.MaxIdleConnsPerHost = uint16(n) - p.MaxIdleConnsPerHostSet = true + p.MaxPoolSize = uint16(n) + p.MaxPoolSizeSet = true case "readconcernlevel": p.ReadConcernLevel = value case "readpreference": @@ -598,12 +574,14 @@ func (p *parser) addOption(pair string) error { return fmt.Errorf("invalid value for %s: %s", key, value) } p.ServerSelectionTimeout = time.Duration(n) * time.Millisecond + p.ServerSelectionTimeoutSet = true case "sockettimeoutms": n, err := strconv.Atoi(value) if err != nil || n < 0 { return fmt.Errorf("invalid value for %s: %s", key, value) } p.SocketTimeout = time.Duration(n) * time.Millisecond + p.SocketTimeoutSet = true case "ssl": switch value { case "true": @@ -681,6 +659,7 @@ func (p *parser) addOption(pair string) error { level = wiremessage.DefaultZlibLevel } p.ZlibLevel = level + p.ZlibLevelSet = true default: if p.UnknownOptions == nil { p.UnknownOptions = make(map[string][]string) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/description.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/description.go similarity index 80% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/description.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/description.go index 758b112..f2ac523 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/description/description.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/description/description.go @@ -4,7 +4,7 @@ // not use this file except in compliance with the License. You may obtain // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 -package description +package description // import "go.mongodb.org/mongo-driver/x/network/description" // Unknown is an unknown server or topology kind. const Unknown = 0 diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/feature.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/feature.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/feature.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/feature.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/server.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/server.go similarity index 93% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/server.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/server.go index 37490db..102e476 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/description/server.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/description/server.go @@ -10,10 +10,10 @@ import ( "fmt" "time" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/core/address" - "github.com/mongodb/mongo-go-driver/core/result" - "github.com/mongodb/mongo-go-driver/core/tag" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/tag" + "go.mongodb.org/mongo-driver/x/network/address" + "go.mongodb.org/mongo-driver/x/network/result" ) // UnsetRTT is the unset value for a round trip time. @@ -34,7 +34,7 @@ type Server struct { AverageRTTSet bool Compression []string // compression methods returned by server CanonicalAddr address.Address - ElectionID objectid.ObjectID + ElectionID primitive.ObjectID HeartbeatInterval time.Duration LastError error LastUpdateTime time.Time diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/server_kind.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/server_kind.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/server_kind.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/server_kind.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/server_selector.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/server_selector.go similarity index 98% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/server_selector.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/server_selector.go index c081164..d53bee0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/description/server_selector.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/description/server_selector.go @@ -11,8 +11,8 @@ import ( "math" "time" - "github.com/mongodb/mongo-go-driver/core/tag" - "github.com/mongodb/mongo-go-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/mongo/readpref" + "go.mongodb.org/mongo-driver/tag" ) // ServerSelector is an interface implemented by types that can select a server given a diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/topology.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/topology.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/topology.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/topology.go index 33a5743..25f30d0 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/description/topology.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/description/topology.go @@ -10,7 +10,7 @@ import ( "sort" "strings" - "github.com/mongodb/mongo-go-driver/core/address" + "go.mongodb.org/mongo-driver/x/network/address" ) // Topology represents a description of a mongodb topology diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/topology_kind.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/topology_kind.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/topology_kind.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/topology_kind.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/version.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/version.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/version.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/version.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/description/version_range.go b/vendor/go.mongodb.org/mongo-driver/x/network/description/version_range.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/description/version_range.go rename to vendor/go.mongodb.org/mongo-driver/x/network/description/version_range.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/result/result.go b/vendor/go.mongodb.org/mongo-driver/x/network/result/result.go similarity index 63% rename from vendor/github.com/mongodb/mongo-go-driver/core/result/result.go rename to vendor/go.mongodb.org/mongo-driver/x/network/result/result.go index d9b7b37..0c85619 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/result/result.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/result/result.go @@ -5,14 +5,14 @@ // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Package result contains the results from various operations. -package result +package result // import "go.mongodb.org/mongo-driver/x/network/result" import ( "time" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/bson/objectid" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/x/bsonx" ) // Upsert contains the information for a single upsert. @@ -64,6 +64,7 @@ type FindAndModify struct { UpdatedExisting bool Upserted interface{} } + WriteConcernError *WriteConcernError `bson:"writeConcernError"` } // WriteError is an error from a write operation that is not a write concern @@ -81,6 +82,8 @@ type WriteConcernError struct { ErrInfo bson.Raw } +func (wce WriteConcernError) Error() string { return wce.ErrMsg } + // ListDatabases is the result from a listDatabases command. type ListDatabases struct { Databases []struct { @@ -93,32 +96,32 @@ type ListDatabases struct { // IsMaster is a result of an IsMaster command. type IsMaster struct { - Arbiters []string `bson:"arbiters,omitempty"` - ArbiterOnly bool `bson:"arbiterOnly,omitempty"` - ClusterTime bsonx.Doc `bson:"$clusterTime,omitempty"` - Compression []string `bson:"compression,omitempty"` - ElectionID objectid.ObjectID `bson:"electionId,omitempty"` - Hidden bool `bson:"hidden,omitempty"` - Hosts []string `bson:"hosts,omitempty"` - IsMaster bool `bson:"ismaster,omitempty"` - IsReplicaSet bool `bson:"isreplicaset,omitempty"` - LastWriteTimestamp time.Time `bson:"lastWriteDate,omitempty"` - LogicalSessionTimeoutMinutes uint32 `bson:"logicalSessionTimeoutMinutes,omitempty"` - MaxBSONObjectSize uint32 `bson:"maxBsonObjectSize,omitempty"` - MaxMessageSizeBytes uint32 `bson:"maxMessageSizeBytes,omitempty"` - MaxWriteBatchSize uint32 `bson:"maxWriteBatchSize,omitempty"` - Me string `bson:"me,omitempty"` - MaxWireVersion int32 `bson:"maxWireVersion,omitempty"` - MinWireVersion int32 `bson:"minWireVersion,omitempty"` - Msg string `bson:"msg,omitempty"` - OK int32 `bson:"ok"` - Passives []string `bson:"passives,omitempty"` - ReadOnly bool `bson:"readOnly,omitempty"` - SaslSupportedMechs []string `bson:"saslSupportedMechs,omitempty"` - Secondary bool `bson:"secondary,omitempty"` - SetName string `bson:"setName,omitempty"` - SetVersion uint32 `bson:"setVersion,omitempty"` - Tags map[string]string `bson:"tags,omitempty"` + Arbiters []string `bson:"arbiters,omitempty"` + ArbiterOnly bool `bson:"arbiterOnly,omitempty"` + ClusterTime bson.Raw `bson:"$clusterTime,omitempty"` + Compression []string `bson:"compression,omitempty"` + ElectionID primitive.ObjectID `bson:"electionId,omitempty"` + Hidden bool `bson:"hidden,omitempty"` + Hosts []string `bson:"hosts,omitempty"` + IsMaster bool `bson:"ismaster,omitempty"` + IsReplicaSet bool `bson:"isreplicaset,omitempty"` + LastWriteTimestamp time.Time `bson:"lastWriteDate,omitempty"` + LogicalSessionTimeoutMinutes uint32 `bson:"logicalSessionTimeoutMinutes,omitempty"` + MaxBSONObjectSize uint32 `bson:"maxBsonObjectSize,omitempty"` + MaxMessageSizeBytes uint32 `bson:"maxMessageSizeBytes,omitempty"` + MaxWriteBatchSize uint32 `bson:"maxWriteBatchSize,omitempty"` + Me string `bson:"me,omitempty"` + MaxWireVersion int32 `bson:"maxWireVersion,omitempty"` + MinWireVersion int32 `bson:"minWireVersion,omitempty"` + Msg string `bson:"msg,omitempty"` + OK int32 `bson:"ok"` + Passives []string `bson:"passives,omitempty"` + ReadOnly bool `bson:"readOnly,omitempty"` + SaslSupportedMechs []string `bson:"saslSupportedMechs,omitempty"` + Secondary bool `bson:"secondary,omitempty"` + SetName string `bson:"setName,omitempty"` + SetVersion uint32 `bson:"setVersion,omitempty"` + Tags map[string]string `bson:"tags,omitempty"` } // BuildInfo is a result of a BuildInfo command. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/appenders.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/appenders.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/appenders.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/appenders.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/command.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/command.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/command.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/command.go index 8c339a5..3221c17 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/command.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/command.go @@ -6,7 +6,7 @@ package wiremessage -import "github.com/mongodb/mongo-go-driver/bson" +import "go.mongodb.org/mongo-driver/bson" // Command represents the OP_COMMAND message of the MongoDB wire protocol. type Command struct { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/command_reply.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/command_reply.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/command_reply.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/command_reply.go index d5773d6..3b50019 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/command_reply.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/command_reply.go @@ -6,7 +6,7 @@ package wiremessage -import "github.com/mongodb/mongo-go-driver/bson" +import "go.mongodb.org/mongo-driver/bson" // CommandReply represents the OP_COMMANDREPLY message of the MongoDB wire protocol. type CommandReply struct { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/compressed.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/compressed.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/compressed.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/compressed.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/delete.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/delete.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/delete.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/delete.go index 0a502da..f128d03 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/delete.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/delete.go @@ -6,7 +6,7 @@ package wiremessage -import "github.com/mongodb/mongo-go-driver/bson" +import "go.mongodb.org/mongo-driver/bson" // Delete represents the OP_DELETE message of the MongoDB wire protocol. type Delete struct { diff --git a/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/get_more.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/get_more.go new file mode 100644 index 0000000..55d7b4d --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/get_more.go @@ -0,0 +1,103 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package wiremessage + +import ( + "errors" + "fmt" + "go.mongodb.org/mongo-driver/x/bsonx" + "strings" +) + +// GetMore represents the OP_GET_MORE message of the MongoDB wire protocol. +type GetMore struct { + MsgHeader Header + Zero int32 + FullCollectionName string + NumberToReturn int32 + CursorID int64 +} + +// MarshalWireMessage implements the Marshaler and WireMessage interfaces. +func (gm GetMore) MarshalWireMessage() ([]byte, error) { + b := make([]byte, 0, gm.Len()) + return gm.AppendWireMessage(b) +} + +// ValidateWireMessage implements the Validator and WireMessage interfaces. +func (gm GetMore) ValidateWireMessage() error { + if int(gm.MsgHeader.MessageLength) != gm.Len() { + return errors.New("incorrect header: message length is not correct") + } + if gm.MsgHeader.OpCode != OpGetMore { + return errors.New("incorrect header: op code is not OpGetMore") + } + if strings.Index(gm.FullCollectionName, ".") == -1 { + return errors.New("incorrect header: collection name does not contain a dot") + } + + return nil +} + +// AppendWireMessage implements the Appender and WireMessage interfaces. +// +// AppendWireMessage will set the MessageLength property of the MsgHeader +// if it is zero. It will also set the OpCode to OpGetMore if the OpCode is +// zero. If either of these properties are non-zero and not correct, this +// method will return both the []byte with the wire message appended to it +// and an invalid header error. +func (gm GetMore) AppendWireMessage(b []byte) ([]byte, error) { + var err error + err = gm.MsgHeader.SetDefaults(gm.Len(), OpGetMore) + + b = gm.MsgHeader.AppendHeader(b) + b = appendInt32(b, gm.Zero) + b = appendCString(b, gm.FullCollectionName) + b = appendInt32(b, gm.NumberToReturn) + b = appendInt64(b, gm.CursorID) + return b, err +} + +// String implements the fmt.Stringer interface. +func (gm GetMore) String() string { + return fmt.Sprintf( + `OP_GET_MORE{MsgHeader: %s, Zero: %d, FullCollectionName: %s, NumberToReturn: %d, CursorID: %d}`, + gm.MsgHeader, gm.Zero, gm.FullCollectionName, gm.NumberToReturn, gm.CursorID, + ) +} + +// Len implements the WireMessage interface. +func (gm GetMore) Len() int { + // Header + Zero + CollectionName + Null Terminator + Return + CursorID + return 16 + 4 + len(gm.FullCollectionName) + 1 + 4 + 8 +} + +// UnmarshalWireMessage implements the Unmarshaler interface. +func (gm *GetMore) UnmarshalWireMessage([]byte) error { + panic("not implemented") +} + +// CommandDocument creates a BSON document representing this command. +func (gm GetMore) CommandDocument() bsonx.Doc { + parts := strings.Split(gm.FullCollectionName, ".") + collName := parts[len(parts)-1] + + doc := bsonx.Doc{ + {"getMore", bsonx.Int64(gm.CursorID)}, + {"collection", bsonx.String(collName)}, + } + if gm.NumberToReturn != 0 { + doc = doc.Append("batchSize", bsonx.Int32(gm.NumberToReturn)) + } + + return doc +} + +// DatabaseName returns the name of the database for this command. +func (gm GetMore) DatabaseName() string { + return strings.Split(gm.FullCollectionName, ".")[0] +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/header.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/header.go similarity index 100% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/header.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/header.go diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/insert.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/insert.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/insert.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/insert.go index 498228d..e8c02fc 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/insert.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/insert.go @@ -6,7 +6,7 @@ package wiremessage -import "github.com/mongodb/mongo-go-driver/bson" +import "go.mongodb.org/mongo-driver/bson" // Insert represents the OP_INSERT message of the MongoDB wire protocol. type Insert struct { diff --git a/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/kill_cursors.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/kill_cursors.go new file mode 100644 index 0000000..d0b8cfc --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/kill_cursors.go @@ -0,0 +1,92 @@ +// Copyright (C) MongoDB, Inc. 2017-present. +// +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 + +package wiremessage + +import ( + "errors" + "fmt" + "go.mongodb.org/mongo-driver/x/bsonx" +) + +// KillCursors represents the OP_KILL_CURSORS message of the MongoDB wire protocol. +type KillCursors struct { + MsgHeader Header + Zero int32 + NumberOfCursorIDs int32 + CursorIDs []int64 + + DatabaseName string + CollectionName string +} + +// MarshalWireMessage implements the Marshaler and WireMessage interfaces. +func (kc KillCursors) MarshalWireMessage() ([]byte, error) { + b := make([]byte, 0, kc.Len()) + return kc.AppendWireMessage(b) +} + +// ValidateWireMessage implements the Validator and WireMessage interfaces. +func (kc KillCursors) ValidateWireMessage() error { + if int(kc.MsgHeader.MessageLength) != kc.Len() { + return errors.New("incorrect header: message length is not correct") + } + if kc.MsgHeader.OpCode != OpKillCursors { + return errors.New("incorrect header: op code is not OpGetMore") + } + if kc.NumberOfCursorIDs != int32(len(kc.CursorIDs)) { + return errors.New("incorrect number of cursor IDs") + } + + return nil +} + +// AppendWireMessage implements the Appender and WireMessage interfaces. +func (kc KillCursors) AppendWireMessage(b []byte) ([]byte, error) { + var err error + err = kc.MsgHeader.SetDefaults(kc.Len(), OpKillCursors) + + b = kc.MsgHeader.AppendHeader(b) + b = appendInt32(b, kc.Zero) + b = appendInt32(b, kc.NumberOfCursorIDs) + for _, id := range kc.CursorIDs { + b = appendInt64(b, id) + } + + return b, err +} + +// String implements the fmt.Stringer interface. +func (kc KillCursors) String() string { + return fmt.Sprintf( + `OP_KILL_CURSORS{MsgHeader: %s, Zero: %d, Number of Cursor IDS: %d, Cursor IDs: %v}`, + kc.MsgHeader, kc.Zero, kc.NumberOfCursorIDs, kc.CursorIDs, + ) +} + +// Len implements the WireMessage interface. +func (kc KillCursors) Len() int { + // Header + Zero + Number IDs + 8 * Number IDs + return 16 + 4 + 4 + int(kc.NumberOfCursorIDs*8) +} + +// UnmarshalWireMessage implements the Unmarshaler interface. +func (kc *KillCursors) UnmarshalWireMessage([]byte) error { + panic("not implemented") +} + +// CommandDocument creates a BSON document representing this command. +func (kc KillCursors) CommandDocument() bsonx.Doc { + cursors := make([]bsonx.Val, len(kc.CursorIDs)) + for i, id := range kc.CursorIDs { + cursors[i] = bsonx.Int64(id) + } + + return bsonx.Doc{ + {"killCursors", bsonx.String(kc.CollectionName)}, + {"cursors", bsonx.Array(cursors)}, + } +} diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/msg.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/msg.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/msg.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/msg.go index 07f35ab..ea379f6 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/msg.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/msg.go @@ -8,9 +8,10 @@ package wiremessage import ( "errors" + "fmt" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" ) // Msg represents the OP_MSG message of the MongoDB wire protocol. @@ -63,7 +64,10 @@ func (m Msg) AppendWireMessage(b []byte) ([]byte, error) { // String implements the fmt.Stringer interface. func (m Msg) String() string { - panic("not implemented") + return fmt.Sprintf( + `OP_MSG{MsgHeader: %v, FlagBits: %d, Sections: %v, Checksum: %d}`, + m.MsgHeader, m.FlagBits, m.Sections, m.Checksum, + ) } // Len implements the WireMessage interface. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/query.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/query.go similarity index 60% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/query.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/query.go index 713e28e..63b4fdb 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/query.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/query.go @@ -11,8 +11,9 @@ import ( "fmt" "strings" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/mongo/writeconcern" + "go.mongodb.org/mongo-driver/x/bsonx" ) // Query represents the OP_QUERY message of the MongoDB wire protocol. @@ -24,6 +25,23 @@ type Query struct { NumberToReturn int32 Query bson.Raw ReturnFieldsSelector bson.Raw + + SkipSet bool + Limit *int32 + BatchSize *int32 +} + +var optionsMap = map[string]string{ + "$orderby": "sort", + "$hint": "hint", + "$comment": "comment", + "$maxScan": "maxScan", + "$max": "max", + "$min": "min", + "$returnKey": "returnKey", + "$showDiskLoc": "showRecordId", + "$maxTimeMS": "maxTimeMS", + "$snapshot": "snapshot", } // MarshalWireMessage implements the Marshaler and WireMessage interfaces. @@ -147,7 +165,129 @@ func (q *Query) AcknowledgedWrite() bool { return true } - return writeconcern.AcknowledgedElementRaw(wcElem) + return writeconcern.AcknowledgedValue(wcElem) +} + +// Legacy returns true if the query represents a legacy find operation. +func (q Query) Legacy() bool { + return !strings.Contains(q.FullCollectionName, "$cmd") +} + +// DatabaseName returns the database name for the query. +func (q Query) DatabaseName() string { + if q.Legacy() { + return strings.Split(q.FullCollectionName, ".")[0] + } + + return q.FullCollectionName[:len(q.FullCollectionName)-5] // remove .$cmd +} + +// CollectionName returns the collection name for the query. +func (q Query) CollectionName() string { + parts := strings.Split(q.FullCollectionName, ".") + return parts[len(parts)-1] +} + +// CommandDocument creates a BSON document representing this command. +func (q Query) CommandDocument() (bsonx.Doc, error) { + if q.Legacy() { + return q.legacyCommandDocument() + } + + cmd, err := bsonx.ReadDoc([]byte(q.Query)) + if err != nil { + return nil, err + } + + cmdElem := cmd[0] + if cmdElem.Key == "$query" { + cmd = cmdElem.Value.Document() + } + + return cmd, nil +} + +func (q Query) legacyCommandDocument() (bsonx.Doc, error) { + doc, err := bsonx.ReadDoc(q.Query) + if err != nil { + return nil, err + } + + parts := strings.Split(q.FullCollectionName, ".") + collName := parts[len(parts)-1] + doc = append(bsonx.Doc{{"find", bsonx.String(collName)}}, doc...) + + var filter bsonx.Doc + var queryIndex int + for i, elem := range doc { + if newKey, ok := optionsMap[elem.Key]; ok { + doc[i].Key = newKey + continue + } + + if elem.Key == "$query" { + filter = elem.Value.Document() + } else { + // the element is the filter + filter = filter.Append(elem.Key, elem.Value) + } + + queryIndex = i + } + + doc = append(doc[:queryIndex], doc[queryIndex+1:]...) // remove $query + if len(filter) != 0 { + doc = doc.Append("filter", bsonx.Document(filter)) + } + + doc, err = q.convertLegacyParams(doc) + if err != nil { + return nil, err + } + + return doc, nil +} + +func (q Query) convertLegacyParams(doc bsonx.Doc) (bsonx.Doc, error) { + if q.ReturnFieldsSelector != nil { + projDoc, err := bsonx.ReadDoc(q.ReturnFieldsSelector) + if err != nil { + return nil, err + } + doc = doc.Append("projection", bsonx.Document(projDoc)) + } + if q.Limit != nil { + limit := *q.Limit + if limit < 0 { + limit *= -1 + doc = doc.Append("singleBatch", bsonx.Boolean(true)) + } + + doc = doc.Append("limit", bsonx.Int32(*q.Limit)) + } + if q.BatchSize != nil { + doc = doc.Append("batchSize", bsonx.Int32(*q.BatchSize)) + } + if q.SkipSet { + doc = doc.Append("skip", bsonx.Int32(q.NumberToSkip)) + } + if q.Flags&TailableCursor > 0 { + doc = doc.Append("tailable", bsonx.Boolean(true)) + } + if q.Flags&OplogReplay > 0 { + doc = doc.Append("oplogReplay", bsonx.Boolean(true)) + } + if q.Flags&NoCursorTimeout > 0 { + doc = doc.Append("noCursorTimeout", bsonx.Boolean(true)) + } + if q.Flags&AwaitData > 0 { + doc = doc.Append("awaitData", bsonx.Boolean(true)) + } + if q.Flags&Partial > 0 { + doc = doc.Append("allowPartialResults", bsonx.Boolean(true)) + } + + return doc, nil } // QueryFlag represents the flags on an OP_QUERY message. diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/readers.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/readers.go similarity index 97% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/readers.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/readers.go index bbf394d..80af38e 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/readers.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/readers.go @@ -10,7 +10,7 @@ import ( "bytes" "errors" - "github.com/mongodb/mongo-go-driver/bson" + "go.mongodb.org/mongo-driver/bson" ) func readInt32(b []byte, pos int32) int32 { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/reply.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/reply.go similarity index 78% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/reply.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/reply.go index 11b86df..3ab833a 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/reply.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/reply.go @@ -11,8 +11,8 @@ import ( "fmt" "strings" - "github.com/mongodb/mongo-go-driver/bson" - "github.com/mongodb/mongo-go-driver/x/bsonx" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/x/bsonx" ) // Reply represents the OP_REPLY message of the MongoDB wire protocol. @@ -117,6 +117,52 @@ func (r *Reply) UnmarshalWireMessage(b []byte) error { return nil } +// GetMainLegacyDocument constructs and returns a BSON document for this reply. +func (r *Reply) GetMainLegacyDocument(fullCollectionName string) (bsonx.Doc, error) { + if r.ResponseFlags&CursorNotFound > 0 { + fmt.Println("cursor not found err") + return bsonx.Doc{ + {"ok", bsonx.Int32(0)}, + }, nil + } + if r.ResponseFlags&QueryFailure > 0 { + firstDoc := r.Documents[0] + return bsonx.Doc{ + {"ok", bsonx.Int32(0)}, + {"errmsg", bsonx.String(firstDoc.Lookup("$err").StringValue())}, + {"code", bsonx.Int32(firstDoc.Lookup("code").Int32())}, + }, nil + } + + doc := bsonx.Doc{ + {"ok", bsonx.Int32(1)}, + } + + batchStr := "firstBatch" + if r.StartingFrom != 0 { + batchStr = "nextBatch" + } + + batchArr := make([]bsonx.Val, len(r.Documents)) + for i, docRaw := range r.Documents { + doc, err := bsonx.ReadDoc(docRaw) + if err != nil { + return nil, err + } + + batchArr[i] = bsonx.Document(doc) + } + + cursorDoc := bsonx.Doc{ + {"id", bsonx.Int64(r.CursorID)}, + {"ns", bsonx.String(fullCollectionName)}, + {batchStr, bsonx.Array(batchArr)}, + } + + doc = doc.Append("cursor", bsonx.Document(cursorDoc)) + return doc, nil +} + // GetMainDocument returns the main BSON document for this reply. func (r *Reply) GetMainDocument() (bsonx.Doc, error) { return bsonx.ReadDoc([]byte(r.Documents[0])) diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/update.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/update.go similarity index 96% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/update.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/update.go index a987327..0a0cfa1 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/update.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/update.go @@ -6,7 +6,7 @@ package wiremessage -import "github.com/mongodb/mongo-go-driver/bson" +import "go.mongodb.org/mongo-driver/bson" // Update represents the OP_UPDATE message of the MongoDB wire protocol. type Update struct { diff --git a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/wiremessage.go b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/wiremessage.go similarity index 98% rename from vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/wiremessage.go rename to vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/wiremessage.go index c2cb153..44bf507 100644 --- a/vendor/github.com/mongodb/mongo-go-driver/core/wiremessage/wiremessage.go +++ b/vendor/go.mongodb.org/mongo-driver/x/network/wiremessage/wiremessage.go @@ -10,7 +10,7 @@ // corresponding implementations. One prefixed with Immutable which can be created by casting a // []byte to the type, and another prefixed with Mutable that is a struct with methods to mutate // the op. -package wiremessage +package wiremessage // import "go.mongodb.org/mongo-driver/x/network/wiremessage" import ( "context"