From bb92a1dbf85e357f124ed3e4955f03a4e898df75 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:26:45 -0500 Subject: [PATCH 01/21] downgrade --- go.mod | 2 +- go.sum | 2 + .../{decimal128.go => decinal128.go} | 0 .../v2/internal/driverutil/description.go | 2 +- .../mongo-driver/v2/mongo/bulk_write.go | 7 - .../mongo-driver/v2/mongo/client.go | 135 ++++++------------ .../v2/mongo/client_bulk_write.go | 8 -- .../mongo-driver/v2/mongo/collection.go | 96 +++++++------ .../mongo-driver/v2/mongo/database.go | 6 +- .../mongo-driver/v2/mongo/index_view.go | 18 ++- .../mongo-driver/v2/mongo/mongointernal.go | 41 ------ .../v2/mongo/options/changestreamoptions.go | 2 +- .../mongo/options/listcollectionsoptions.go | 3 +- .../mongo-driver/v2/version/version.go | 2 +- .../v2/x/mongo/driver/operation.go | 14 +- .../mongo/driver/operation/find_and_modify.go | 18 --- .../v2/x/mongo/driver/operation/insert.go | 19 --- .../v2/x/mongo/driver/operation/update.go | 18 --- .../v2/x/mongo/driver/topology/fsm.go | 2 +- .../v2/x/mongo/driver/topology/server.go | 16 +-- .../x/mongo/driver/topology/server_options.go | 33 +++-- .../mongo/driver/topology/topology_options.go | 127 ++++++---------- vendor/modules.txt | 2 +- 23 files changed, 196 insertions(+), 377 deletions(-) rename vendor/go.mongodb.org/mongo-driver/v2/internal/decimal128/{decimal128.go => decinal128.go} (100%) delete mode 100644 vendor/go.mongodb.org/mongo-driver/v2/mongo/mongointernal.go diff --git a/go.mod b/go.mod index 7c452914..90bb96e9 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,7 @@ require ( github.com/samber/mo v1.13.0 github.com/stretchr/testify v1.10.0 github.com/urfave/cli v1.22.9 - go.mongodb.org/mongo-driver/v2 v2.4.0 + go.mongodb.org/mongo-driver/v2 v2.3.1 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 golang.org/x/sync v0.13.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 diff --git a/go.sum b/go.sum index 698a8a02..9456b762 100644 --- a/go.sum +++ b/go.sum @@ -129,6 +129,8 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver/v2 v2.3.1 h1:WrCgSzO7dh1/FrePud9dK5fKNZOE97q5EQimGkos7Wo= +go.mongodb.org/mongo-driver/v2 v2.3.1/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI= go.mongodb.org/mongo-driver/v2 v2.4.0 h1:Oq6BmUAAFTzMeh6AonuDlgZMuAuEiUxoAD1koK5MuFo= go.mongodb.org/mongo-driver/v2 v2.4.0/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI= golang.org/x/arch v0.16.0 h1:foMtLTdyOmIniqWCHjY6+JxuC54XP1fDwx4N0ASyW+U= diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/decimal128/decimal128.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/decimal128/decinal128.go similarity index 100% rename from vendor/go.mongodb.org/mongo-driver/v2/internal/decimal128/decimal128.go rename to vendor/go.mongodb.org/mongo-driver/v2/internal/decimal128/decinal128.go diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go index 926de0bd..89963799 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go @@ -21,7 +21,7 @@ import ( ) const ( - MinWireVersion = 8 + MinWireVersion = 7 MaxWireVersion = 25 ) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go index ca683c1d..036e3bad 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go @@ -40,7 +40,6 @@ type bulkWrite struct { result BulkWriteResult let any rawData *bool - additionalCmd bson.D } func (bw *bulkWrite) execute(ctx context.Context) error { @@ -214,9 +213,6 @@ func (bw *bulkWrite) runInsert(ctx context.Context, batch bulkWriteBatch) (opera if bw.rawData != nil { op.RawData(*bw.rawData) } - if len(bw.additionalCmd) > 0 { - op.AdditionalCmd(bw.additionalCmd) - } err := op.Execute(ctx) @@ -431,9 +427,6 @@ func (bw *bulkWrite) runUpdate(ctx context.Context, batch bulkWriteBatch) (opera if bw.rawData != nil { op.RawData(*bw.rawData) } - if len(bw.additionalCmd) > 0 { - op.AdditionalCmd(bw.additionalCmd) - } err := op.Execute(ctx) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go index 10182276..cb2e5494 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go @@ -11,8 +11,6 @@ import ( "errors" "fmt" "net/http" - "sync" - "sync/atomic" "time" "go.mongodb.org/mongo-driver/v2/bson" @@ -58,26 +56,24 @@ var ( // The Client type opens and closes connections automatically and maintains a pool of idle connections. For // connection pool configuration options, see documentation for the ClientOptions type in the mongo/options package. type Client struct { - id uuid.UUID - deployment driver.Deployment - localThreshold time.Duration - retryWrites bool - retryReads bool - clock *session.ClusterClock - readPreference *readpref.ReadPref - readConcern *readconcern.ReadConcern - writeConcern *writeconcern.WriteConcern - bsonOpts *options.BSONOptions - registry *bson.Registry - monitor *event.CommandMonitor - serverAPI *driver.ServerAPIOptions - serverMonitor *event.ServerMonitor - sessionPool *session.Pool - timeout *time.Duration - httpClient *http.Client - logger *logger.Logger - currentDriverInfo *atomic.Pointer[options.DriverInfo] - seenDriverInfo sync.Map + id uuid.UUID + deployment driver.Deployment + localThreshold time.Duration + retryWrites bool + retryReads bool + clock *session.ClusterClock + readPreference *readpref.ReadPref + readConcern *readconcern.ReadConcern + writeConcern *writeconcern.WriteConcern + bsonOpts *options.BSONOptions + registry *bson.Registry + monitor *event.CommandMonitor + serverAPI *driver.ServerAPIOptions + serverMonitor *event.ServerMonitor + sessionPool *session.Pool + timeout *time.Duration + httpClient *http.Client + logger *logger.Logger // in-use encryption fields isAutoEncryptionSet bool @@ -91,19 +87,27 @@ type Client struct { authenticator driver.Authenticator } -// Connect creates a new Client with the given configuration options. +// Connect creates a new Client and then initializes it using the Connect method. // -// Connect returns an error if the configuration options are invalid, but does -// not validate that the MongoDB deployment is reachable. To verify that the -// deployment is reachable, call [Client.Ping]. -// -// When creating an [options.ClientOptions], the order the methods are called -// matters. Later option setter calls overwrite the values from previous option -// setter calls, including the ApplyURI method. This allows callers to -// determine the order of precedence for setting options. For instance, if -// ApplyURI is called before SetAuth, the Credential from SetAuth will -// overwrite the values from the connection string. If ApplyURI is called +// 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. +// +// The NewClient function does not do any I/O and returns an error if the given options are invalid. +// The Client.Connect method starts background goroutines to monitor the state of the deployment and does not do +// any I/O in the main goroutine to prevent the main goroutine from blocking. Therefore, it will not error if the +// deployment is down. +// +// The Client.Ping method can be used to verify that the deployment is successfully connected and the +// Client was correctly configured. func Connect(opts ...*options.ClientOptions) (*Client, error) { c, err := newClient(opts...) if err != nil { @@ -136,11 +140,7 @@ func newClient(opts ...*options.ClientOptions) (*Client, error) { if err != nil { return nil, err } - - client := &Client{ - id: id, - currentDriverInfo: &atomic.Pointer[options.DriverInfo]{}, - } + client := &Client{id: id} // ClusterClock client.clock = new(session.ClusterClock) @@ -225,16 +225,7 @@ func newClient(opts ...*options.ClientOptions) (*Client, error) { } } - if clientOpts.DriverInfo != nil { - client.AppendDriverInfo(*clientOpts.DriverInfo) - } - - cfg, err := topology.NewAuthenticatorConfig(client.authenticator, - topology.WithAuthConfigClock(client.clock), - topology.WithAuthConfigClientOptions(clientOpts), - topology.WithAuthConfigDriverInfo(client.currentDriverInfo), - ) - + cfg, err := topology.NewConfigFromOptionsWithAuthenticator(clientOpts, client.clock, client.authenticator) if err != nil { return nil, err } @@ -311,45 +302,6 @@ func (c *Client) connect() error { return nil } -// AppendDriverInfo appends the provided [options.DriverInfo] to the metadata -// (e.g. name, version, platform) that will be sent to the server in handshake -// requests when establishing new connections. -// -// Repeated calls to AppendDriverInfo with equivalent DriverInfo is a no-op. -// -// Metadata is limited to 512 bytes; any excess will be truncated. -func (c *Client) AppendDriverInfo(info options.DriverInfo) { - if _, loaded := c.seenDriverInfo.LoadOrStore(info, struct{}{}); loaded { - return - } - - if old := c.currentDriverInfo.Load(); old != nil { - if old.Name != "" && info.Name != "" && old.Name != info.Name { - info.Name = old.Name + "|" + info.Name - } else if old.Name != "" { - info.Name = old.Name - } - - if old.Version != "" && info.Version != "" && old.Version != info.Version { - info.Version = old.Version + "|" + info.Version - } else if old.Version != "" { - info.Version = old.Version - } - - if old.Platform != "" && info.Platform != "" && old.Platform != info.Platform { - info.Platform = old.Platform + "|" + info.Platform - } else if old.Platform != "" { - info.Platform = old.Platform - } - } - - // Copy-on-write so that the info stored in the client is immutable. - infoCopy := new(options.DriverInfo) - *infoCopy = info - - c.currentDriverInfo.Store(infoCopy) -} - // 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 @@ -1006,11 +958,10 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, selector: selector, writeConcern: wc, } - if rawData, ok := optionsutil.Value(bwo.Internal, "rawData").(bool); ok { - op.rawData = &rawData - } - if additionalCmd, ok := optionsutil.Value(bwo.Internal, "addCommandFields").(bson.D); ok { - op.additionalCmd = additionalCmd + if rawDataOpt := optionsutil.Value(bwo.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op.rawData = &rawData + } } if bwo.VerboseResults == nil || !(*bwo.VerboseResults) { op.errorsOnly = true diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go index cb9d8cb4..27c3ad3c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go @@ -45,7 +45,6 @@ type clientBulkWrite struct { selector description.ServerSelector writeConcern *writeconcern.WriteConcern rawData *bool - additionalCmd bson.D result ClientBulkWriteResult } @@ -149,13 +148,6 @@ func (bw *clientBulkWrite) newCommand() func([]byte, description.SelectedServer) if bw.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { dst = bsoncore.AppendBooleanElement(dst, "rawData", *bw.rawData) } - if len(bw.additionalCmd) > 0 { - doc, err := bson.Marshal(bw.additionalCmd) - if err != nil { - return nil, err - } - dst = append(dst, doc[4:len(doc)-1]...) - } return dst, nil } } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go index af1960d9..ef4188d6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go @@ -246,11 +246,10 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, writeConcern: wc, let: args.Let, } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op.rawData = &rawData - } - if additionalCmd, ok := optionsutil.Value(args.Internal, "addCommandFields").(bson.D); ok { - op.additionalCmd = additionalCmd + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op.rawData = &rawData + } } err = op.execute(ctx) @@ -331,11 +330,10 @@ func (coll *Collection) insert( if args.Ordered != nil { op = op.Ordered(*args.Ordered) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) - } - if additionalCmd, ok := optionsutil.Value(args.Internal, "addCommandFields").(bson.D); ok { - op = op.AdditionalCmd(additionalCmd) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone if coll.client.retryWrites { @@ -390,14 +388,7 @@ func (coll *Collection) InsertOne(ctx context.Context, document any, } if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { imOpts.Opts = append(imOpts.Opts, func(opts *options.InsertManyOptions) error { - opts.Internal = optionsutil.WithValue(opts.Internal, "rawData", rawDataOpt) - - return nil - }) - } - if additionalCmd := optionsutil.Value(args.Internal, "addCommandFields"); additionalCmd != nil { - imOpts.Opts = append(imOpts.Opts, func(opts *options.InsertManyOptions) error { - opts.Internal = optionsutil.WithValue(opts.Internal, "addCommandFields", additionalCmd) + optionsutil.WithValue(opts.Internal, "rawData", rawDataOpt) return nil }) @@ -561,8 +552,10 @@ func (coll *Collection) delete( } op = op.Let(let) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } // deleteMany cannot be retried @@ -712,11 +705,10 @@ func (coll *Collection) updateOrReplace( } op = op.Comment(comment) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) - } - if additionalCmd, ok := optionsutil.Value(args.Internal, "addCommandFields").(bson.D); ok { - op = op.AdditionalCmd(additionalCmd) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone // retryable writes are only enabled updateOne/replaceOne operations @@ -1075,8 +1067,10 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption } op.CustomOptions(customOptions) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone @@ -1172,8 +1166,10 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter any, } op.Hint(hintVal) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone if coll.client.retryReads { @@ -1256,8 +1252,10 @@ func (coll *Collection) EstimatedDocumentCount( } op = op.Comment(comment) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone @@ -1348,8 +1346,10 @@ func (coll *Collection) Distinct( } op.Hint(hint) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone if coll.client.retryReads { @@ -1554,8 +1554,10 @@ func (coll *Collection) find( } op.Sort(sort) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone if coll.client.retryReads { @@ -1755,8 +1757,10 @@ func (coll *Collection) FindOneAndDelete( } op = op.Let(let) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } return coll.findAndModify(ctx, op) @@ -1855,11 +1859,10 @@ func (coll *Collection) FindOneAndReplace( } op = op.Let(let) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) - } - if additionalCmd, ok := optionsutil.Value(args.Internal, "addCommandFields").(bson.D); ok { - op = op.AdditionalCmd(additionalCmd) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } return coll.findAndModify(ctx, op) @@ -1970,11 +1973,10 @@ func (coll *Collection) FindOneAndUpdate( } op = op.Let(let) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) - } - if additionalCmd, ok := optionsutil.Value(args.Internal, "addCommandFields").(bson.D); ok { - op = op.AdditionalCmd(additionalCmd) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } return coll.findAndModify(ctx, op) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go index 7064929e..e42097bb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go @@ -489,8 +489,10 @@ func (db *Database) ListCollections( if args.AuthorizedCollections != nil { op = op.AuthorizedCollections(*args.AuthorizedCollections) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go index 147978d2..f8529c16 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go @@ -102,8 +102,10 @@ func (iv IndexView) List(ctx context.Context, opts ...options.Lister[options.Lis op = op.BatchSize(*args.BatchSize) cursorOpts.BatchSize = *args.BatchSize } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } retry := driver.RetryNone @@ -288,8 +290,10 @@ func (iv IndexView) CreateMany( op.CommitQuorum(commitQuorum) } - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } _, err = processWriteError(op.Execute(ctx)) @@ -425,8 +429,10 @@ func (iv IndexView) drop(ctx context.Context, index any, opts ...options.Lister[ Deployment(iv.coll.client.deployment).ServerAPI(iv.coll.client.serverAPI). Timeout(iv.coll.client.timeout).Crypt(iv.coll.client.cryptFLE).Authenticator(iv.coll.client.authenticator) - if rawData, ok := optionsutil.Value(args.Internal, "rawData").(bool); ok { - op = op.RawData(rawData) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } } err = op.Execute(ctx) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongointernal.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongointernal.go deleted file mode 100644 index 31195d37..00000000 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongointernal.go +++ /dev/null @@ -1,41 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2025-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 - -//go:build mongointernal - -package mongo - -import ( - "time" - - "go.mongodb.org/mongo-driver/v2/bson" - "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" - "go.mongodb.org/mongo-driver/v2/x/mongo/driver/session" -) - -// NewSessionWithLSID returns a Session with the given sessionID document. The -// sessionID is a BSON document with key "id" containing a 16-byte UUID (binary -// subtype 4). -// -// Sessions returned by NewSessionWithLSID are never added to the driver's -// session pool. Calling "EndSession" or "ClientSession.SetServer" on a Session -// returned by NewSessionWithLSID will panic. -// -// NewSessionWithLSID is intended only for internal use and may be changed or -// removed at any time. -func NewSessionWithLSID(client *Client, sessionID bson.Raw) *Session { - return &Session{ - clientSession: &session.Client{ - Server: &session.Server{ - SessionID: bsoncore.Document(sessionID), - LastUsed: time.Now(), - }, - ClientID: client.id, - }, - client: client, - deployment: client.deployment, - } -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go index 92f19638..9e5bb93b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go @@ -135,7 +135,7 @@ func (cso *ChangeStreamOptionsBuilder) SetShowExpandedEvents(see bool) *ChangeSt } // SetStartAtOperationTime sets the value for the StartAtOperationTime field. If specified, the change stream -// will only return changes that occurred at or after the given timestamp. +// will only return changes that occurred at or after the given timestamp. This MongoDB versions >= 4.0. // If this is specified, ResumeAfter and StartAfter must not be set. func (cso *ChangeStreamOptionsBuilder) SetStartAtOperationTime(t *bson.Timestamp) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go index c69a6dc4..14f96cc6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go @@ -65,7 +65,8 @@ func (lc *ListCollectionsOptionsBuilder) SetBatchSize(size int32) *ListCollectio // SetAuthorizedCollections sets the value for the AuthorizedCollections field. If true, and // NameOnly is true, limits the documents returned to only contain collections the user is -// authorized to use. The default value is false. +// authorized to use. The default value is false. This option is only valid for MongoDB server +// versions >= 4.0. Server versions < 4.0 ignore this option. func (lc *ListCollectionsOptionsBuilder) SetAuthorizedCollections(b bool) *ListCollectionsOptionsBuilder { lc.Opts = append(lc.Opts, func(opts *ListCollectionsOptions) error { opts.AuthorizedCollections = &b diff --git a/vendor/go.mongodb.org/mongo-driver/v2/version/version.go b/vendor/go.mongodb.org/mongo-driver/v2/version/version.go index ab026bd1..2b483845 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/version/version.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/version/version.go @@ -11,4 +11,4 @@ package version // Driver is the current version of the driver. -var Driver = "2.4.0" +var Driver = "2.3.1" diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go index 3e720eba..57ec762e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go @@ -1133,11 +1133,9 @@ func (op Operation) readWireMessage(ctx context.Context, conn *mnet.Connection) // decode res, err := op.decodeResult(opcode, rem) - // When a cluster clock is given, update cluster/operation time and recovery tokens before handling the error - // to ensure we're properly updating everything. - if op.Clock != nil { - op.updateClusterTimes(res) - } + // Update cluster/operation time and recovery tokens before handling the error to ensure we're properly updating + // everything. + op.updateClusterTimes(res) op.updateOperationTime(res) op.Client.UpdateRecoveryToken(bson.Raw(res)) @@ -1731,10 +1729,7 @@ func (op Operation) addClusterTime(dst []byte, desc description.SelectedServer) if (clock == nil && client == nil) || !sessionsSupported(desc.WireVersion) { return dst } - var clusterTime bson.Raw - if clock != nil { - clusterTime = clock.GetClusterTime() - } + clusterTime := clock.GetClusterTime() if client != nil { clusterTime = session.MaxClusterTime(clusterTime, client.ClusterTime) } @@ -1746,6 +1741,7 @@ func (op Operation) addClusterTime(dst []byte, desc description.SelectedServer) return dst } return append(bsoncore.AppendHeader(dst, bsoncore.Type(val.Type), "$clusterTime"), val.Value...) + // return bsoncore.AppendDocumentElement(dst, "$clusterTime", clusterTime) } // calculateMaxTimeMS calculates the value of the 'maxTimeMS' field to potentially append diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go index 0b3da9c4..09205681 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go @@ -51,7 +51,6 @@ type FindAndModify struct { let bsoncore.Document timeout *time.Duration rawData *bool - additionalCmd bson.D result FindAndModifyResult } @@ -217,13 +216,6 @@ func (fam *FindAndModify) command(dst []byte, desc description.SelectedServer) ( if fam.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { dst = bsoncore.AppendBooleanElement(dst, "rawData", *fam.rawData) } - if len(fam.additionalCmd) > 0 { - doc, err := bson.Marshal(fam.additionalCmd) - if err != nil { - return nil, err - } - dst = append(dst, doc[4:len(doc)-1]...) - } return dst, nil } @@ -499,13 +491,3 @@ func (fam *FindAndModify) RawData(rawData bool) *FindAndModify { fam.rawData = &rawData return fam } - -// AdditionalCmd sets additional command fields to be attached. -func (fam *FindAndModify) AdditionalCmd(d bson.D) *FindAndModify { - if fam == nil { - fam = new(FindAndModify) - } - - fam.additionalCmd = d - return fam -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go index d4f01e6b..57d461ae 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go @@ -12,7 +12,6 @@ import ( "fmt" "time" - "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/driverutil" "go.mongodb.org/mongo-driver/v2/internal/logger" @@ -44,7 +43,6 @@ type Insert struct { serverAPI *driver.ServerAPIOptions timeout *time.Duration rawData *bool - additionalCmd bson.D logger *logger.Logger } @@ -139,13 +137,6 @@ func (i *Insert) command(dst []byte, desc description.SelectedServer) ([]byte, e if i.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { dst = bsoncore.AppendBooleanElement(dst, "rawData", *i.rawData) } - if len(i.additionalCmd) > 0 { - doc, err := bson.Marshal(i.additionalCmd) - if err != nil { - return nil, err - } - dst = append(dst, doc[4:len(doc)-1]...) - } return dst, nil } @@ -342,13 +333,3 @@ func (i *Insert) RawData(rawData bool) *Insert { i.rawData = &rawData return i } - -// AdditionalCmd sets additional command fields to be attached. -func (i *Insert) AdditionalCmd(d bson.D) *Insert { - if i == nil { - i = new(Insert) - } - - i.additionalCmd = d - return i -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go index 07848a54..00e193ef 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go @@ -47,7 +47,6 @@ type Update struct { let bsoncore.Document timeout *time.Duration rawData *bool - additionalCmd bson.D logger *logger.Logger } @@ -209,13 +208,6 @@ func (u *Update) command(dst []byte, desc description.SelectedServer) ([]byte, e if u.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { dst = bsoncore.AppendBooleanElement(dst, "rawData", *u.rawData) } - if len(u.additionalCmd) > 0 { - doc, err := bson.Marshal(u.additionalCmd) - if err != nil { - return nil, err - } - dst = append(dst, doc[4:len(doc)-1]...) - } return dst, nil } @@ -445,13 +437,3 @@ func (u *Update) RawData(rawData bool) *Update { u.rawData = &rawData return u } - -// AdditionalCmd sets additional command fields to be attached. -func (u *Update) AdditionalCmd(d bson.D) *Update { - if u == nil { - u = new(Update) - } - - u.additionalCmd = d - return u -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go index 26e2fc32..530b2169 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go @@ -20,7 +20,7 @@ import ( var ( // MinSupportedMongoDBVersion is the version string for the lowest MongoDB version supported by the driver. - MinSupportedMongoDBVersion = "4.2" + MinSupportedMongoDBVersion = "4.0" // SupportedWireVersions is the range of wire versions supported by the driver. SupportedWireVersions = driverutil.NewVersionRange(driverutil.MinWireVersion, driverutil.MaxWireVersion) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go index a408aee5..90cee89e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go @@ -807,18 +807,9 @@ func (s *Server) createConnection() *connection { opts := copyConnectionOpts(s.cfg.connectionOpts) opts = append(opts, WithHandshaker(func(Handshaker) Handshaker { - handshaker := operation.NewHello().AppName(s.cfg.appname).Compressors(s.cfg.compressionOpts). - ServerAPI(s.cfg.serverAPI) - - if s.cfg.driverInfo != nil { - driverInfo := s.cfg.driverInfo.Load() - if driverInfo != nil { - handshaker = handshaker.OuterLibraryName(driverInfo.Name).OuterLibraryVersion(driverInfo.Version). - OuterLibraryPlatform(driverInfo.Platform) - } - } - - return handshaker + return operation.NewHello().AppName(s.cfg.appname).Compressors(s.cfg.compressionOpts). + ServerAPI(s.cfg.serverAPI).OuterLibraryName(s.cfg.outerLibraryName). + OuterLibraryVersion(s.cfg.outerLibraryVersion).OuterLibraryPlatform(s.cfg.outerLibraryPlatform) }), // Override any monitors specified in options with nil to avoid monitoring heartbeats. WithMonitor(func(*event.CommandMonitor) *event.CommandMonitor { return nil }), @@ -851,6 +842,7 @@ func (s *Server) setupHeartbeatConnection(ctx context.Context) error { func (s *Server) createBaseOperation(conn *mnet.Connection) *operation.Hello { return operation. NewHello(). + ClusterClock(s.cfg.clock). Deployment(driver.SingleConnectionDeployment{C: conn}). ServerAPI(s.cfg.serverAPI) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server_options.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server_options.go index 297cafc7..490834cb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server_options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server_options.go @@ -7,13 +7,11 @@ package topology import ( - "sync/atomic" "time" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/logger" - "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/session" @@ -34,7 +32,6 @@ type serverConfig struct { monitoringDisabled bool serverAPI *driver.ServerAPIOptions loadBalanced bool - driverInfo *atomic.Pointer[options.DriverInfo] // Connection pool options. maxConns uint64 @@ -44,6 +41,11 @@ type serverConfig struct { logger *logger.Logger poolMaxIdleTime time.Duration poolMaintainInterval time.Duration + + // Fields provided by a library that wraps the Go Driver. + outerLibraryName string + outerLibraryVersion string + outerLibraryPlatform string } func newServerConfig(connectTimeout time.Duration, opts ...ServerOption) *serverConfig { @@ -99,12 +101,27 @@ func WithServerAppName(fn func(string) string) ServerOption { } } -// WithDriverInfo sets at atomic pointer to the server configuration, which will -// be used to create the "driver" section on handshake commands. An atomic -// pointer is used so that the driver info can be updated concurrently. -func WithDriverInfo(info *atomic.Pointer[options.DriverInfo]) ServerOption { +// WithOuterLibraryName configures the name for the outer library to include +// in the drivers section of the handshake metadata. +func WithOuterLibraryName(fn func(string) string) ServerOption { + return func(cfg *serverConfig) { + cfg.outerLibraryName = fn(cfg.outerLibraryName) + } +} + +// WithOuterLibraryVersion configures the version for the outer library to +// include in the drivers section of the handshake metadata. +func WithOuterLibraryVersion(fn func(string) string) ServerOption { + return func(cfg *serverConfig) { + cfg.outerLibraryVersion = fn(cfg.outerLibraryVersion) + } +} + +// WithOuterLibraryPlatform configures the platform for the outer library to +// include in the platform section of the handshake metadata. +func WithOuterLibraryPlatform(fn func(string) string) ServerOption { return func(cfg *serverConfig) { - cfg.driverInfo = info + cfg.outerLibraryPlatform = fn(cfg.outerLibraryPlatform) } } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go index 2d53805d..2ddc7434 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go @@ -11,7 +11,6 @@ import ( "crypto/tls" "fmt" "net/http" - "sync/atomic" "time" "go.mongodb.org/mongo-driver/v2/event" @@ -140,56 +139,14 @@ func NewConfig(opts *options.ClientOptions, clock *session.ClusterClock) (*Confi return nil, fmt.Errorf("error creating authenticator: %w", err) } } - return NewAuthenticatorConfig(authenticator, - WithAuthConfigClock(clock), - WithAuthConfigClientOptions(opts), - ) -} - -type authConfigOptions struct { - clock *session.ClusterClock - opts *options.ClientOptions - driverInfo *atomic.Pointer[options.DriverInfo] -} - -// AuthConfigOption is a function that configures authConfigOptions. -type AuthConfigOption func(*authConfigOptions) - -// WithAuthConfigClock sets the cluster clock in authConfigOptions. -func WithAuthConfigClock(clock *session.ClusterClock) AuthConfigOption { - return func(co *authConfigOptions) { - co.clock = clock - } -} - -// WithAuthConfigClientOptions sets the client options in authConfigOptions. -func WithAuthConfigClientOptions(opts *options.ClientOptions) AuthConfigOption { - return func(co *authConfigOptions) { - co.opts = opts - } + return NewConfigFromOptionsWithAuthenticator(opts, clock, authenticator) } -// WithAuthConfigDriverInfo sets the driver info in authConfigOptions. -func WithAuthConfigDriverInfo(driverInfo *atomic.Pointer[options.DriverInfo]) AuthConfigOption { - return func(co *authConfigOptions) { - co.driverInfo = driverInfo - } -} - -// NewAuthenticatorConfig will translate data from client options into a +// NewConfigFromOptionsWithAuthenticator will translate data from client options into a // topology config for building non-default deployments. Server and topology // options are not honored if a custom deployment is used. It uses a passed in // authenticator to authenticate the connection. -func NewAuthenticatorConfig(authenticator driver.Authenticator, clientOpts ...AuthConfigOption) (*Config, error) { - settings := authConfigOptions{} - for _, apply := range clientOpts { - apply(&settings) - } - - opts := settings.opts - clock := settings.clock - driverInfo := settings.driverInfo - +func NewConfigFromOptionsWithAuthenticator(opts *options.ClientOptions, clock *session.ClusterClock, authenticator driver.Authenticator) (*Config, error) { var serverAPI *driver.ServerAPIOptions if err := opts.Validate(); err != nil { @@ -243,8 +200,23 @@ func NewAuthenticatorConfig(authenticator driver.Authenticator, clientOpts ...Au })) } - if driverInfo != nil { - serverOpts = append(serverOpts, WithDriverInfo(driverInfo)) + var outerLibraryName, outerLibraryVersion, outerLibraryPlatform string + if opts.DriverInfo != nil { + outerLibraryName = opts.DriverInfo.Name + outerLibraryVersion = opts.DriverInfo.Version + outerLibraryPlatform = opts.DriverInfo.Platform + + serverOpts = append(serverOpts, WithOuterLibraryName(func(string) string { + return outerLibraryName + })) + + serverOpts = append(serverOpts, WithOuterLibraryVersion(func(string) string { + return outerLibraryVersion + })) + + serverOpts = append(serverOpts, WithOuterLibraryPlatform(func(string) string { + return outerLibraryPlatform + })) } // Compressors & ZlibLevel @@ -284,57 +256,46 @@ func NewAuthenticatorConfig(authenticator driver.Authenticator, clientOpts ...Au // Handshaker var handshaker func(driver.Handshaker) driver.Handshaker if authenticator != nil { - handshaker = func(driver.Handshaker) driver.Handshaker { - handshakeOpts := &auth.HandshakeOptions{ - AppName: appName, - Authenticator: authenticator, - Compressors: comps, - ServerAPI: serverAPI, - LoadBalanced: loadBalanced, - ClusterClock: clock, - } - - if opts.Auth.AuthMechanism == "" { - // Required for SASL mechanism negotiation during handshake - handshakeOpts.DBUser = opts.Auth.AuthSource + "." + opts.Auth.Username - } + handshakeOpts := &auth.HandshakeOptions{ + AppName: appName, + Authenticator: authenticator, + Compressors: comps, + ServerAPI: serverAPI, + LoadBalanced: loadBalanced, + ClusterClock: clock, + OuterLibraryName: outerLibraryName, + OuterLibraryVersion: outerLibraryVersion, + OuterLibraryPlatform: outerLibraryPlatform, + } - if auth, ok := optionsutil.Value(opts.Custom, "authenticateToAnything").(bool); ok && auth { + if opts.Auth.AuthMechanism == "" { + // Required for SASL mechanism negotiation during handshake + handshakeOpts.DBUser = opts.Auth.AuthSource + "." + opts.Auth.Username + } + if a := optionsutil.Value(opts.Custom, "authenticateToAnything"); a != nil { + if v, ok := a.(bool); ok && v { // Authenticate arbiters handshakeOpts.PerformAuthentication = func(_ description.Server) bool { return true } } + } - if driverInfo != nil { - if di := driverInfo.Load(); di != nil { - handshakeOpts.OuterLibraryName = di.Name - handshakeOpts.OuterLibraryVersion = di.Version - handshakeOpts.OuterLibraryPlatform = di.Platform - } - } - + handshaker = func(driver.Handshaker) driver.Handshaker { return auth.Handshaker(nil, handshakeOpts) } } else { handshaker = func(driver.Handshaker) driver.Handshaker { - op := operation.NewHello(). + return operation.NewHello(). AppName(appName). Compressors(comps). ClusterClock(clock). ServerAPI(serverAPI). - LoadBalanced(loadBalanced) - - if driverInfo != nil { - if di := driverInfo.Load(); di != nil { - op = op.OuterLibraryName(di.Name). - OuterLibraryVersion(di.Version). - OuterLibraryPlatform(di.Platform) - } - } - - return op + LoadBalanced(loadBalanced). + OuterLibraryName(outerLibraryName). + OuterLibraryVersion(outerLibraryVersion). + OuterLibraryPlatform(outerLibraryPlatform) } } diff --git a/vendor/modules.txt b/vendor/modules.txt index 7a0418d8..10f4b1d0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -240,7 +240,7 @@ github.com/xdg-go/stringprep # github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 ## explicit; go 1.17 github.com/youmark/pkcs8 -# go.mongodb.org/mongo-driver/v2 v2.4.0 +# go.mongodb.org/mongo-driver/v2 v2.3.1 ## explicit; go 1.19 go.mongodb.org/mongo-driver/v2/bson go.mongodb.org/mongo-driver/v2/event From d82b44d4a127f8708114fa989785054289a85406 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:30:24 -0500 Subject: [PATCH 02/21] update CI --- .github/workflows/all.yml | 45 +++++++++++++++++++-------------------- 1 file changed, 22 insertions(+), 23 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index ced7c10d..09e825e1 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -7,20 +7,25 @@ on: pull_request: workflow_dispatch: +env: + replsetSrcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 + replsetDstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 + shardedSrcConnStr: mongodb://localhost:27020 + shardedDstConnStr: mongodb://localhost:27030 + jobs: basics: strategy: fail-fast: false matrix: include: + - mongodb_versions: [ '4.0', '8.0' ] + topology: replset # Testing fallback when `hello` isn’t implemented # (but appendOplogNote is). - mongodb_versions: [ '4.2.5', '6.0' ] - topology: - name: replset - srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - dstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 + topology: replset exclude: - mongodb_versions: [ '4.2', '4.2' ] @@ -31,6 +36,8 @@ jobs: toHashedIndexKey: true - mongodb_versions: [ '4.2', '6.0' ] toHashedIndexKey: true + - mongodb_versions: [ '4.2', '8.0' ] + toHashedIndexKey: true # versions are: source, destination mongodb_versions: @@ -38,6 +45,7 @@ jobs: - [ '4.2', '4.4' ] - [ '4.2', '5.0' ] - [ '4.2', '6.0' ] + - [ '4.2', '8.0' ] - [ '4.4', '4.4' ] - [ '4.4', '5.0' ] @@ -61,26 +69,15 @@ jobs: toHashedIndexKey: [true, false] topology: - - name: replset - srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - dstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 - - - name: replset-to-sharded - dstArgs: --sharded 2 - srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - dstConnStr: mongodb://localhost:27030 - - - name: sharded - srcArgs: --sharded 2 - dstArgs: --sharded 2 - srcConnStr: mongodb://localhost:27020 - dstConnStr: mongodb://localhost:27030 + - replset + - replset-to-sharded + - sharded # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. runs-on: ubuntu-22.04 - name: ${{ matrix.mongodb_versions[0] }} to ${{ matrix.mongodb_versions[1] }}, ${{ matrix.topology.name }}${{ matrix.toHashedIndexKey && ', hashed doc compare' || '' }} + name: ${{ matrix.mongodb_versions[0] }} to ${{ matrix.mongodb_versions[1] }}, ${{ matrix.topology }}${{ matrix.toHashedIndexKey && ', hashed doc compare' || '' }} steps: - run: uname -a @@ -115,8 +112,8 @@ jobs: run: |- { echo ./build.sh - echo mlaunch init --binarypath $(cat .srcpath) --port 27020 --dir src --replicaset ${{ matrix.topology.srcArgs }} - echo mlaunch init --binarypath $(cat .dstpath) --port 27030 --dir dst --replicaset ${{ matrix.topology.dstArgs }} + echo mlaunch init --binarypath $(cat .srcpath) --port 27020 --dir src --replicaset ${{ (matrix.topology == 'sharded') && '--sharded 2' || '' }} + echo mlaunch init --binarypath $(cat .dstpath) --port 27030 --dir dst --replicaset ${{ (matrix.topology == 'sharded' || matrix.topology == 'replset-to-sharded') && '--sharded 2' || '' }} echo mlaunch init --binarypath $(cat .metapath) --port 27040 --dir meta --replicaset --nodes 1 } | parallel @@ -124,6 +121,8 @@ jobs: run: go test -v ./... -race env: MVTEST_DOC_COMPARE_METHOD: ${{matrix.toHashedIndexKey && 'toHashedIndexKey' || ''}} - MVTEST_SRC: ${{matrix.topology.srcConnStr}} - MVTEST_DST: ${{matrix.topology.dstConnStr}} + + MVTEST_SRC: ${{ (matrix.topology == 'sharded') && env.shardedSrcConnStr || env.replsetSrcConnStr }} + MVTEST_DST: ${{ (matrix.topology == 'sharded' || matrix.topology == 'replset-to-sharded') && env.shardedDstConnStr || env.replsetDstConnStr }} + MVTEST_META: mongodb://localhost:27040 From 6954efe2ca7c30bb324790cd3b34358c18f6863d Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:31:37 -0500 Subject: [PATCH 03/21] pare down --- .github/workflows/all.yml | 54 +++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 09e825e1..4cc004a0 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -24,8 +24,8 @@ jobs: # Testing fallback when `hello` isn’t implemented # (but appendOplogNote is). - - mongodb_versions: [ '4.2.5', '6.0' ] - topology: replset +# - mongodb_versions: [ '4.2.5', '6.0' ] +# topology: replset exclude: - mongodb_versions: [ '4.2', '4.2' ] @@ -42,36 +42,36 @@ jobs: # versions are: source, destination mongodb_versions: - [ '4.2', '4.2' ] - - [ '4.2', '4.4' ] - - [ '4.2', '5.0' ] - - [ '4.2', '6.0' ] - - [ '4.2', '8.0' ] - - - [ '4.4', '4.4' ] - - [ '4.4', '5.0' ] - - [ '4.4', '6.0' ] - - [ '4.4', '8.0' ] - - - [ '5.0', '5.0' ] - - [ '5.0', '6.0' ] - - [ '5.0', '7.0' ] - - [ '5.0', '8.0' ] - - - [ '6.0', '6.0' ] - - [ '6.0', '7.0' ] - - [ '6.0', '8.0' ] - - - [ '7.0', '7.0' ] - - [ '7.0', '8.0' ] - - - [ '8.0', '8.0' ] +# - [ '4.2', '4.4' ] +# - [ '4.2', '5.0' ] +# - [ '4.2', '6.0' ] +# - [ '4.2', '8.0' ] +# +# - [ '4.4', '4.4' ] +# - [ '4.4', '5.0' ] +# - [ '4.4', '6.0' ] +# - [ '4.4', '8.0' ] +# +# - [ '5.0', '5.0' ] +# - [ '5.0', '6.0' ] +# - [ '5.0', '7.0' ] +# - [ '5.0', '8.0' ] +# +# - [ '6.0', '6.0' ] +# - [ '6.0', '7.0' ] +# - [ '6.0', '8.0' ] +# +# - [ '7.0', '7.0' ] +# - [ '7.0', '8.0' ] +# +# - [ '8.0', '8.0' ] toHashedIndexKey: [true, false] topology: - replset - - replset-to-sharded - - sharded +# - replset-to-sharded +# - sharded # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. From 2a1d00b9265df3bb0aafcd8695beefdfc5129933 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:33:01 -0500 Subject: [PATCH 04/21] old pymongo in CI --- .github/workflows/all.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 4cc004a0..591630fd 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -96,7 +96,7 @@ jobs: run: |- { echo npm install -g m - echo pipx install 'mtools[all]' + echo pipx install pymongo==4.3.2 'mtools[all]' } | parallel - name: Install MongoDB ${{ matrix.mongodb_versions[0] }} (source) From b65c1a1fe10a58f7092eb9ab49b41a1a9cadd035 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:34:15 -0500 Subject: [PATCH 05/21] =?UTF-8?q?not=20*that*=20old=20=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/workflows/all.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 591630fd..1b04d6f4 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -92,11 +92,12 @@ jobs: with: go-version: stable + # Use an old pymongo so we can install MongoDB 4.0. - name: Install m and mtools run: |- { echo npm install -g m - echo pipx install pymongo==4.3.2 'mtools[all]' + echo pipx install pymongo==4.13.2 'mtools[all]' } | parallel - name: Install MongoDB ${{ matrix.mongodb_versions[0] }} (source) From 8e23efb7009a72f4e0296d2162f059f97cb4845b Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:34:43 -0500 Subject: [PATCH 06/21] use pip --- .github/workflows/all.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 1b04d6f4..d5acca3e 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -97,7 +97,7 @@ jobs: run: |- { echo npm install -g m - echo pipx install pymongo==4.13.2 'mtools[all]' + echo pip install pymongo==4.13.2 'mtools[all]' } | parallel - name: Install MongoDB ${{ matrix.mongodb_versions[0] }} (source) From 54920b9b4b5b36401c24b192a4f3eb8b2aa7a093 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:38:39 -0500 Subject: [PATCH 07/21] all versions --- .github/workflows/all.yml | 54 +++++++++++++++++++-------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index d5acca3e..5782c937 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -24,8 +24,8 @@ jobs: # Testing fallback when `hello` isn’t implemented # (but appendOplogNote is). -# - mongodb_versions: [ '4.2.5', '6.0' ] -# topology: replset + - mongodb_versions: [ '4.2.5', '6.0' ] + topology: replset exclude: - mongodb_versions: [ '4.2', '4.2' ] @@ -42,36 +42,36 @@ jobs: # versions are: source, destination mongodb_versions: - [ '4.2', '4.2' ] -# - [ '4.2', '4.4' ] -# - [ '4.2', '5.0' ] -# - [ '4.2', '6.0' ] -# - [ '4.2', '8.0' ] -# -# - [ '4.4', '4.4' ] -# - [ '4.4', '5.0' ] -# - [ '4.4', '6.0' ] -# - [ '4.4', '8.0' ] -# -# - [ '5.0', '5.0' ] -# - [ '5.0', '6.0' ] -# - [ '5.0', '7.0' ] -# - [ '5.0', '8.0' ] -# -# - [ '6.0', '6.0' ] -# - [ '6.0', '7.0' ] -# - [ '6.0', '8.0' ] -# -# - [ '7.0', '7.0' ] -# - [ '7.0', '8.0' ] -# -# - [ '8.0', '8.0' ] + - [ '4.2', '4.4' ] + - [ '4.2', '5.0' ] + - [ '4.2', '6.0' ] + - [ '4.2', '8.0' ] + + - [ '4.4', '4.4' ] + - [ '4.4', '5.0' ] + - [ '4.4', '6.0' ] + - [ '4.4', '8.0' ] + + - [ '5.0', '5.0' ] + - [ '5.0', '6.0' ] + - [ '5.0', '7.0' ] + - [ '5.0', '8.0' ] + + - [ '6.0', '6.0' ] + - [ '6.0', '7.0' ] + - [ '6.0', '8.0' ] + + - [ '7.0', '7.0' ] + - [ '7.0', '8.0' ] + + - [ '8.0', '8.0' ] toHashedIndexKey: [true, false] topology: - replset -# - replset-to-sharded -# - sharded + - replset-to-sharded + - sharded # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. From d573764751138551b7b69211adc7bc8e4ef53896 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:42:28 -0500 Subject: [PATCH 08/21] revert GHA --- .github/workflows/all.yml | 48 +++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 5782c937..ced7c10d 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -7,25 +7,20 @@ on: pull_request: workflow_dispatch: -env: - replsetSrcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - replsetDstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 - shardedSrcConnStr: mongodb://localhost:27020 - shardedDstConnStr: mongodb://localhost:27030 - jobs: basics: strategy: fail-fast: false matrix: include: - - mongodb_versions: [ '4.0', '8.0' ] - topology: replset # Testing fallback when `hello` isn’t implemented # (but appendOplogNote is). - mongodb_versions: [ '4.2.5', '6.0' ] - topology: replset + topology: + name: replset + srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 + dstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 exclude: - mongodb_versions: [ '4.2', '4.2' ] @@ -36,8 +31,6 @@ jobs: toHashedIndexKey: true - mongodb_versions: [ '4.2', '6.0' ] toHashedIndexKey: true - - mongodb_versions: [ '4.2', '8.0' ] - toHashedIndexKey: true # versions are: source, destination mongodb_versions: @@ -45,7 +38,6 @@ jobs: - [ '4.2', '4.4' ] - [ '4.2', '5.0' ] - [ '4.2', '6.0' ] - - [ '4.2', '8.0' ] - [ '4.4', '4.4' ] - [ '4.4', '5.0' ] @@ -69,15 +61,26 @@ jobs: toHashedIndexKey: [true, false] topology: - - replset - - replset-to-sharded - - sharded + - name: replset + srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 + dstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 + + - name: replset-to-sharded + dstArgs: --sharded 2 + srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 + dstConnStr: mongodb://localhost:27030 + + - name: sharded + srcArgs: --sharded 2 + dstArgs: --sharded 2 + srcConnStr: mongodb://localhost:27020 + dstConnStr: mongodb://localhost:27030 # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. runs-on: ubuntu-22.04 - name: ${{ matrix.mongodb_versions[0] }} to ${{ matrix.mongodb_versions[1] }}, ${{ matrix.topology }}${{ matrix.toHashedIndexKey && ', hashed doc compare' || '' }} + name: ${{ matrix.mongodb_versions[0] }} to ${{ matrix.mongodb_versions[1] }}, ${{ matrix.topology.name }}${{ matrix.toHashedIndexKey && ', hashed doc compare' || '' }} steps: - run: uname -a @@ -92,12 +95,11 @@ jobs: with: go-version: stable - # Use an old pymongo so we can install MongoDB 4.0. - name: Install m and mtools run: |- { echo npm install -g m - echo pip install pymongo==4.13.2 'mtools[all]' + echo pipx install 'mtools[all]' } | parallel - name: Install MongoDB ${{ matrix.mongodb_versions[0] }} (source) @@ -113,8 +115,8 @@ jobs: run: |- { echo ./build.sh - echo mlaunch init --binarypath $(cat .srcpath) --port 27020 --dir src --replicaset ${{ (matrix.topology == 'sharded') && '--sharded 2' || '' }} - echo mlaunch init --binarypath $(cat .dstpath) --port 27030 --dir dst --replicaset ${{ (matrix.topology == 'sharded' || matrix.topology == 'replset-to-sharded') && '--sharded 2' || '' }} + echo mlaunch init --binarypath $(cat .srcpath) --port 27020 --dir src --replicaset ${{ matrix.topology.srcArgs }} + echo mlaunch init --binarypath $(cat .dstpath) --port 27030 --dir dst --replicaset ${{ matrix.topology.dstArgs }} echo mlaunch init --binarypath $(cat .metapath) --port 27040 --dir meta --replicaset --nodes 1 } | parallel @@ -122,8 +124,6 @@ jobs: run: go test -v ./... -race env: MVTEST_DOC_COMPARE_METHOD: ${{matrix.toHashedIndexKey && 'toHashedIndexKey' || ''}} - - MVTEST_SRC: ${{ (matrix.topology == 'sharded') && env.shardedSrcConnStr || env.replsetSrcConnStr }} - MVTEST_DST: ${{ (matrix.topology == 'sharded' || matrix.topology == 'replset-to-sharded') && env.shardedDstConnStr || env.replsetDstConnStr }} - + MVTEST_SRC: ${{matrix.topology.srcConnStr}} + MVTEST_DST: ${{matrix.topology.dstConnStr}} MVTEST_META: mongodb://localhost:27040 From 9db05433ef013b27ce11d36c81eb6db8a9113445 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:43:47 -0500 Subject: [PATCH 09/21] Revert "revert GHA" This reverts commit d573764751138551b7b69211adc7bc8e4ef53896. --- .github/workflows/all.yml | 48 +++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index ced7c10d..5782c937 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -7,20 +7,25 @@ on: pull_request: workflow_dispatch: +env: + replsetSrcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 + replsetDstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 + shardedSrcConnStr: mongodb://localhost:27020 + shardedDstConnStr: mongodb://localhost:27030 + jobs: basics: strategy: fail-fast: false matrix: include: + - mongodb_versions: [ '4.0', '8.0' ] + topology: replset # Testing fallback when `hello` isn’t implemented # (but appendOplogNote is). - mongodb_versions: [ '4.2.5', '6.0' ] - topology: - name: replset - srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - dstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 + topology: replset exclude: - mongodb_versions: [ '4.2', '4.2' ] @@ -31,6 +36,8 @@ jobs: toHashedIndexKey: true - mongodb_versions: [ '4.2', '6.0' ] toHashedIndexKey: true + - mongodb_versions: [ '4.2', '8.0' ] + toHashedIndexKey: true # versions are: source, destination mongodb_versions: @@ -38,6 +45,7 @@ jobs: - [ '4.2', '4.4' ] - [ '4.2', '5.0' ] - [ '4.2', '6.0' ] + - [ '4.2', '8.0' ] - [ '4.4', '4.4' ] - [ '4.4', '5.0' ] @@ -61,26 +69,15 @@ jobs: toHashedIndexKey: [true, false] topology: - - name: replset - srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - dstConnStr: mongodb://localhost:27030,localhost:27031,localhost:27032 - - - name: replset-to-sharded - dstArgs: --sharded 2 - srcConnStr: mongodb://localhost:27020,localhost:27021,localhost:27022 - dstConnStr: mongodb://localhost:27030 - - - name: sharded - srcArgs: --sharded 2 - dstArgs: --sharded 2 - srcConnStr: mongodb://localhost:27020 - dstConnStr: mongodb://localhost:27030 + - replset + - replset-to-sharded + - sharded # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. runs-on: ubuntu-22.04 - name: ${{ matrix.mongodb_versions[0] }} to ${{ matrix.mongodb_versions[1] }}, ${{ matrix.topology.name }}${{ matrix.toHashedIndexKey && ', hashed doc compare' || '' }} + name: ${{ matrix.mongodb_versions[0] }} to ${{ matrix.mongodb_versions[1] }}, ${{ matrix.topology }}${{ matrix.toHashedIndexKey && ', hashed doc compare' || '' }} steps: - run: uname -a @@ -95,11 +92,12 @@ jobs: with: go-version: stable + # Use an old pymongo so we can install MongoDB 4.0. - name: Install m and mtools run: |- { echo npm install -g m - echo pipx install 'mtools[all]' + echo pip install pymongo==4.13.2 'mtools[all]' } | parallel - name: Install MongoDB ${{ matrix.mongodb_versions[0] }} (source) @@ -115,8 +113,8 @@ jobs: run: |- { echo ./build.sh - echo mlaunch init --binarypath $(cat .srcpath) --port 27020 --dir src --replicaset ${{ matrix.topology.srcArgs }} - echo mlaunch init --binarypath $(cat .dstpath) --port 27030 --dir dst --replicaset ${{ matrix.topology.dstArgs }} + echo mlaunch init --binarypath $(cat .srcpath) --port 27020 --dir src --replicaset ${{ (matrix.topology == 'sharded') && '--sharded 2' || '' }} + echo mlaunch init --binarypath $(cat .dstpath) --port 27030 --dir dst --replicaset ${{ (matrix.topology == 'sharded' || matrix.topology == 'replset-to-sharded') && '--sharded 2' || '' }} echo mlaunch init --binarypath $(cat .metapath) --port 27040 --dir meta --replicaset --nodes 1 } | parallel @@ -124,6 +122,8 @@ jobs: run: go test -v ./... -race env: MVTEST_DOC_COMPARE_METHOD: ${{matrix.toHashedIndexKey && 'toHashedIndexKey' || ''}} - MVTEST_SRC: ${{matrix.topology.srcConnStr}} - MVTEST_DST: ${{matrix.topology.dstConnStr}} + + MVTEST_SRC: ${{ (matrix.topology == 'sharded') && env.shardedSrcConnStr || env.replsetSrcConnStr }} + MVTEST_DST: ${{ (matrix.topology == 'sharded' || matrix.topology == 'replset-to-sharded') && env.shardedDstConnStr || env.replsetDstConnStr }} + MVTEST_META: mongodb://localhost:27040 From 4aaee9727f8d13455ae03124afb4c20fd30354c7 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:47:41 -0500 Subject: [PATCH 10/21] try 3.6 --- .github/workflows/all.yml | 5 +- go.mod | 2 +- go.sum | 2 + .../mongo-driver/v2/bson/bsoncodec.go | 6 +- .../mongo-driver/v2/bson/buffered_byte_src.go | 128 ----- .../mongo-driver/v2/bson/codec_cache.go | 4 +- .../mongo-driver/v2/bson/copier.go | 8 +- .../mongo-driver/v2/bson/decimal.go | 4 +- .../mongo-driver/v2/bson/decoder.go | 6 +- .../v2/bson/default_value_decoders.go | 31 +- .../v2/bson/default_value_encoders.go | 4 +- .../mongo-driver/v2/bson/doc.go | 78 +-- .../v2/bson/empty_interface_codec.go | 6 +- .../mongo-driver/v2/bson/encoder.go | 13 +- .../mongo-driver/v2/bson/extjson_parser.go | 2 +- .../mongo-driver/v2/bson/extjson_writer.go | 7 +- .../mongo-driver/v2/bson/json_scanner.go | 2 +- .../mongo-driver/v2/bson/marshal.go | 17 +- .../mongo-driver/v2/bson/mgoregistry.go | 4 +- .../mongo-driver/v2/bson/primitive.go | 14 +- .../mongo-driver/v2/bson/raw_value.go | 10 +- .../mongo-driver/v2/bson/registry.go | 4 +- .../v2/bson/streaming_byte_src.go | 104 ---- .../mongo-driver/v2/bson/struct_codec.go | 4 - .../mongo-driver/v2/bson/types.go | 2 +- .../mongo-driver/v2/bson/unmarshal.go | 14 +- .../mongo-driver/v2/bson/value_reader.go | 524 +++++++----------- .../mongo-driver/v2/bson/value_writer.go | 25 +- .../v2/internal/bsoncoreutil/bsoncoreutil.go | 2 +- .../v2/internal/bsonutil/bsonutil.go | 6 +- .../v2/internal/codecutil/encoding.go | 8 +- .../v2/internal/driverutil/description.go | 2 +- .../v2/internal/driverutil/operation.go | 37 -- .../v2/internal/httputil/httputil.go | 14 +- .../v2/internal/logger/component.go | 16 +- .../v2/internal/logger/io_sink.go | 6 +- .../mongo-driver/v2/internal/logger/logger.go | 13 +- .../v2/internal/mongoutil/mongoutil.go | 16 - .../v2/internal/optionsutil/options.go | 45 -- .../v2/mongo/background_context.go | 2 +- .../mongo-driver/v2/mongo/batch_cursor.go | 7 +- .../mongo-driver/v2/mongo/bulk_write.go | 35 +- .../v2/mongo/bulk_write_models.go | 137 +++-- .../mongo-driver/v2/mongo/change_stream.go | 83 +-- .../mongo-driver/v2/mongo/client.go | 35 +- .../v2/mongo/client_bulk_write.go | 51 +- .../v2/mongo/client_bulk_write_models.go | 72 +-- .../v2/mongo/client_encryption.go | 9 +- .../mongo-driver/v2/mongo/collection.go | 195 ++----- .../mongo-driver/v2/mongo/cursor.go | 116 +--- .../mongo-driver/v2/mongo/database.go | 100 ++-- .../mongo-driver/v2/mongo/doc.go | 4 +- .../mongo-driver/v2/mongo/errors.go | 174 +----- .../mongo-driver/v2/mongo/gridfs_bucket.go | 20 +- .../v2/mongo/gridfs_download_stream.go | 33 +- .../v2/mongo/gridfs_upload_stream.go | 6 +- .../mongo-driver/v2/mongo/index_view.go | 60 +- .../mongo-driver/v2/mongo/mongo.go | 31 +- .../mongo-driver/v2/mongo/mongocryptd.go | 2 +- .../v2/mongo/options/aggregateoptions.go | 28 +- .../v2/mongo/options/autoencryptionoptions.go | 26 +- .../v2/mongo/options/bulkwriteoptions.go | 17 +- .../v2/mongo/options/changestreamoptions.go | 19 +- .../mongo/options/clientbulkwriteoptions.go | 13 +- .../mongo/options/clientencryptionoptions.go | 20 +- .../v2/mongo/options/clientoptions.go | 66 +-- .../v2/mongo/options/countoptions.go | 21 +- .../mongo/options/createcollectionoptions.go | 47 +- .../v2/mongo/options/datakeyoptions.go | 4 +- .../v2/mongo/options/deleteoptions.go | 80 ++- .../v2/mongo/options/distinctoptions.go | 22 +- .../v2/mongo/options/dropcollectionoptions.go | 4 +- .../v2/mongo/options/estimatedcountoptions.go | 10 +- .../v2/mongo/options/findoptions.go | 207 ++++--- .../v2/mongo/options/gridfsoptions.go | 8 +- .../v2/mongo/options/indexoptions.go | 43 +- .../v2/mongo/options/insertoptions.go | 24 +- .../mongo/options/listcollectionsoptions.go | 6 - .../v2/mongo/options/loggeroptions.go | 4 +- .../v2/mongo/options/replaceoptions.go | 46 +- .../v2/mongo/options/rewrapdatakeyoptions.go | 4 +- .../v2/mongo/options/updateoptions.go | 108 ++-- .../mongo-driver/v2/mongo/readpref/options.go | 13 +- .../v2/mongo/readpref/readpref.go | 8 +- .../mongo-driver/v2/mongo/results.go | 27 +- .../v2/mongo/search_index_view.go | 8 +- .../mongo-driver/v2/mongo/session.go | 11 +- .../mongo-driver/v2/mongo/single_result.go | 6 +- .../v2/mongo/writeconcern/writeconcern.go | 2 +- .../mongo-driver/v2/version/version.go | 2 +- .../mongo-driver/v2/x/bsonx/bsoncore/array.go | 87 ++- .../v2/x/bsonx/bsoncore/document.go | 90 ++- .../v2/x/bsonx/bsoncore/element.go | 75 +-- .../mongo-driver/v2/x/bsonx/bsoncore/value.go | 103 ++-- .../v2/x/mongo/driver/auth/auth.go | 8 +- .../v2/x/mongo/driver/auth/default.go | 43 +- .../v2/x/mongo/driver/auth/mongodbcr.go | 120 ++++ .../v2/x/mongo/driver/auth/oidc.go | 83 +-- .../v2/x/mongo/driver/batch_cursor.go | 40 +- .../v2/x/mongo/driver/compression.go | 4 +- .../x/mongo/driver/connstring/connstring.go | 12 + .../x/mongo/driver/mongocrypt/mongocrypt.go | 12 - .../mongocrypt/options/mongocrypt_options.go | 9 - .../v2/x/mongo/driver/operation.go | 63 +-- .../v2/x/mongo/driver/operation/aggregate.go | 17 +- .../v2/x/mongo/driver/operation/count.go | 17 +- .../v2/x/mongo/driver/operation/create.go | 2 +- .../mongo/driver/operation/create_indexes.go | 15 - .../v2/x/mongo/driver/operation/delete.go | 18 +- .../v2/x/mongo/driver/operation/distinct.go | 15 - .../x/mongo/driver/operation/drop_indexes.go | 17 +- .../v2/x/mongo/driver/operation/find.go | 15 - .../mongo/driver/operation/find_and_modify.go | 17 +- .../v2/x/mongo/driver/operation/insert.go | 15 - .../driver/operation/list_collections.go | 18 +- .../x/mongo/driver/operation/list_indexes.go | 18 +- .../v2/x/mongo/driver/operation/update.go | 26 +- .../v2/x/mongo/driver/topology/connection.go | 55 +- .../v2/x/mongo/driver/topology/errors.go | 33 +- .../v2/x/mongo/driver/topology/fsm.go | 2 +- .../v2/x/mongo/driver/topology/pool.go | 22 +- .../v2/x/mongo/driver/topology/server.go | 2 +- .../v2/x/mongo/driver/topology/topology.go | 10 +- .../mongo/driver/topology/topology_options.go | 10 - .../x/mongo/driver/wiremessage/wiremessage.go | 2 +- vendor/modules.txt | 5 +- 126 files changed, 1570 insertions(+), 2801 deletions(-) delete mode 100644 vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go delete mode 100644 vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go delete mode 100644 vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go create mode 100644 vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 5782c937..a36bf1b1 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -19,6 +19,9 @@ jobs: fail-fast: false matrix: include: + - mongodb_versions: [ '3.6', '8.0' ] + topology: replset + - mongodb_versions: [ '4.0', '8.0' ] topology: replset @@ -97,7 +100,7 @@ jobs: run: |- { echo npm install -g m - echo pip install pymongo==4.13.2 'mtools[all]' + echo pip install pymongo==4.10.1 'mtools[all]' } | parallel - name: Install MongoDB ${{ matrix.mongodb_versions[0] }} (source) diff --git a/go.mod b/go.mod index 90bb96e9..1f15ff50 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,7 @@ require ( github.com/samber/mo v1.13.0 github.com/stretchr/testify v1.10.0 github.com/urfave/cli v1.22.9 - go.mongodb.org/mongo-driver/v2 v2.3.1 + go.mongodb.org/mongo-driver/v2 v2.1.0 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 golang.org/x/sync v0.13.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 diff --git a/go.sum b/go.sum index 9456b762..32d9b3f4 100644 --- a/go.sum +++ b/go.sum @@ -129,6 +129,8 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver/v2 v2.1.0 h1:/ELnVNjmfUKDsoBisXxuJL0noR9CfeUIrP7Yt3R+egg= +go.mongodb.org/mongo-driver/v2 v2.1.0/go.mod h1:AWiLRShSrk5RHQS3AEn3RL19rqOzVq49MCpWQ3x/huI= go.mongodb.org/mongo-driver/v2 v2.3.1 h1:WrCgSzO7dh1/FrePud9dK5fKNZOE97q5EQimGkos7Wo= go.mongodb.org/mongo-driver/v2 v2.3.1/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI= go.mongodb.org/mongo-driver/v2 v2.4.0 h1:Oq6BmUAAFTzMeh6AonuDlgZMuAuEiUxoAD1koK5MuFo= diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go index 78b861a3..bacc99fb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go @@ -69,9 +69,6 @@ func (vde ValueDecoderError) Error() string { if vde.Received.IsValid() { received = vde.Received.Type().String() } - if !vde.Received.CanSet() { - received = "unsettable " + received - } return fmt.Sprintf("%s can only decode valid and settable %s, but got %s", vde.Name, strings.Join(typeKinds, ", "), received) } @@ -91,7 +88,6 @@ type EncodeContext struct { nilSliceAsEmpty bool nilByteSliceAsEmpty bool omitZeroStruct bool - omitEmpty bool useJSONStructTags bool } @@ -107,7 +103,7 @@ type DecodeContext struct { truncate bool // defaultDocumentType specifies the Go type to decode top-level and nested BSON documents into. In particular, the - // usage for this field is restricted to data typed as "any" or "map[string]any". If DocumentType is + // usage for this field is restricted to data typed as "interface{}" or "map[string]interface{}". If DocumentType is // set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an // error. defaultDocumentType reflect.Type diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go deleted file mode 100644 index eb19e3cb..00000000 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2025-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 ( - "bytes" - "io" -) - -// bufferedByteSrc implements the low-level byteSrc interface by reading -// directly from an in-memory byte slice. It provides efficient, zero-copy -// access for parsing BSON when the entire document is buffered in memory. -type bufferedByteSrc struct { - buf []byte // entire BSON document - offset int64 // Current read index into buf -} - -var _ byteSrc = (*bufferedByteSrc)(nil) - -// Read reads up to len(p) bytes from the in-memory buffer, advancing the offset -// by the number of bytes read. -func (b *bufferedByteSrc) readExact(p []byte) (int, error) { - if b.offset >= int64(len(b.buf)) { - return 0, io.EOF - } - n := copy(p, b.buf[b.offset:]) - b.offset += int64(n) - return n, nil -} - -// ReadByte returns the single byte at buf[offset] and advances offset by 1. -func (b *bufferedByteSrc) ReadByte() (byte, error) { - if b.offset >= int64(len(b.buf)) { - return 0, io.EOF - } - b.offset++ - return b.buf[b.offset-1], nil -} - -// peek returns buf[offset:offset+n] without advancing offset. -func (b *bufferedByteSrc) peek(n int) ([]byte, error) { - // Ensure we don't read past the end of the buffer. - if int64(n)+b.offset > int64(len(b.buf)) { - return b.buf[b.offset:], io.EOF - } - - // Return the next n bytes without advancing the offset - return b.buf[b.offset : b.offset+int64(n)], nil -} - -// discard advances offset by n bytes, returning the number of bytes discarded. -func (b *bufferedByteSrc) discard(n int) (int, error) { - // Ensure we don't read past the end of the buffer. - if int64(n)+b.offset > int64(len(b.buf)) { - // If we have exceeded the buffer length, discard only up to the end. - left := len(b.buf) - int(b.offset) - b.offset = int64(len(b.buf)) - - return left, io.EOF - } - - // Advance the read position - b.offset += int64(n) - return n, nil -} - -// readSlice scans buf[offset:] for the first occurrence of delim, returns -// buf[offset:idx+1], and advances offset past it; errors if delim not found. -func (b *bufferedByteSrc) readSlice(delim byte) ([]byte, error) { - // Ensure we don't read past the end of the buffer. - if b.offset >= int64(len(b.buf)) { - return nil, io.EOF - } - - // Look for the delimiter in the remaining bytes - rem := b.buf[b.offset:] - idx := bytes.IndexByte(rem, delim) - if idx < 0 { - return nil, io.EOF - } - - // Build the result slice up through the delimiter. - result := rem[:idx+1] - - // Advance the offset past the delimiter. - b.offset += int64(idx + 1) - - return result, nil -} - -// pos returns the current read position in the buffer. -func (b *bufferedByteSrc) pos() int64 { - return b.offset -} - -// regexLength will return the total byte length of a BSON regex value. -func (b *bufferedByteSrc) regexLength() (int32, error) { - rem := b.buf[b.offset:] - - // Find end of the first C-string (pattern). - i := bytes.IndexByte(rem, 0x00) - if i < 0 { - return 0, io.EOF - } - - // Find end of second C-string (options). - j := bytes.IndexByte(rem[i+1:], 0x00) - if j < 0 { - return 0, io.EOF - } - - // Total length = first C-string length (pattern) + second C-string length - // (options) + 2 null terminators - return int32(i + j + 2), nil -} - -func (*bufferedByteSrc) streamable() bool { - return false -} - -func (b *bufferedByteSrc) reset() { - b.buf = nil - b.offset = 0 -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go index de97441e..b4042822 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go @@ -49,7 +49,7 @@ func (c *typeEncoderCache) LoadOrStore(rt reflect.Type, enc ValueEncoder) ValueE func (c *typeEncoderCache) Clone() *typeEncoderCache { cc := new(typeEncoderCache) - c.cache.Range(func(k, v any) bool { + c.cache.Range(func(k, v interface{}) bool { if k != nil && v != nil { cc.cache.Store(k, v) } @@ -82,7 +82,7 @@ func (c *typeDecoderCache) LoadOrStore(rt reflect.Type, dec ValueDecoder) ValueD func (c *typeDecoderCache) Clone() *typeDecoderCache { cc := new(typeDecoderCache) - c.cache.Range(func(k, v any) bool { + c.cache.Range(func(k, v interface{}) bool { if k != nil && v != nil { cc.cache.Store(k, v) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go index c9a37c75..6279f072 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go @@ -7,6 +7,7 @@ package bson import ( + "bytes" "errors" "fmt" "io" @@ -179,11 +180,8 @@ func copyValueFromBytes(dst ValueWriter, t Type, src []byte) error { return wvb.writeValueBytes(t, src) } - vr := newBufferedDocumentReader(src) - vr.advanceFrame() - - vr.stack[vr.frame].mode = mElement - vr.stack[vr.frame].vType = t + vr := newDocumentReader(bytes.NewReader(src)) + vr.pushElement(t) return copyValue(dst, vr) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go index 6241733a..85c506ef 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go @@ -145,7 +145,7 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { return nil } - var res any + var res interface{} err := json.Unmarshal(b, &res) if err != nil { return err @@ -154,7 +154,7 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { // Extended JSON if !ok { - m, ok := res.(map[string]any) + m, ok := res.(map[string]interface{}) if !ok { return errors.New("not an extended JSON Decimal128: expected document") } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go index 4c24dc66..2fa9e6f1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go @@ -20,7 +20,7 @@ var ErrDecodeToNil = errors.New("cannot Decode to nil value") // methods and is not consumable from outside of this package. The Decoders retrieved from this pool // must have both Reset and SetRegistry called on them. var decPool = sync.Pool{ - New: func() any { + New: func() interface{} { return new(Decoder) }, } @@ -44,7 +44,7 @@ func NewDecoder(vr ValueReader) *Decoder { // value pointed to by val. // // See [Unmarshal] for details about BSON unmarshaling behavior. -func (d *Decoder) Decode(val any) error { +func (d *Decoder) Decode(val interface{}) error { if unmarshaler, ok := val.(Unmarshaler); ok { // TODO(skriptble): Reuse a []byte here and use the AppendDocumentBytes method. buf, err := copyDocumentToBytes(d.vr) @@ -88,7 +88,7 @@ func (d *Decoder) SetRegistry(r *Registry) { } // DefaultDocumentM causes the Decoder to always unmarshal documents into the bson.M type. This -// behavior is restricted to data typed as "any" or "map[string]any". +// behavior is restricted to data typed as "interface{}" or "map[string]interface{}". func (d *Decoder) DefaultDocumentM() { d.dc.defaultDocumentType = reflect.TypeOf(M{}) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go index 8ce5954d..42ea2e58 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go @@ -32,8 +32,8 @@ func (d decodeBinaryError) Error() string { // registerDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with // the provided RegistryBuilder. // -// There is no support for decoding map[string]any because there is no decoder for -// any, so users must either register this decoder themselves or use the +// There is no support for decoding map[string]interface{} because there is no decoder for +// interface{}, so users must either register this decoder themselves or use the // EmptyInterfaceDecoder available in the bson package. func registerDefaultDecoders(reg *Registry) { intDecoder := decodeAdapter{intDecodeValue, intDecodeType} @@ -150,7 +150,7 @@ func dDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { return err } - var v any + var v interface{} err = decoder.DecodeValue(dc, elemVr, reflect.ValueOf(&v).Elem()) if err != nil { return err @@ -1332,12 +1332,8 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle eType := val.Type().Elem() - isInterfaceSlice := eType.Kind() == reflect.Interface && val.Len() > 0 - - // If this is not an interface slice with pre-populated elements, we can look up - // the decoder for eType once. var vDecoder ValueDecoder - if !isInterfaceSlice { + if !(eType.Kind() == reflect.Interface && val.Len() > 0) { vDecoder, err = dc.LookupDecoder(eType) if err != nil { return nil, err @@ -1355,9 +1351,7 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle } var elem reflect.Value - if isInterfaceSlice && idx < val.Len() { - // Decode into an existing any slot. - + if vDecoder == nil { elem = val.Index(idx).Elem() switch { case elem.Kind() != reflect.Ptr || elem.IsNil(): @@ -1365,12 +1359,6 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle if err != nil { return nil, err } - - // If an element is allocated and unsettable, it must be overwritten. - if !elem.CanSet() { - elem = reflect.New(elem.Type()).Elem() - } - err = valueDecoder.DecodeValue(dc, vr, elem) if err != nil { return nil, newDecodeError(strconv.Itoa(idx), err) @@ -1392,15 +1380,6 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle } } } else { - // For non-interface slices, or if we've exhausted the pre-populated - // slots, we create a fresh value. - - if vDecoder == nil { - vDecoder, err = dc.LookupDecoder(eType) - if err != nil { - return nil, err - } - } elem, err = decodeTypeOrValueWithInfo(vDecoder, dc, vr, eType) if err != nil { return nil, newDecodeError(strconv.Itoa(idx), err) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go index 67d464cb..bd5a20f2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go @@ -18,7 +18,7 @@ import ( ) var bvwPool = sync.Pool{ - New: func() any { + New: func() interface{} { return new(valueWriter) }, } @@ -26,7 +26,7 @@ var bvwPool = sync.Pool{ var errInvalidValue = errors.New("cannot encode invalid element") var sliceWriterPool = sync.Pool{ - New: func() any { + New: func() interface{} { sw := make(sliceWriter, 0) return &sw }, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go index b346f71f..81aceef2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go @@ -4,14 +4,30 @@ // not use this 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 is a library for reading, writing, and manipulating BSON. BSON is a binary serialization -// format used to store documents and make remote procedure calls in MongoDB. For more information about -// the Go BSON library, including usage examples, check out the [Work with BSON] page in the Go Driver -// docs site. For more information about BSON, see https://bsonspec.org. +// Package bson is a library for reading, writing, and manipulating BSON. BSON is a binary serialization format used to +// store documents and make remote procedure calls in MongoDB. The BSON specification is located at https://bsonspec.org. +// The BSON library handles marshaling and unmarshaling of values through a configurable codec system. For a description +// of the codec system and examples of registering custom codecs, see the bsoncodec package. For additional information +// and usage examples, check out the [Work with BSON] page in the Go Driver docs site. +// +// # Raw BSON +// +// The Raw family of types is used to validate and retrieve elements from a slice of bytes. This +// type is most useful when you want do lookups on BSON bytes without unmarshaling it into another +// type. +// +// Example: +// +// var raw bson.Raw = ... // bytes from somewhere +// err := raw.Validate() +// if err != nil { return err } +// val := raw.Lookup("foo") +// i32, ok := val.Int32OK() +// // do something with i32... // // # Native Go Types // -// The [D] and [M] types defined in this package can be used to build representations of BSON using native Go types. D is a +// The D and M types defined in this package can be used to build representations of BSON using native Go types. D is a // slice and M is a map. For more information about the use cases for these types, see the documentation on the type // definitions. // @@ -74,19 +90,29 @@ // 4. A pointer field is marshaled as the underlying type if the pointer is non-nil. If the pointer is nil, it is // marshaled as a BSON null value. // -// 5. When unmarshaling, a field of type any will follow the D/M type mappings listed above. BSON documents -// unmarshaled into an any field will be unmarshaled as a D. +// 5. When unmarshaling, a field of type interface{} will follow the D/M type mappings listed above. BSON documents +// unmarshaled into an interface{} field will be unmarshaled as a D. +// +// The encoding of each struct field can be customized by the "bson" struct tag. +// +// This tag behavior is configurable, and different struct tag behavior can be configured by initializing a new +// bsoncodec.StructCodec with the desired tag parser and registering that StructCodec onto the Registry. By default, JSON +// tags are not honored, but that can be enabled by creating a StructCodec with JSONFallbackStructTagParser, like below: // -// The encoding of each struct field can be customized by the "bson" struct tag. The "bson" tag gives the name of the -// field, followed by a comma-separated list of options. The name may be omitted in order to specify options without -// overriding the default field name. The following options can be used to configure behavior: +// Example: +// +// structcodec, _ := bsoncodec.NewStructCodec(bsoncodec.JSONFallbackStructTagParser) +// +// The bson tag gives the name of the field, possibly followed by a comma-separated list of options. +// The name may be empty in order to specify options without overriding the default field name. The following options can +// be used to configure behavior: // // 1. omitempty: If the "omitempty" struct tag is specified on a field, the field will not be marshaled if it is set to // an "empty" value. Numbers, booleans, and strings are considered empty if their value is equal to the zero value for // the type (i.e. 0 for numbers, false for booleans, and "" for strings). Slices, maps, and arrays are considered // empty if they are of length zero. Interfaces and pointers are considered empty if their value is nil. By default, -// structs are only considered empty if the struct type implements [Zeroer] and the "IsZero" -// method returns true. Struct types that do not implement [Zeroer] are never considered empty and will be +// structs are only considered empty if the struct type implements [bsoncodec.Zeroer] and the IsZero +// method returns true. Struct types that do not implement [bsoncodec.Zeroer] are never considered empty and will be // marshaled as embedded documents. NOTE: It is recommended that this tag be used for all slice and map fields. // // 2. minsize: If the minsize struct tag is specified on a field of type int64, uint, uint32, or uint64 and the value of @@ -101,33 +127,23 @@ // 4. inline: If the inline struct tag is specified for a struct or map field, the field will be "flattened" when // marshaling and "un-flattened" when unmarshaling. This means that all of the fields in that struct/map will be // pulled up one level and will become top-level fields rather than being fields in a nested document. For example, -// if a map field named "Map" with value map[string]any{"foo": "bar"} is inlined, the resulting document will +// if a map field named "Map" with value map[string]interface{}{"foo": "bar"} is inlined, the resulting document will // be {"foo": "bar"} instead of {"map": {"foo": "bar"}}. There can only be one inlined map field in a struct. If // there are duplicated fields in the resulting document when an inlined struct is marshaled, the inlined field will // be overwritten. If there are duplicated fields in the resulting document when an inlined map is marshaled, an // error will be returned. This tag can be used with fields that are pointers to structs. If an inlined pointer field // is nil, it will not be marshaled. For fields that are not maps or structs, this tag is ignored. // -// # Raw BSON +// # Marshaling and Unmarshaling // -// The Raw family of types is used to validate and retrieve elements from a slice of bytes. This -// type is most useful when you want do lookups on BSON bytes without unmarshaling it into another -// type. +// Manually marshaling and unmarshaling can be done with the Marshal and Unmarshal family of functions. // -// Example: +// bsoncodec code 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. // -// var raw bson.Raw = ... // bytes from somewhere -// err := raw.Validate() -// if err != nil { return err } -// val := raw.Lookup("foo") -// i32, ok := val.Int32OK() -// // do something with i32... -// -// # Custom Registry -// -// The Go BSON library uses a [Registry] to define encoding and decoding behavior for different data types. -// The default encoding and decoding behavior can be customized or extended by using a modified Registry. -// The custom registry system is composed of two parts: +// The codec system is composed of two parts: // // 1) [ValueEncoder] and [ValueDecoder] that handle encoding and decoding Go values to and from BSON // representations. @@ -135,7 +151,5 @@ // 2) A [Registry] that holds these ValueEncoders and ValueDecoders and provides methods for // retrieving them. // -// To use a custom Registry, use [Encoder.SetRegistry] or [Decoder.SetRegistry]. -// // [Work with BSON]: https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/ package bson diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go index ae1db53f..80d44d8c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go @@ -10,7 +10,7 @@ import ( "reflect" ) -// emptyInterfaceCodec is the Codec used for any values. +// emptyInterfaceCodec is the Codec used for interface{} values. type emptyInterfaceCodec struct { // decodeBinaryAsSlice causes DecodeValue to unmarshal BSON binary field values that are the // "Generic" or "Old" BSON binary subtype as a Go byte slice instead of a Binary. @@ -22,7 +22,7 @@ type emptyInterfaceCodec struct { // collection. var _ typeDecoder = &emptyInterfaceCodec{} -// EncodeValue is the ValueEncoderFunc for any. +// EncodeValue is the ValueEncoderFunc for interface{}. func (eic *emptyInterfaceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tEmpty { return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val} @@ -111,7 +111,7 @@ func (eic *emptyInterfaceCodec) decodeType(dc DecodeContext, vr ValueReader, t r return elem, nil } -// DecodeValue is the ValueDecoderFunc for any. +// DecodeValue is the ValueDecoderFunc for interface{}. func (eic *emptyInterfaceCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tEmpty { return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go index d27bb7b5..0ad2432d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go @@ -15,7 +15,7 @@ import ( // methods and is not consumable from outside of this package. The Encoders retrieved from this pool // must have both Reset and SetRegistry called on them. var encPool = sync.Pool{ - New: func() any { + New: func() interface{} { return new(Encoder) }, } @@ -38,7 +38,7 @@ func NewEncoder(vw ValueWriter) *Encoder { // Encode writes the BSON encoding of val to the stream. // // See [Marshal] for details about BSON marshaling behavior. -func (e *Encoder) Encode(val any) error { +func (e *Encoder) Encode(val interface{}) error { if marshaler, ok := val.(Marshaler); ok { // TODO(skriptble): Should we have a MarshalAppender interface so that we can have []byte reuse? buf, err := marshaler.MarshalBSON() @@ -108,8 +108,7 @@ func (e *Encoder) NilByteSliceAsEmpty() { // TODO struct fields once the logic is updated to also inspect private struct fields. // OmitZeroStruct causes the Encoder to consider the zero value for a struct (e.g. MyStruct{}) -// as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set -// or the OmitEmpty() method is called. +// as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set. // // Note that the Encoder only examines exported struct fields when determining if a struct is the // zero value. It considers pointers to a zero struct value (e.g. &MyStruct{}) not empty. @@ -117,12 +116,6 @@ func (e *Encoder) OmitZeroStruct() { e.ec.omitZeroStruct = true } -// OmitEmpty causes the Encoder to omit empty values from the marshaled BSON as the "omitempty" -// struct tag option is set. -func (e *Encoder) OmitEmpty() { - e.ec.omitEmpty = true -} - // UseJSONStructTags causes the Encoder to fall back to using the "json" struct tag if a "bson" // struct tag is not specified. func (e *Encoder) UseJSONStructTags() { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go index eb536a67..a63f23a2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go @@ -46,7 +46,7 @@ const ( type extJSONValue struct { t Type - v any + v interface{} } type extJSONObject struct { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go index 2d43943f..5f231ba1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go @@ -407,13 +407,12 @@ func (ejvw *extJSONValueWriter) WriteRegex(pattern string, options string) error return err } - options = sortStringAlphebeticAscending(options) var buf bytes.Buffer buf.WriteString(`{"$regularExpression":{"pattern":`) writeStringWithEscapes(pattern, &buf, ejvw.escapeHTML) - buf.WriteString(`,"options":`) - writeStringWithEscapes(options, &buf, ejvw.escapeHTML) - buf.WriteString(`}},`) + buf.WriteString(`,"options":"`) + buf.WriteString(sortStringAlphebeticAscending(options)) + buf.WriteString(`"}},`) ejvw.buf = append(ejvw.buf, buf.Bytes()...) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go index bc03915d..b6eba79e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go @@ -37,7 +37,7 @@ const ( type jsonToken struct { t jsonTokenType - v any + v interface{} p int } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go index 71a28dab..21631d81 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go @@ -15,7 +15,7 @@ import ( const defaultDstCap = 256 var extjPool = sync.Pool{ - New: func() any { + New: func() interface{} { return new(extJSONValueWriter) }, } @@ -43,7 +43,7 @@ type ValueMarshaler interface { // Pool of buffers for marshalling BSON. var bufPool = sync.Pool{ - New: func() any { + New: func() interface{} { return new(bytes.Buffer) }, } @@ -54,7 +54,7 @@ var bufPool = sync.Pool{ // Marshal will use the default registry created by NewRegistry to recursively // marshal val into a []byte. Marshal will inspect struct tags and alter the // marshaling process accordingly. -func Marshal(val any) ([]byte, error) { +func Marshal(val interface{}) ([]byte, error) { sw := bufPool.Get().(*bytes.Buffer) defer func() { // Proper usage of a sync.Pool requires each entry to have approximately @@ -74,10 +74,7 @@ func Marshal(val any) ([]byte, error) { } }() sw.Reset() - - vw := getDocumentWriter(sw) - defer putDocumentWriter(vw) - + vw := NewDocumentWriter(sw) enc := encPool.Get().(*Encoder) defer encPool.Put(enc) enc.Reset(vw) @@ -94,7 +91,7 @@ func Marshal(val any) ([]byte, error) { // // MarshalValue will use bson.NewRegistry() to transform val into a BSON value. If val is a struct, this function will // inspect struct tags and alter the marshalling process accordingly. -func MarshalValue(val any) (Type, []byte, error) { +func MarshalValue(val interface{}) (Type, []byte, error) { sw := bufPool.Get().(*bytes.Buffer) defer func() { // Proper usage of a sync.Pool requires each entry to have approximately @@ -143,7 +140,7 @@ func MarshalValue(val any) (Type, []byte, error) { } // MarshalExtJSON returns the extended JSON encoding of val. -func MarshalExtJSON(val any, canonical, escapeHTML bool) ([]byte, error) { +func MarshalExtJSON(val interface{}, canonical, escapeHTML bool) ([]byte, error) { sw := sliceWriter(make([]byte, 0, defaultDstCap)) ejvw := extjPool.Get().(*extJSONValueWriter) ejvw.reset(sw, canonical, escapeHTML) @@ -175,7 +172,7 @@ func IndentExtJSON(dst *bytes.Buffer, src []byte, prefix, indent string) error { // MarshalExtJSONIndent returns the extended JSON encoding of val with each line with prefixed // and indented. -func MarshalExtJSONIndent(val any, canonical, escapeHTML bool, prefix, indent string) ([]byte, error) { +func MarshalExtJSONIndent(val interface{}, canonical, escapeHTML bool, prefix, indent string) ([]byte, error) { marshaled, err := MarshalExtJSON(val, canonical, escapeHTML) if err != nil { return nil, err diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go index 6aa74f29..f42935e5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go @@ -17,7 +17,7 @@ var ( tInt = reflect.TypeOf(int(0)) tM = reflect.TypeOf(M{}) - tInterfaceSlice = reflect.TypeOf([]any{}) + tInterfaceSlice = reflect.TypeOf([]interface{}{}) tGetter = reflect.TypeOf((*getter)(nil)).Elem() tSetter = reflect.TypeOf((*setter)(nil)).Elem() ) @@ -131,7 +131,7 @@ type setter interface { // If GetBSON returns return a non-nil error, the marshalling procedure // will stop and error out with the provided value. type getter interface { - GetBSON() (any, error) + GetBSON() (interface{}, error) } // setterDecodeValue is the ValueDecoderFunc for Setter types. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go index 55d57446..162bfa71 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go @@ -137,7 +137,7 @@ type Symbol string // CodeWithScope represents a BSON JavaScript code with scope value. type CodeWithScope struct { Code JavaScript - Scope any + Scope interface{} } func (cws CodeWithScope) String() string { @@ -257,17 +257,17 @@ func (d *D) UnmarshalJSON(b []byte) error { // E represents a BSON element for a D. It is usually used inside a D. type E struct { Key string - Value any + Value interface{} } // M is an unordered representation of a BSON document. This type should be used when the order of the elements does not -// matter. This type is handled as a regular map[string]any when encoding and decoding. Elements will be +// matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be // serialized in an undefined, random order. If the order of the elements matters, a D should be used instead. // // Example usage: // // bson.M{"foo": "bar", "hello": "world", "pi": 3.14159} -type M map[string]any +type M map[string]interface{} func (m M) String() string { b, err := MarshalExtJSON(m, true, false) @@ -282,7 +282,7 @@ func (m M) String() string { // Example usage: // // bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}} -type A []any +type A []interface{} func jsonDecodeD(dec *json.Decoder) (D, error) { res := D{} @@ -326,8 +326,8 @@ func jsonDecodeD(dec *json.Decoder) (D, error) { return res, nil } -func jsonDecodeSlice(dec *json.Decoder) ([]any, error) { - var res []any +func jsonDecodeSlice(dec *json.Decoder) ([]interface{}, error) { + var res []interface{} done := false for !done { t, err := dec.Token() diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go index 24283a24..53f053f0 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go @@ -43,7 +43,7 @@ func (rv RawValue) IsZero() bool { // error is returned. This method will use the registry used to create the RawValue, if the RawValue // was created from partial BSON processing, or it will use the default registry. Users wishing to // specify the registry to use should use UnmarshalWithRegistry. -func (rv RawValue) Unmarshal(val any) error { +func (rv RawValue) Unmarshal(val interface{}) error { reg := rv.r if reg == nil { reg = defaultRegistry @@ -66,12 +66,12 @@ func (rv RawValue) Equal(rv2 RawValue) bool { // UnmarshalWithRegistry performs the same unmarshalling as Unmarshal but uses the provided registry // instead of the one attached or the default registry. -func (rv RawValue) UnmarshalWithRegistry(r *Registry, val any) error { +func (rv RawValue) UnmarshalWithRegistry(r *Registry, val interface{}) error { if r == nil { return ErrNilRegistry } - vr := newBufferedValueReader(rv.Type, rv.Value) + vr := newValueReader(rv.Type, bytes.NewReader(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) @@ -86,12 +86,12 @@ func (rv RawValue) UnmarshalWithRegistry(r *Registry, val any) error { // 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 *DecodeContext, val any) error { +func (rv RawValue) UnmarshalWithContext(dc *DecodeContext, val interface{}) error { if dc == nil { return ErrNilContext } - vr := newBufferedValueReader(rv.Type, rv.Value) + vr := newValueReader(rv.Type, bytes.NewReader(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) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go index 21057da4..d8f65ddc 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go @@ -65,7 +65,7 @@ func (entme errNoTypeMapEntry) Error() string { // for any value whose type implements bson.Marshaler, regardless of the value's concrete type. // // 3. Type map entries - This can be used to associate a BSON type with a Go type. These type -// associations are used when decoding into a bson.D/bson.M or a struct field of type any. +// associations are used when decoding into a bson.D/bson.M or a struct field of type interface{}. // For example, by default, BSON int32 and int64 values decode as Go int32 and int64 instances, // respectively, when decoding into a bson.D. The following code would change the behavior so these // values decode as Go int instances instead: @@ -214,7 +214,7 @@ func (r *Registry) RegisterInterfaceDecoder(iface reflect.Type, dec ValueDecoder // mapping is decoding situations where an empty interface is used and a default type needs to be // created and decoded into. // -// By default, BSON documents will decode into any values as bson.D. To change the default type for BSON +// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON // documents, a type map entry for TypeEmbeddedDocument should be registered. For example, to force BSON documents // to decode to bson.Raw, use the following code: // diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go deleted file mode 100644 index c9366e9f..00000000 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2025-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 ( - "bufio" - "io" -) - -// streamingByteSrc reads from an ioReader wrapped in a bufio.Reader. It -// first reads the BSON length header, then ensures it only ever reads exactly -// that many bytes. -// -// Note: this approach trades memory usage for extra buffering and reader calls, -// so it is less performanted than the in-memory bufferedValueReader. -type streamingByteSrc struct { - br *bufio.Reader - offset int64 // offset is the current read position in the buffer -} - -var _ byteSrc = (*streamingByteSrc)(nil) - -// Read reads up to len(p) bytes from the underlying bufio.Reader, advancing -// the offset by the number of bytes read. -func (s *streamingByteSrc) readExact(p []byte) (int, error) { - n, err := io.ReadFull(s.br, p) - if err == nil { - s.offset += int64(n) - } - - return n, err -} - -// ReadByte returns the single byte at buf[offset] and advances offset by 1. -func (s *streamingByteSrc) ReadByte() (byte, error) { - c, err := s.br.ReadByte() - if err == nil { - s.offset++ - } - return c, err -} - -// peek returns buf[offset:offset+n] without advancing offset. -func (s *streamingByteSrc) peek(n int) ([]byte, error) { - return s.br.Peek(n) -} - -// discard advances offset by n bytes, returning the number of bytes discarded. -func (s *streamingByteSrc) discard(n int) (int, error) { - m, err := s.br.Discard(n) - s.offset += int64(m) - return m, err -} - -// readSlice scans buf[offset:] for the first occurrence of delim, returns -// buf[offset:idx+1], and advances offset past it; errors if delim not found. -func (s *streamingByteSrc) readSlice(delim byte) ([]byte, error) { - data, err := s.br.ReadSlice(delim) - if err != nil { - return nil, err - } - s.offset += int64(len(data)) - return data, nil -} - -// pos returns the current read position in the buffer. -func (s *streamingByteSrc) pos() int64 { - return s.offset -} - -// regexLength will return the total byte length of a BSON regex value. -func (s *streamingByteSrc) regexLength() (int32, error) { - var ( - count int32 - nulCount int - ) - - for nulCount < 2 { - buf, err := s.br.Peek(int(count) + 1) - if err != nil { - return 0, err - } - - b := buf[count] - count++ - if b == 0x00 { - nulCount++ - } - } - - return count, nil -} - -func (*streamingByteSrc) streamable() bool { - return true -} - -func (s *streamingByteSrc) reset() { - s.offset = 0 -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go index 83b63f5f..b3f160c8 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go @@ -118,10 +118,6 @@ func (sc *structCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect } } - if ec.omitEmpty { - desc.omitEmpty = true - } - desc.encoder, rv, err = lookupElementEncoder(ec, desc.encoder, rv) if err != nil && !errors.Is(err, errInvalidValue) { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go index d11cb2aa..c2883aa4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go @@ -83,7 +83,7 @@ var tInt64 = reflect.TypeOf(int64(0)) var tString = reflect.TypeOf("") var tTime = reflect.TypeOf(time.Time{}) -var tEmpty = reflect.TypeOf((*any)(nil)).Elem() +var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem() var tByteSlice = reflect.TypeOf([]byte(nil)) var tByte = reflect.TypeOf(byte(0x00)) var tURL = reflect.TypeOf(url.URL{}) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go index 4377c4e4..72870c10 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go @@ -41,10 +41,8 @@ type ValueUnmarshaler interface { // // When unmarshaling BSON, if the BSON value is null and the Go value is a // pointer, the pointer is set to nil without calling UnmarshalBSONValue. -func Unmarshal(data []byte, val any) error { - vr := getBufferedDocumentReader(data) - defer putBufferedDocumentReader(vr) - +func Unmarshal(data []byte, val interface{}) error { + vr := newDocumentReader(bytes.NewReader(data)) if l, err := vr.peekLength(); err != nil { return err } else if int(l) != len(data) { @@ -56,8 +54,8 @@ func Unmarshal(data []byte, val any) error { // UnmarshalValue parses the BSON value of type t with bson.NewRegistry() and // stores the result in the value pointed to by val. If val is nil or not a pointer, // UnmarshalValue returns an error. -func UnmarshalValue(t Type, data []byte, val any) error { - vr := newBufferedValueReader(t, data) +func UnmarshalValue(t Type, data []byte, val interface{}) error { + vr := newValueReader(t, bytes.NewReader(data)) return unmarshalFromReader(DecodeContext{Registry: defaultRegistry}, vr, val) } @@ -70,7 +68,7 @@ func UnmarshalValue(t Type, data []byte, val any) error { // // For more information about Extended JSON, see // https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/ -func UnmarshalExtJSON(data []byte, canonicalOnly bool, val any) error { +func UnmarshalExtJSON(data []byte, canonicalOnly bool, val interface{}) error { ejvr, err := NewExtJSONValueReader(bytes.NewReader(data), canonicalOnly) if err != nil { return err @@ -79,7 +77,7 @@ func UnmarshalExtJSON(data []byte, canonicalOnly bool, val any) error { return unmarshalFromReader(DecodeContext{Registry: defaultRegistry}, ejvr, val) } -func unmarshalFromReader(dc DecodeContext, vr ValueReader, val any) error { +func unmarshalFromReader(dc DecodeContext, vr ValueReader, val interface{}) error { dec := decPool.Get().(*Decoder) defer decPool.Put(dec) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go index e5bcc198..678c47b1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go @@ -13,41 +13,8 @@ import ( "fmt" "io" "math" - "sync" ) -type byteSrc interface { - io.ByteReader - - readExact(p []byte) (int, error) - - // Peek returns the next n bytes without advancing the cursor. It must return - // exactly n bytes or n error if fewer are available. - peek(n int) ([]byte, error) - - // discard advanced the cursor by n bytes, returning the actual number - // discarded or an error if fewer were available. - discard(n int) (int, error) - - // readSlice reads until (and including) the first occurrence of delim, - // returning the entire slice [start...delimiter] and advancing the cursor. - // past it. Returns an error if delim is not found. - readSlice(delim byte) ([]byte, error) - - // pos returns the number of bytes consumed so far. - pos() int64 - - // regexLength returns the total byte length of a BSON regex value (two - // C-strings including their terminating NULs) in buffered mode. - regexLength() (int32, error) - - // streamable returns true if this source can be used in a streaming context. - streamable() bool - - // reset resets the source to its initial state. - reset() -} - var _ ValueReader = &valueReader{} // ErrEOA is the error returned when the end of a BSON array has been reached. @@ -62,92 +29,44 @@ type vrState struct { end int64 } -var vrPool = sync.Pool{ - New: func() any { - return &valueReader{ - stack: make([]vrState, 1, 5), - } - }, -} - // valueReader is for reading BSON values. type valueReader struct { - src byteSrc + r *bufio.Reader offset int64 stack []vrState frame int64 } -func getBufferedDocumentReader(b []byte) *valueReader { - return newBufferedDocumentReader(b) +// NewDocumentReader returns a ValueReader using b for the underlying BSON +// representation. +func NewDocumentReader(r io.Reader) ValueReader { + return newDocumentReader(r) } -func putBufferedDocumentReader(vr *valueReader) { - if vr == nil { - return +// newValueReader returns a ValueReader that starts in the Value mode instead of in top +// level document mode. This enables the creation of a ValueReader for a single BSON value. +func newValueReader(t Type, r io.Reader) ValueReader { + vr := newDocumentReader(r) + if len(vr.stack) == 0 { + vr.stack = make([]vrState, 1, 5) } - - vr.src.reset() - - // Reset src and stack to avoid holding onto memory. - vr.src = nil - vr.frame = 0 - vr.stack = vr.stack[:0] - - vrPool.Put(vr) + vr.stack[0].mode = mValue + vr.stack[0].vType = t + return vr } -// NewDocumentReader returns a ValueReader using b for the underlying BSON -// representation. -func NewDocumentReader(r io.Reader) ValueReader { +func newDocumentReader(r io.Reader) *valueReader { stack := make([]vrState, 1, 5) stack[0] = vrState{ mode: mTopLevel, } - return &valueReader{ - src: &streamingByteSrc{br: bufio.NewReader(r), offset: 0}, + r: bufio.NewReader(r), stack: stack, } } -// newBufferedValueReader returns a ValueReader that starts in the Value mode -// instead of in top level document mode. This enables the creation of a -// ValueReader for a single BSON value. -func newBufferedValueReader(t Type, b []byte) ValueReader { - bVR := newBufferedDocumentReader(b) - - bVR.stack[0].vType = t - bVR.stack[0].mode = mValue - - return bVR -} - -func newBufferedDocumentReader(b []byte) *valueReader { - vr := vrPool.Get().(*valueReader) - - vr.src = &bufferedByteSrc{ - buf: b, - offset: 0, - } - - // Reset parse state. - vr.frame = 0 - if cap(vr.stack) < 1 { - vr.stack = make([]vrState, 1, 5) - } else { - vr.stack = vr.stack[:1] - } - - vr.stack[0] = vrState{ - mode: mTopLevel, - end: int64(len(b)), - } - - return vr -} - func (vr *valueReader) advanceFrame() { if vr.frame+1 >= int64(len(vr.stack)) { // We need to grow the stack length := len(vr.stack) @@ -167,6 +86,62 @@ func (vr *valueReader) advanceFrame() { vr.stack[vr.frame].end = 0 } +func (vr *valueReader) pushDocument() error { + vr.advanceFrame() + + vr.stack[vr.frame].mode = mDocument + + length, err := vr.readLength() + if err != nil { + return err + } + vr.stack[vr.frame].end = int64(length) + vr.offset - 4 + + return nil +} + +func (vr *valueReader) pushArray() error { + vr.advanceFrame() + + vr.stack[vr.frame].mode = mArray + + length, err := vr.readLength() + if err != nil { + return err + } + vr.stack[vr.frame].end = int64(length) + vr.offset - 4 + + return nil +} + +func (vr *valueReader) pushElement(t Type) { + vr.advanceFrame() + + vr.stack[vr.frame].mode = mElement + vr.stack[vr.frame].vType = t +} + +func (vr *valueReader) pushValue(t Type) { + vr.advanceFrame() + + vr.stack[vr.frame].mode = mValue + vr.stack[vr.frame].vType = t +} + +func (vr *valueReader) pushCodeWithScope() (int64, error) { + vr.advanceFrame() + + vr.stack[vr.frame].mode = mCodeWithScope + + length, err := vr.readLength() + if err != nil { + return 0, err + } + vr.stack[vr.frame].end = int64(length) + vr.offset - 4 + + return int64(length), nil +} + func (vr *valueReader) pop() error { var cnt int switch vr.stack[vr.frame].mode { @@ -176,27 +151,22 @@ func (vr *valueReader) pop() error { cnt = 2 // we pop twice to jump over the vrElement: vrDocument -> vrElement -> vrDocument/TopLevel/etc... } for i := 0; i < cnt && vr.frame > 0; i++ { - if vr.src.pos() < vr.stack[vr.frame].end { - _, err := vr.src.discard(int(vr.stack[vr.frame].end - vr.src.pos())) + if vr.offset < vr.stack[vr.frame].end { + _, err := vr.r.Discard(int(vr.stack[vr.frame].end - vr.offset)) if err != nil { return err } } vr.frame-- } - - if vr.src.streamable() { - if vr.frame == 0 { - if vr.stack[0].end > vr.src.pos() { - vr.stack[0].end -= vr.src.pos() - } else { - vr.stack[0].end = 0 - } - - vr.src.reset() + if vr.frame == 0 { + if vr.stack[0].end > vr.offset { + vr.stack[0].end -= vr.offset + } else { + vr.stack[0].end = 0 } + vr.offset = 0 } - return nil } @@ -239,9 +209,7 @@ func (vr *valueReader) Type() Type { return vr.stack[vr.frame].vType } -// peekNextValueSize returns the length of the next value in the stream without -// offsetting the reader position. -func peekNextValueSize(vr *valueReader) (int32, error) { +func (vr *valueReader) appendNextElement(dst []byte) ([]byte, error) { var length int32 var err error switch vr.stack[vr.frame].vType { @@ -269,73 +237,58 @@ func peekNextValueSize(vr *valueReader) (int32, error) { case TypeObjectID: length = 12 case TypeRegex: - length, err = vr.src.regexLength() - default: - return 0, fmt.Errorf("attempted to read bytes of unknown BSON type %v", vr.stack[vr.frame].vType) - } - - return length, err -} - -// readBytes tries to grab the next n bytes zero-allocation using peek+discard. -// If peek fails (e.g. bufio buffer full), it falls back to io.ReadFull. -func readBytes(src byteSrc, n int) ([]byte, error) { - if src.streamable() { - data := make([]byte, n) - if _, err := src.readExact(data); err != nil { - return nil, err + for n := 0; n < 2; n++ { // Read two C strings. + str, err := vr.r.ReadBytes(0x00) + if err != nil { + return nil, err + } + dst = append(dst, str...) + vr.offset += int64(len(str)) } - - return data, nil + return dst, nil + default: + return nil, fmt.Errorf("attempted to read bytes of unknown BSON type %v", vr.stack[vr.frame].vType) } - - // Zero-allocation path. - buf, err := src.peek(n) if err != nil { return nil, err } - _, _ = src.discard(n) // Discard the bytes from the source. - return buf, nil -} - -// readBytesValueReader returns a subslice [offset, offset+length) or EOF. -func (vr *valueReader) readBytes(n int32) ([]byte, error) { - if n < 0 { - return nil, fmt.Errorf("invalid length: %d", n) + buf := make([]byte, length) + _, err = io.ReadFull(vr.r, buf) + if err != nil { + return nil, err } - - return readBytes(vr.src, int(n)) + dst = append(dst, buf...) + vr.offset += int64(len(buf)) + return dst, err } -//nolint:unparam func (vr *valueReader) readValueBytes(dst []byte) (Type, []byte, error) { switch vr.stack[vr.frame].mode { case mTopLevel: length, err := vr.peekLength() if err != nil { - return 0, nil, err + return Type(0), nil, err + } + dst, err = vr.appendBytes(dst, length) + if err != nil { + return Type(0), nil, err } - b, err := vr.readBytes(length) - return Type(0), append(dst, b...), err + return Type(0), dst, nil case mElement, mValue: - t := vr.stack[vr.frame].vType - - length, err := peekNextValueSize(vr) + dst, err := vr.appendNextElement(dst) if err != nil { - return t, dst, err + return Type(0), dst, err } - b, err := vr.readBytes(length) - - if err := vr.pop(); err != nil { + t := vr.stack[vr.frame].vType + err = vr.pop() + if err != nil { return Type(0), nil, err } - - return t, append(dst, b...), err - + return t, dst, nil default: - return Type(0), nil, vr.invalidTransitionErr(0, "readValueBytes", []mode{mElement, mValue}) + return Type(0), nil, vr.invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue}) } } @@ -346,12 +299,7 @@ func (vr *valueReader) Skip() error { return vr.invalidTransitionErr(0, "Skip", []mode{mElement, mValue}) } - length, err := peekNextValueSize(vr) - if err != nil { - return err - } - - _, err = vr.src.discard(int(length)) + _, err := vr.appendNextElement(nil) if err != nil { return err } @@ -359,33 +307,20 @@ func (vr *valueReader) Skip() error { return vr.pop() } -// ReadArray returns an ArrayReader for the next BSON array in the valueReader -// source, advancing the reader position to the end of the array. func (vr *valueReader) ReadArray() (ArrayReader, error) { if err := vr.ensureElementValue(TypeArray, mArray, "ReadArray"); err != nil { return nil, err } - // Push a new frame for the array. - vr.advanceFrame() - - // Read the 4-byte length. - size, err := vr.readLength() + err := vr.pushArray() if err != nil { return nil, err } - // Compute the end position: current position + total size - length. - vr.stack[vr.frame].mode = mArray - vr.stack[vr.frame].end = vr.src.pos() + int64(size) - 4 - return vr, nil } -// ReadBinary reads a BSON binary value, returning the byte slice and the -// type of the binary data (0x02 for old binary, 0x00 for new binary, etc.), -// advancing the reader position to the end of the binary value. -func (vr *valueReader) ReadBinary() ([]byte, byte, error) { +func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { if err := vr.ensureElementValue(TypeBinary, 0, "ReadBinary"); err != nil { return nil, 0, err } @@ -395,7 +330,7 @@ func (vr *valueReader) ReadBinary() ([]byte, byte, error) { return nil, 0, err } - btype, err := vr.readByte() + btype, err = vr.readByte() if err != nil { return nil, 0, err } @@ -408,24 +343,18 @@ func (vr *valueReader) ReadBinary() ([]byte, byte, error) { } } - b, err := vr.readBytes(length) + b = make([]byte, length) + err = vr.read(b) if err != nil { return nil, 0, err } - // copy so user doesn’t share underlying buffer - cp := make([]byte, len(b)) - copy(cp, b) - if err := vr.pop(); err != nil { return nil, 0, err } - - return cp, btype, nil + return b, btype, nil } -// ReadBoolean reads a BSON boolean value, returning true or false, advancing -// the reader position to the end of the boolean value. func (vr *valueReader) ReadBoolean() (bool, error) { if err := vr.ensureElementValue(TypeBoolean, 0, "ReadBoolean"); err != nil { return false, err @@ -446,8 +375,6 @@ func (vr *valueReader) ReadBoolean() (bool, error) { return b == 1, nil } -// ReadDocument reads a BSON embedded document, returning a DocumentReader, -// advancing the reader position to the end of the document. func (vr *valueReader) ReadDocument() (DocumentReader, error) { switch vr.stack[vr.frame].mode { case mTopLevel: @@ -459,7 +386,7 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { return nil, fmt.Errorf("invalid string length: %d", length) } - vr.stack[vr.frame].end = int64(length) + vr.src.pos() - 4 + vr.stack[vr.frame].end = int64(length) + vr.offset - 4 return vr, nil case mElement, mValue: if vr.stack[vr.frame].vType != TypeEmbeddedDocument { @@ -469,22 +396,15 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { return nil, vr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue}) } - vr.advanceFrame() - - size, err := vr.readLength() + err := vr.pushDocument() if err != nil { return nil, err } - vr.stack[vr.frame].mode = mDocument - vr.stack[vr.frame].end = int64(size) + vr.src.pos() - 4 - return vr, nil } -// ReadCodeWithScope reads a BSON CodeWithScope value, returning the code as a -// string, advancing the reader position to the end of the CodeWithScope value. -func (vr *valueReader) ReadCodeWithScope() (string, DocumentReader, error) { +func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) { if err := vr.ensureElementValue(TypeCodeWithScope, 0, "ReadCodeWithScope"); err != nil { return "", nil, err } @@ -500,26 +420,21 @@ func (vr *valueReader) ReadCodeWithScope() (string, DocumentReader, error) { if strLength <= 0 { return "", nil, fmt.Errorf("invalid string length: %d", strLength) } - buf, err := vr.readBytes(strLength) + strBytes := make([]byte, strLength) + err = vr.read(strBytes) if err != nil { return "", nil, err } + code = string(strBytes[:len(strBytes)-1]) - code := string(buf[:len(buf)-1]) - vr.advanceFrame() - - // Use readLength to ensure that we are not out of bounds. - size, err := vr.readLength() + size, err := vr.pushCodeWithScope() if err != nil { return "", nil, err } - vr.stack[vr.frame].mode = mCodeWithScope - vr.stack[vr.frame].end = vr.src.pos() + int64(size) - 4 - // The total length should equal: // 4 (total length) + strLength + 4 (the length of str itself) + (document length) - componentsLength := int64(4+strLength+4) + int64(size) + componentsLength := int64(4+strLength+4) + size if int64(totalLength) != componentsLength { return "", nil, fmt.Errorf( "length of CodeWithScope does not match lengths of components; total: %d; components: %d", @@ -529,34 +444,27 @@ func (vr *valueReader) ReadCodeWithScope() (string, DocumentReader, error) { return code, vr, nil } -// ReadDBPointer reads a BSON DBPointer value, returning the namespace, the -// object ID, and an error if any, advancing the reader position to the end of -// the DBPointer value. -func (vr *valueReader) ReadDBPointer() (string, ObjectID, error) { +func (vr *valueReader) ReadDBPointer() (ns string, oid ObjectID, err error) { if err := vr.ensureElementValue(TypeDBPointer, 0, "ReadDBPointer"); err != nil { - return "", ObjectID{}, err + return "", oid, err } - ns, err := vr.readString() + + ns, err = vr.readString() if err != nil { - return "", ObjectID{}, err + return "", oid, err } - oidBytes, err := vr.readBytes(12) + err = vr.read(oid[:]) if err != nil { return "", ObjectID{}, err } - var oid ObjectID - copy(oid[:], oidBytes) - if err := vr.pop(); err != nil { return "", ObjectID{}, err } return ns, oid, nil } -// ReadDateTime reads a BSON DateTime value, advancing the reader position to -// the end of the DateTime value. func (vr *valueReader) ReadDateTime() (int64, error) { if err := vr.ensureElementValue(TypeDateTime, 0, "ReadDateTime"); err != nil { return 0, err @@ -573,16 +481,17 @@ func (vr *valueReader) ReadDateTime() (int64, error) { return i, nil } -// ReadDecimal128 reads a BSON Decimal128 value, advancing the reader -// to the end of the Decimal128 value. func (vr *valueReader) ReadDecimal128() (Decimal128, error) { if err := vr.ensureElementValue(TypeDecimal128, 0, "ReadDecimal128"); err != nil { return Decimal128{}, err } - b, err := vr.readBytes(16) + + var b [16]byte + err := vr.read(b[:]) if err != nil { return Decimal128{}, err } + l := binary.LittleEndian.Uint64(b[0:8]) h := binary.LittleEndian.Uint64(b[8:16]) @@ -592,8 +501,6 @@ func (vr *valueReader) ReadDecimal128() (Decimal128, error) { return NewDecimal128(h, l), nil } -// ReadDouble reads a BSON double value, advancing the reader position to -// to the end of the double value. func (vr *valueReader) ReadDouble() (float64, error) { if err := vr.ensureElementValue(TypeDouble, 0, "ReadDouble"); err != nil { return 0, err @@ -610,59 +517,39 @@ func (vr *valueReader) ReadDouble() (float64, error) { return math.Float64frombits(u), nil } -// ReadInt32 reads a BSON int32 value, advancing the reader position to the end -// of the int32 value. func (vr *valueReader) ReadInt32() (int32, error) { if err := vr.ensureElementValue(TypeInt32, 0, "ReadInt32"); err != nil { return 0, err } - i, err := vr.readi32() - if err != nil { - return 0, err - } if err := vr.pop(); err != nil { return 0, err } - return i, nil + return vr.readi32() } -// ReadInt64 reads a BSON int64 value, advancing the reader position to the end -// of the int64 value. func (vr *valueReader) ReadInt64() (int64, error) { if err := vr.ensureElementValue(TypeInt64, 0, "ReadInt64"); err != nil { return 0, err } - i, err := vr.readi64() - if err != nil { - return 0, err - } if err := vr.pop(); err != nil { return 0, err } - return i, nil + return vr.readi64() } -// ReadJavascript reads a BSON JavaScript value, advancing the reader -// to the end of the JavaScript value. func (vr *valueReader) ReadJavascript() (string, error) { if err := vr.ensureElementValue(TypeJavaScript, 0, "ReadJavascript"); err != nil { return "", err } - s, err := vr.readString() - if err != nil { - return "", err - } if err := vr.pop(); err != nil { return "", err } - return s, nil + return vr.readString() } -// ReadMaxKey reads a BSON MaxKey value, advancing the reader position to the -// end of the MaxKey value. func (vr *valueReader) ReadMaxKey() error { if err := vr.ensureElementValue(TypeMaxKey, 0, "ReadMaxKey"); err != nil { return err @@ -671,8 +558,6 @@ func (vr *valueReader) ReadMaxKey() error { return vr.pop() } -// ReadMinKey reads a BSON MinKey value, advancing the reader position to the -// end of the MinKey value. func (vr *valueReader) ReadMinKey() error { if err := vr.ensureElementValue(TypeMinKey, 0, "ReadMinKey"); err != nil { return err @@ -681,8 +566,6 @@ func (vr *valueReader) ReadMinKey() error { return vr.pop() } -// REadNull reads a BSON Null value, advancing the reader position to the -// end of the Null value. func (vr *valueReader) ReadNull() error { if err := vr.ensureElementValue(TypeNull, 0, "ReadNull"); err != nil { return err @@ -691,29 +574,23 @@ func (vr *valueReader) ReadNull() error { return vr.pop() } -// ReadObjectID reads a BSON ObjectID value, advancing the reader to the end of -// the ObjectID value. func (vr *valueReader) ReadObjectID() (ObjectID, error) { if err := vr.ensureElementValue(TypeObjectID, 0, "ReadObjectID"); err != nil { return ObjectID{}, err } - oidBytes, err := vr.readBytes(12) + var oid ObjectID + err := vr.read(oid[:]) if err != nil { return ObjectID{}, err } - var oid ObjectID - copy(oid[:], oidBytes) - if err := vr.pop(); err != nil { return ObjectID{}, err } return oid, nil } -// ReadRegex reads a BSON Regex value, advancing the reader position to the -// regex value. func (vr *valueReader) ReadRegex() (string, string, error) { if err := vr.ensureElementValue(TypeRegex, 0, "ReadRegex"); err != nil { return "", "", err @@ -735,52 +612,39 @@ func (vr *valueReader) ReadRegex() (string, string, error) { return pattern, options, nil } -// ReadString reads a BSON String value, advancing the reader position to the -// end of the String value. func (vr *valueReader) ReadString() (string, error) { if err := vr.ensureElementValue(TypeString, 0, "ReadString"); err != nil { return "", err } - s, err := vr.readString() - if err != nil { - return "", err - } if err := vr.pop(); err != nil { return "", err } - return s, nil + return vr.readString() } -// ReadSymbol reads a BSON Symbol value, advancing the reader position to the -// end of the Symbol value. func (vr *valueReader) ReadSymbol() (string, error) { if err := vr.ensureElementValue(TypeSymbol, 0, "ReadSymbol"); err != nil { return "", err } - s, err := vr.readString() - if err != nil { - return "", err - } + if err := vr.pop(); err != nil { return "", err } - return s, nil + return vr.readString() } -// ReadTimestamp reads a BSON Timestamp value, advancing the reader to the end -// of the Timestamp value. -func (vr *valueReader) ReadTimestamp() (uint32, uint32, error) { +func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { if err := vr.ensureElementValue(TypeTimestamp, 0, "ReadTimestamp"); err != nil { return 0, 0, err } - i, err := vr.readu32() + i, err = vr.readu32() if err != nil { return 0, 0, err } - t, err := vr.readu32() + t, err = vr.readu32() if err != nil { return 0, 0, err } @@ -791,8 +655,6 @@ func (vr *valueReader) ReadTimestamp() (uint32, uint32, error) { return t, i, nil } -// ReadUndefined reads a BSON Undefined value, advancing the reader position -// to the end of the Undefined value. func (vr *valueReader) ReadUndefined() error { if err := vr.ensureElementValue(TypeUndefined, 0, "ReadUndefined"); err != nil { return err @@ -801,8 +663,6 @@ func (vr *valueReader) ReadUndefined() error { return vr.pop() } -// ReadElement reads the next element in the BSON document, advancing the -// reader position to the end of the element. func (vr *valueReader) ReadElement() (string, ValueReader, error) { switch vr.stack[vr.frame].mode { case mTopLevel, mDocument, mCodeWithScope: @@ -816,7 +676,7 @@ func (vr *valueReader) ReadElement() (string, ValueReader, error) { } if t == 0 { - if vr.src.pos() != vr.stack[vr.frame].end { + if vr.offset != vr.stack[vr.frame].end { return "", nil, vr.invalidDocumentLengthError() } @@ -829,15 +689,10 @@ func (vr *valueReader) ReadElement() (string, ValueReader, error) { return "", nil, err } - vr.advanceFrame() - - vr.stack[vr.frame].mode = mElement - vr.stack[vr.frame].vType = Type(t) + vr.pushElement(Type(t)) return name, vr, nil } -// ReadValue reads the next value in the BSON array, advancing the to the end of -// the value. func (vr *valueReader) ReadValue() (ValueReader, error) { switch vr.stack[vr.frame].mode { case mArray: @@ -851,7 +706,7 @@ func (vr *valueReader) ReadValue() (ValueReader, error) { } if t == 0 { - if vr.src.pos() != vr.stack[vr.frame].end { + if vr.offset != vr.stack[vr.frame].end { return nil, vr.invalidDocumentLengthError() } @@ -859,32 +714,49 @@ func (vr *valueReader) ReadValue() (ValueReader, error) { return nil, ErrEOA } - _, err = vr.src.readSlice(0x00) - if err != nil { + if _, err := vr.readCString(); err != nil { return nil, err } - vr.advanceFrame() - - vr.stack[vr.frame].mode = mValue - vr.stack[vr.frame].vType = Type(t) + vr.pushValue(Type(t)) return vr, nil } +func (vr *valueReader) read(p []byte) error { + n, err := io.ReadFull(vr.r, p) + if err != nil { + return err + } + vr.offset += int64(n) + return nil +} + +func (vr *valueReader) appendBytes(dst []byte, length int32) ([]byte, error) { + buf := make([]byte, length) + err := vr.read(buf) + if err != nil { + return nil, err + } + return append(dst, buf...), nil +} + func (vr *valueReader) readByte() (byte, error) { - b, err := vr.src.ReadByte() + b, err := vr.r.ReadByte() if err != nil { return 0x0, err } + vr.offset++ return b, nil } func (vr *valueReader) readCString() (string, error) { - data, err := vr.src.readSlice(0x00) + str, err := vr.r.ReadString(0x00) if err != nil { return "", err } - return string(data[:len(data)-1]), nil + l := len(str) + vr.offset += int64(l) + return str[:l-1], nil } func (vr *valueReader) readString() (string, error) { @@ -892,69 +764,79 @@ func (vr *valueReader) readString() (string, error) { if err != nil { return "", err } - if length <= 0 { return "", fmt.Errorf("invalid string length: %d", length) } - raw, err := readBytes(vr.src, int(length)) + buf := make([]byte, length) + err = vr.read(buf) if err != nil { return "", err } - // Check that the last byte is the NUL terminator. - if raw[len(raw)-1] != 0x00 { - return "", fmt.Errorf("string does not end with null byte, but with %v", raw[len(raw)-1]) + if buf[length-1] != 0x00 { + return "", fmt.Errorf("string does not end with null byte, but with %v", buf[length-1]) } - // Convert and strip the trailing NUL. - return string(raw[:len(raw)-1]), nil + return string(buf[:length-1]), nil } func (vr *valueReader) peekLength() (int32, error) { - buf, err := vr.src.peek(4) + buf, err := vr.r.Peek(4) if err != nil { return 0, err } + return int32(binary.LittleEndian.Uint32(buf)), nil } func (vr *valueReader) readLength() (int32, error) { - return vr.readi32() + l, err := vr.readi32() + if err != nil { + return 0, err + } + if l < 0 { + return 0, fmt.Errorf("invalid negative length: %d", l) + } + return l, nil } func (vr *valueReader) readi32() (int32, error) { - raw, err := readBytes(vr.src, 4) + var buf [4]byte + err := vr.read(buf[:]) if err != nil { return 0, err } - return int32(binary.LittleEndian.Uint32(raw)), nil + return int32(binary.LittleEndian.Uint32(buf[:])), nil } func (vr *valueReader) readu32() (uint32, error) { - raw, err := readBytes(vr.src, 4) + var buf [4]byte + err := vr.read(buf[:]) if err != nil { return 0, err } - return binary.LittleEndian.Uint32(raw), nil + return binary.LittleEndian.Uint32(buf[:]), nil } func (vr *valueReader) readi64() (int64, error) { - raw, err := readBytes(vr.src, 8) + var buf [8]byte + err := vr.read(buf[:]) if err != nil { return 0, err } - return int64(binary.LittleEndian.Uint64(raw)), nil + return int64(binary.LittleEndian.Uint64(buf[:])), nil } func (vr *valueReader) readu64() (uint64, error) { - raw, err := readBytes(vr.src, 8) + var buf [8]byte + err := vr.read(buf[:]) if err != nil { return 0, err } - return binary.LittleEndian.Uint64(raw), nil + return binary.LittleEndian.Uint64(buf[:]), nil } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go index 9dd8912d..57334a92 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go @@ -21,7 +21,7 @@ import ( var _ ValueWriter = &valueWriter{} var vwPool = sync.Pool{ - New: func() any { + New: func() interface{} { return new(valueWriter) }, } @@ -33,29 +33,6 @@ func putValueWriter(vw *valueWriter) { } } -var documentWriterPool = sync.Pool{ - New: func() any { - return newDocumentWriter(nil) - }, -} - -func getDocumentWriter(w io.Writer) *valueWriter { - vw := documentWriterPool.Get().(*valueWriter) - - vw.reset(vw.buf) - vw.buf = vw.buf[:0] - vw.w = w - - return vw -} - -func putDocumentWriter(vw *valueWriter) { - if vw != nil { - vw.w = nil // don't leak the writer - documentWriterPool.Put(vw) - } -} - // This is here so that during testing we can change it and not require // allocating a 4GB slice. var maxSize = math.MaxInt32 diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go index 7acdb2f1..ff0f6493 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go @@ -8,7 +8,7 @@ package bsoncoreutil // Truncate truncates a given string for a certain width func Truncate(str string, width int) string { - if width <= 0 { + if width == 0 { return "" } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go index 4af8284e..1eba9c24 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go @@ -52,9 +52,9 @@ func RawArrayToDocuments(arr bson.RawArray) []bson.Raw { return out } -// RawToInterfaces takes one or many bson.Raw documents and returns them as a []any. -func RawToInterfaces(docs ...bson.Raw) []any { - out := make([]any, len(docs)) +// RawToInterfaces takes one or many bson.Raw documents and returns them as a []interface{}. +func RawToInterfaces(docs ...bson.Raw) []interface{} { + out := make([]interface{}, len(docs)) for i := range docs { out[i] = docs[i] } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go index 11a74312..aafb1e99 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go @@ -22,24 +22,22 @@ var ErrNilValue = errors.New("value is nil") // MarshalError is returned when attempting to transform a value into a document // results in an error. type MarshalError struct { - Value any + Value interface{} Err error } // Error implements the error interface. func (e MarshalError) Error() string { - return fmt.Sprintf("cannot marshal type %q to a BSON Document: %v", + return fmt.Sprintf("cannot transform type %s to a BSON Document: %v", reflect.TypeOf(e.Value), e.Err) } -func (e MarshalError) Unwrap() error { return e.Err } - // EncoderFn is used to functionally construct an encoder for marshaling values. type EncoderFn func(io.Writer) *bson.Encoder // MarshalValue will attempt to encode the value with the encoder returned by // the encoder function. -func MarshalValue(val any, encFn EncoderFn) (bsoncore.Value, error) { +func MarshalValue(val interface{}, encFn EncoderFn) (bsoncore.Value, error) { // If the val is already a bsoncore.Value, then do nothing. if bval, ok := val.(bsoncore.Value); ok { return bval, nil diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go index 89963799..df3adc36 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go @@ -21,7 +21,7 @@ import ( ) const ( - MinWireVersion = 7 + MinWireVersion = 6 MaxWireVersion = 25 ) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go index 74142a56..e37cba59 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go @@ -6,12 +6,6 @@ package driverutil -import ( - "context" - "math" - "time" -) - // Operation Names should be sourced from the command reference documentation: // https://www.mongodb.com/docs/manual/reference/command/ const ( @@ -36,34 +30,3 @@ const ( UpdateOp = "update" // UpdateOp is the name for updating BulkWriteOp = "bulkWrite" // BulkWriteOp is the name for client-level bulk write ) - -// CalculateMaxTimeMS calculates the maxTimeMS value to send to the server -// based on the context deadline and the minimum round trip time. If the -// calculated maxTimeMS is likely to cause a socket timeout, then this function -// will return 0 and false. -func CalculateMaxTimeMS(ctx context.Context, rttMin time.Duration) (int64, bool) { - deadline, ok := ctx.Deadline() - if !ok { - return 0, true - } - - remainingTimeout := time.Until(deadline) - - // Always round up to the next millisecond value so we never truncate the calculated - // maxTimeMS value (e.g. 400 microseconds evaluates to 1ms, not 0ms). - maxTimeMS := int64((remainingTimeout - rttMin + time.Millisecond - 1) / time.Millisecond) - if maxTimeMS <= 0 { - return 0, false - } - - // The server will return a "BadValue" error if maxTimeMS is greater - // than the maximum positive int32 value (about 24.9 days). If the - // user specified a timeout value greater than that, omit maxTimeMS - // and let the client-side timeout handle cancelling the op if the - // timeout is ever reached. - if maxTimeMS > math.MaxInt32 { - return 0, true - } - - return maxTimeMS, true -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go index 761ad14d..db0dd5f1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go @@ -10,17 +10,9 @@ import ( "net/http" ) -var DefaultHTTPClient = &http.Client{} - -// NewHTTPClient will return the globally-defined DefaultHTTPClient, updating -// the transport if it differs from the http package DefaultTransport. -func NewHTTPClient() *http.Client { - client := DefaultHTTPClient - if _, ok := http.DefaultTransport.(*http.Transport); !ok { - client.Transport = http.DefaultTransport - } - - return client +// DefaultHTTPClient is the default HTTP client used across the driver. +var DefaultHTTPClient = &http.Client{ + Transport: http.DefaultTransport.(*http.Transport).Clone(), } // CloseIdleHTTPConnections closes any connections which were previously diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go index ef6649ec..a601707c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go @@ -75,10 +75,10 @@ const ( ) // KeyValues is a list of key-value pairs. -type KeyValues []any +type KeyValues []interface{} // Add adds a key-value pair to an instance of a KeyValues list. -func (kvs *KeyValues) Add(key string, value any) { +func (kvs *KeyValues) Add(key string, value interface{}) { *kvs = append(*kvs, key, value) } @@ -157,9 +157,9 @@ type Command struct { } // SerializeCommand takes a command and a variable number of key-value pairs and -// returns a slice of any that can be passed to the logger for +// returns a slice of interface{} that can be passed to the logger for // structured logging. -func SerializeCommand(cmd Command, extraKeysAndValues ...any) KeyValues { +func SerializeCommand(cmd Command, extraKeysAndValues ...interface{}) KeyValues { // Initialize the boilerplate keys and values. keysAndValues := KeyValues{ KeyCommandName, cmd.Name, @@ -203,7 +203,7 @@ type Connection struct { // SerializeConnection serializes a Connection message into a slice of keys and // values that can be passed to a logger. -func SerializeConnection(conn Connection, extraKeysAndValues ...any) KeyValues { +func SerializeConnection(conn Connection, extraKeysAndValues ...interface{}) KeyValues { // Initialize the boilerplate keys and values. keysAndValues := KeyValues{ KeyMessage, conn.Message, @@ -235,7 +235,7 @@ type Server struct { // SerializeServer serializes a Server message into a slice of keys and // values that can be passed to a logger. -func SerializeServer(srv Server, extraKV ...any) KeyValues { +func SerializeServer(srv Server, extraKV ...interface{}) KeyValues { // Initialize the boilerplate keys and values. keysAndValues := KeyValues{ KeyDriverConnectionID, srv.DriverConnectionID, @@ -272,7 +272,7 @@ type ServerSelection struct { // SerializeServerSelection serializes a Topology message into a slice of keys // and values that can be passed to a logger. -func SerializeServerSelection(srvSelection ServerSelection, extraKV ...any) KeyValues { +func SerializeServerSelection(srvSelection ServerSelection, extraKV ...interface{}) KeyValues { keysAndValues := KeyValues{ KeySelector, srvSelection.Selector, KeyOperation, srvSelection.Operation, @@ -299,7 +299,7 @@ type Topology struct { // SerializeTopology serializes a Topology message into a slice of keys and // values that can be passed to a logger. -func SerializeTopology(topo Topology, extraKV ...any) KeyValues { +func SerializeTopology(topo Topology, extraKV ...interface{}) KeyValues { keysAndValues := KeyValues{ KeyTopologyID, topo.ID.Hex(), } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go index 3edceb61..0a6c1bdc 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go @@ -36,12 +36,12 @@ func NewIOSink(out io.Writer) *IOSink { } // Info will write a JSON-encoded message to the io.Writer. -func (sink *IOSink) Info(_ int, msg string, keysAndValues ...any) { +func (sink *IOSink) Info(_ int, msg string, keysAndValues ...interface{}) { mapSize := len(keysAndValues) / 2 if math.MaxInt-mapSize >= 2 { mapSize += 2 } - kvMap := make(map[string]any, mapSize) + kvMap := make(map[string]interface{}, mapSize) kvMap[KeyTimestamp] = time.Now().UnixNano() kvMap[KeyMessage] = msg @@ -57,7 +57,7 @@ func (sink *IOSink) Info(_ int, msg string, keysAndValues ...any) { } // Error will write a JSON-encoded error message to the io.Writer. -func (sink *IOSink) Error(err error, msg string, kv ...any) { +func (sink *IOSink) Error(err error, msg string, kv ...interface{}) { kv = append(kv, KeyError, err.Error()) sink.Info(0, msg, kv...) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go index c9b700b2..c43e37c2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go @@ -36,10 +36,10 @@ const maxDocumentLengthEnvVar = "MONGODB_LOG_MAX_DOCUMENT_LENGTH" type LogSink interface { // Info logs a non-error message with the given key/value pairs. The // level argument is provided for optional logging. - Info(level int, msg string, keysAndValues ...any) + Info(level int, msg string, keysAndValues ...interface{}) // Error logs an error, with the given message and key/value pairs. - Error(err error, msg string, keysAndValues ...any) + Error(err error, msg string, keysAndValues ...interface{}) } // Logger represents the configuration for the internal logger. @@ -112,7 +112,7 @@ func (logger *Logger) LevelComponentEnabled(level Level, component Component) bo // this function is implemented based on the go-logr/logr LogSink interface, // which is why "Print" has a message parameter. Any duplication in code is // intentional to adhere to the logr pattern. -func (logger *Logger) Print(level Level, component Component, msg string, keysAndValues ...any) { +func (logger *Logger) Print(level Level, component Component, msg string, keysAndValues ...interface{}) { // If the level is not enabled for the component, then // skip the message. if !logger.LevelComponentEnabled(level, component) { @@ -130,7 +130,7 @@ func (logger *Logger) Print(level Level, component Component, msg string, keysAn // Error logs an error, with the given message and key/value pairs. // It functions similarly to Print, but may have unique behavior, and should be // preferred for logging errors. -func (logger *Logger) Error(err error, msg string, keysAndValues ...any) { +func (logger *Logger) Error(err error, msg string, keysAndValues ...interface{}) { if logger.Sink == nil { return } @@ -241,9 +241,10 @@ func FormatDocument(msg bson.Raw, width uint) string { return "{}" } - str, truncated := bsoncore.Document(msg).StringN(int(width)) + str := bsoncore.Document(msg).StringN(int(width)) - if truncated { + // If the last byte is not a closing bracket, then the document was truncated + if len(str) > 0 && str[len(str)-1] != '}' { str += TruncationSuffix } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go index be58d38b..0345b96e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go @@ -7,9 +7,7 @@ package mongoutil import ( - "context" "reflect" - "time" "go.mongodb.org/mongo-driver/v2/mongo/options" ) @@ -85,17 +83,3 @@ func HostsFromURI(uri string) ([]string, error) { return opts.Hosts, nil } - -// TimeoutWithinContext will return true if the provided timeout is nil or if -// it is less than the context deadline. If the context does not have a -// deadline, it will return true. -func TimeoutWithinContext(ctx context.Context, timeout time.Duration) bool { - deadline, ok := ctx.Deadline() - if !ok { - return true - } - - ctxTimeout := time.Until(deadline) - - return ctxTimeout <= 0 || timeout < ctxTimeout -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go deleted file mode 100644 index 5e7527c9..00000000 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright (C) MongoDB, Inc. 2025-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 optionsutil - -// Options stores internal options. -type Options struct { - values map[string]any -} - -// WithValue sets an option value with the associated key. -func WithValue(opts Options, key string, option any) Options { - if opts.values == nil { - opts.values = make(map[string]any) - } - opts.values[key] = option - return opts -} - -// Value returns the value associated with the options for key. -func Value(opts Options, key string) any { - if opts.values == nil { - return nil - } - if val, ok := opts.values[key]; ok { - return val - } - return nil -} - -// Equal compares two Options instances for equality. -func Equal(opts1, opts2 Options) bool { - if len(opts1.values) != len(opts2.values) { - return false - } - for key, val1 := range opts1.values { - if val2, ok := opts2.values[key]; !ok || val1 != val2 { - return false - } - } - return true -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go index 0fac0868..e4146e8b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go @@ -29,6 +29,6 @@ func newBackgroundContext(ctx context.Context) context.Context { } } -func (b *backgroundContext) Value(key any) any { +func (b *backgroundContext) Value(key interface{}) interface{} { return b.childValuesCtx.Value(key) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go index fc6f7604..148a6275 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go @@ -50,12 +50,7 @@ type batchCursor interface { // SetComment will set a user-configurable comment that can be used to // identify the operation in server logs. - SetComment(any) - - // MaxAwaitTime returns the maximum amount of time the server will allow - // the operations to execute. This is only valid for tailable awaitData - // cursors. - MaxAwaitTime() *time.Duration + SetComment(interface{}) } // changeStreamCursor is the interface implemented by batch cursors that also provide the functionality for retrieving diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go index 036e3bad..415a90ae 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go @@ -29,7 +29,7 @@ type bulkWriteBatch struct { // bulkWrite performs a bulkwrite operation type bulkWrite struct { - comment any + comment interface{} ordered *bool bypassDocumentValidation *bool models []WriteModel @@ -38,8 +38,7 @@ type bulkWrite struct { selector description.ServerSelector writeConcern *writeconcern.WriteConcern result BulkWriteResult - let any - rawData *bool + let interface{} } func (bw *bulkWrite) execute(ctx context.Context) error { @@ -50,7 +49,7 @@ func (bw *bulkWrite) execute(ctx context.Context) error { batches := createBatches(bw.models, ordered) bw.result = BulkWriteResult{ - UpsertedIDs: make(map[int64]any), + UpsertedIDs: make(map[int64]interface{}), } bwErr := BulkWriteException{ @@ -105,7 +104,7 @@ func (bw *bulkWrite) execute(ctx context.Context) error { func (bw *bulkWrite) runBatch(ctx context.Context, batch bulkWriteBatch) (BulkWriteResult, BulkWriteException, error) { batchRes := BulkWriteResult{ - UpsertedIDs: make(map[int64]any), + UpsertedIDs: make(map[int64]interface{}), } batchErr := BulkWriteException{} @@ -210,10 +209,6 @@ func (bw *bulkWrite) runInsert(ctx context.Context, batch bulkWriteBatch) (opera } op = op.Retry(retry) - if bw.rawData != nil { - op.RawData(*bw.rawData) - } - err := op.Execute(ctx) return op.Result(), err @@ -287,19 +282,15 @@ func (bw *bulkWrite) runDelete(ctx context.Context, batch bulkWriteBatch) (opera } op = op.Retry(retry) - if bw.rawData != nil { - op.RawData(*bw.rawData) - } - err := op.Execute(ctx) return op.Result(), err } func createDeleteDoc( - filter any, + filter interface{}, collation *options.Collation, - hint any, + hint interface{}, deleteOne bool, bsonOpts *options.BSONOptions, registry *bson.Registry, @@ -424,21 +415,17 @@ func (bw *bulkWrite) runUpdate(ctx context.Context, batch bulkWriteBatch) (opera } op = op.Retry(retry) - if bw.rawData != nil { - op.RawData(*bw.rawData) - } - err := op.Execute(ctx) return op.Result(), err } type updateDoc struct { - filter any - update any - hint any - sort any - arrayFilters []any + filter interface{} + update interface{} + hint interface{} + sort interface{} + arrayFilters []interface{} collation *options.Collation upsert *bool multi bool diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go index f28af163..ddc3043a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go @@ -23,7 +23,7 @@ type WriteModel interface { // // See corresponding setter methods for documentation. type InsertOneModel struct { - Document any + Document interface{} } // NewInsertOneModel creates a new InsertOneModel. @@ -34,7 +34,7 @@ func NewInsertOneModel() *InsertOneModel { // SetDocument specifies the document to be inserted. The document cannot be nil. If it does not have an _id field when // transformed into BSON, one will be added automatically to the marshalled document. The original document will not be // modified. -func (iom *InsertOneModel) SetDocument(doc any) *InsertOneModel { +func (iom *InsertOneModel) SetDocument(doc interface{}) *InsertOneModel { iom.Document = doc return iom } @@ -45,9 +45,9 @@ func (*InsertOneModel) writeModel() {} // // See corresponding setter methods for documentation. type DeleteOneModel struct { - Filter any + Filter interface{} Collation *options.Collation - Hint any + Hint interface{} } // NewDeleteOneModel creates a new DeleteOneModel. @@ -58,7 +58,7 @@ func NewDeleteOneModel() *DeleteOneModel { // SetFilter specifies a filter to use to select the document to delete. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (dom *DeleteOneModel) SetFilter(filter any) *DeleteOneModel { +func (dom *DeleteOneModel) SetFilter(filter interface{}) *DeleteOneModel { dom.Filter = filter return dom } @@ -70,14 +70,13 @@ func (dom *DeleteOneModel) SetCollation(collation *options.Collation) *DeleteOne return dom } -// SetHint specifies the index to use for the operation. This should either be -// the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.4. Server versions < 4.4 will -// return an error if this option is specified. The driver will return an error -// if this option is specified during an unacknowledged write operation. The -// driver will return an error if the hint parameter is a multi-key map. The -// default value is nil, which means that no hint will be sent. -func (dom *DeleteOneModel) SetHint(hint any) *DeleteOneModel { +// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will +// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if +// this option is specified. The driver will return an error if this option is specified during an unacknowledged write +// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which +// means that no hint will be sent. +func (dom *DeleteOneModel) SetHint(hint interface{}) *DeleteOneModel { dom.Hint = hint return dom } @@ -88,9 +87,9 @@ func (*DeleteOneModel) writeModel() {} // // See corresponding setter methods for documentation. type DeleteManyModel struct { - Filter any + Filter interface{} Collation *options.Collation - Hint any + Hint interface{} } // NewDeleteManyModel creates a new DeleteManyModel. @@ -100,7 +99,7 @@ func NewDeleteManyModel() *DeleteManyModel { // SetFilter specifies a filter to use to select documents to delete. The filter must be a document containing query // operators. It cannot be nil. -func (dmm *DeleteManyModel) SetFilter(filter any) *DeleteManyModel { +func (dmm *DeleteManyModel) SetFilter(filter interface{}) *DeleteManyModel { dmm.Filter = filter return dmm } @@ -112,14 +111,13 @@ func (dmm *DeleteManyModel) SetCollation(collation *options.Collation) *DeleteMa return dmm } -// SetHint specifies the index to use for the operation. This should either be -// the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.4. Server versions < 4.4 will -// return an error if this option is specified. The driver will return an error -// if this option is specified during an unacknowledged write operation. The -// driver will return an error if the hint parameter is a multi-key map. The -// default value is nil, which means that no hint will be sent. -func (dmm *DeleteManyModel) SetHint(hint any) *DeleteManyModel { +// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will +// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if +// this option is specified. The driver will return an error if this option is specified during an unacknowledged write +// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which +// means that no hint will be sent. +func (dmm *DeleteManyModel) SetHint(hint interface{}) *DeleteManyModel { dmm.Hint = hint return dmm } @@ -132,10 +130,10 @@ func (*DeleteManyModel) writeModel() {} type ReplaceOneModel struct { Collation *options.Collation Upsert *bool - Filter any - Replacement any - Hint any - Sort any + Filter interface{} + Replacement interface{} + Hint interface{} + Sort interface{} } // NewReplaceOneModel creates a new ReplaceOneModel. @@ -143,14 +141,13 @@ func NewReplaceOneModel() *ReplaceOneModel { return &ReplaceOneModel{} } -// SetHint specifies the index to use for the operation. This should either be -// the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.2. Server versions < 4.2 will -// return an error if this option is specified. The driver will return an error -// if this option is specified during an unacknowledged write operation. The -// driver will return an error if the hint parameter is a multi-key map. The -// default value is nil, which means that no hint will be sent. -func (rom *ReplaceOneModel) SetHint(hint any) *ReplaceOneModel { +// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will +// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if +// this option is specified. The driver will return an error if this option is specified during an unacknowledged write +// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which +// means that no hint will be sent. +func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel { rom.Hint = hint return rom } @@ -158,14 +155,14 @@ func (rom *ReplaceOneModel) SetHint(hint any) *ReplaceOneModel { // SetFilter specifies a filter to use to select the document to replace. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (rom *ReplaceOneModel) SetFilter(filter any) *ReplaceOneModel { +func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel { rom.Filter = filter return rom } // SetReplacement specifies a document that will be used to replace the selected document. It cannot be nil and cannot // contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). -func (rom *ReplaceOneModel) SetReplacement(rep any) *ReplaceOneModel { +func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel { rom.Replacement = rep return rom } @@ -189,7 +186,7 @@ func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel { // matched by the sort order will be replaced. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (rom *ReplaceOneModel) SetSort(sort any) *ReplaceOneModel { +func (rom *ReplaceOneModel) SetSort(sort interface{}) *ReplaceOneModel { rom.Sort = sort return rom } @@ -202,11 +199,11 @@ func (*ReplaceOneModel) writeModel() {} type UpdateOneModel struct { Collation *options.Collation Upsert *bool - Filter any - Update any - ArrayFilters []any - Hint any - Sort any + Filter interface{} + Update interface{} + ArrayFilters []interface{} + Hint interface{} + Sort interface{} } // NewUpdateOneModel creates a new UpdateOneModel. @@ -214,14 +211,13 @@ func NewUpdateOneModel() *UpdateOneModel { return &UpdateOneModel{} } -// SetHint specifies the index to use for the operation. This should either be -// the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.2. Server versions < 4.2 will -// return an error if this option is specified. The driver will return an error -// if this option is specified during an unacknowledged write operation. The -// driver will return an error if the hint parameter is a multi-key map. The -// default value is nil, which means that no hint will be sent. -func (uom *UpdateOneModel) SetHint(hint any) *UpdateOneModel { +// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will +// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if +// this option is specified. The driver will return an error if this option is specified during an unacknowledged write +// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which +// means that no hint will be sent. +func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel { uom.Hint = hint return uom } @@ -229,21 +225,21 @@ func (uom *UpdateOneModel) SetHint(hint any) *UpdateOneModel { // SetFilter specifies a filter to use to select the document to update. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (uom *UpdateOneModel) SetFilter(filter any) *UpdateOneModel { +func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel { uom.Filter = filter return uom } // SetUpdate specifies the modifications to be made to the selected document. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (uom *UpdateOneModel) SetUpdate(update any) *UpdateOneModel { +func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel { uom.Update = update return uom } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (uom *UpdateOneModel) SetArrayFilters(filters []any) *UpdateOneModel { +func (uom *UpdateOneModel) SetArrayFilters(filters []interface{}) *UpdateOneModel { uom.ArrayFilters = filters return uom } @@ -267,7 +263,7 @@ func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel { // matched by the sort order will be updated. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (uom *UpdateOneModel) SetSort(sort any) *UpdateOneModel { +func (uom *UpdateOneModel) SetSort(sort interface{}) *UpdateOneModel { uom.Sort = sort return uom } @@ -280,10 +276,10 @@ func (*UpdateOneModel) writeModel() {} type UpdateManyModel struct { Collation *options.Collation Upsert *bool - Filter any - Update any - ArrayFilters []any - Hint any + Filter interface{} + Update interface{} + ArrayFilters []interface{} + Hint interface{} } // NewUpdateManyModel creates a new UpdateManyModel. @@ -291,35 +287,34 @@ func NewUpdateManyModel() *UpdateManyModel { return &UpdateManyModel{} } -// SetHint specifies the index to use for the operation. This should either be -// the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.2. Server versions < 4.2 will -// return an error if this option is specified. The driver will return an error -// if this option is specified during an unacknowledged write operation. The -// driver will return an error if the hint parameter is a multi-key map. The -// default value is nil, which means that no hint will be sent. -func (umm *UpdateManyModel) SetHint(hint any) *UpdateManyModel { +// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will +// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if +// this option is specified. The driver will return an error if this option is specified during an unacknowledged write +// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which +// means that no hint will be sent. +func (umm *UpdateManyModel) SetHint(hint interface{}) *UpdateManyModel { umm.Hint = hint return umm } // SetFilter specifies a filter to use to select documents to update. The filter must be a document containing query // operators. It cannot be nil. -func (umm *UpdateManyModel) SetFilter(filter any) *UpdateManyModel { +func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel { umm.Filter = filter return umm } // SetUpdate specifies the modifications to be made to the selected documents. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (umm *UpdateManyModel) SetUpdate(update any) *UpdateManyModel { +func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel { umm.Update = update return umm } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (umm *UpdateManyModel) SetArrayFilters(filters []any) *UpdateManyModel { +func (umm *UpdateManyModel) SetArrayFilters(filters []interface{}) *UpdateManyModel { umm.ArrayFilters = filters return umm } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go index d5ad8058..bde1ebc8 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go @@ -12,6 +12,7 @@ import ( "fmt" "reflect" "strconv" + "time" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/internal/csot" @@ -102,7 +103,34 @@ type changeStreamConfig struct { crypt driver.Crypt } -func newChangeStream(ctx context.Context, config changeStreamConfig, pipeline any, +// validChangeStreamTimeouts will return "false" if maxAwaitTimeMS is set, +// timeoutMS is set to a non-zero value, and maxAwaitTimeMS is greater than or +// equal to timeoutMS. Otherwise, the timeouts are valid. +func validChangeStreamTimeouts(ctx context.Context, cs *ChangeStream) bool { + if cs.options == nil || cs.client == nil { + return true + } + + maxAwaitTime := cs.options.MaxAwaitTime + timeout := cs.client.timeout + + if maxAwaitTime == nil { + return true + } + + if deadline, ok := ctx.Deadline(); ok { + ctxTimeout := time.Until(deadline) + timeout = &ctxTimeout + } + + if timeout == nil { + return true + } + + return *timeout <= 0 || *maxAwaitTime < *timeout +} + +func newChangeStream(ctx context.Context, config changeStreamConfig, pipeline interface{}, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { if ctx == nil { ctx = context.Background() @@ -311,8 +339,8 @@ AggregateExecuteLoop: break AggregateExecuteLoop } - var tt driver.Error - if errors.As(err, &tt) { + switch tt := err.(type) { + case driver.Error: // If error is not retryable, do not retry. if !tt.RetryableRead() { break AggregateExecuteLoop @@ -342,13 +370,13 @@ AggregateExecuteLoop: // Reset deployment. cs.aggregate.Deployment(cs.createOperationDeployment(server, conn)) - } else { + default: // Do not retry if error is not a driver error. break AggregateExecuteLoop } } if err != nil { - cs.err = wrapErrors(err) + cs.err = replaceErrors(err) return cs.err } @@ -356,7 +384,7 @@ AggregateExecuteLoop: cr.Server = server cs.cursor, cs.err = driver.NewBatchCursor(cr, cs.sess, cs.client.clock, cs.cursorOptions) - if cs.err = wrapErrors(cs.err); cs.err != nil { + if cs.err = replaceErrors(cs.err); cs.err != nil { return cs.Err() } @@ -401,7 +429,7 @@ func (cs *ChangeStream) storeResumeToken() error { return nil } -func (cs *ChangeStream) buildPipelineSlice(pipeline any) error { +func (cs *ChangeStream) buildPipelineSlice(pipeline interface{}) error { val := reflect.ValueOf(pipeline) if !val.IsValid() || !(val.Kind() == reflect.Slice) { cs.err = errors.New("can only marshal slices and arrays into aggregation pipelines, but got invalid") @@ -557,7 +585,7 @@ func (cs *ChangeStream) SetBatchSize(size int32) { // Decode will unmarshal the current event document into val and return any errors from the unmarshalling process // without any modification. If val is nil or is a typed nil, an error will be returned. -func (cs *ChangeStream) Decode(val any) error { +func (cs *ChangeStream) Decode(val interface{}) error { if cs.cursor == nil { return ErrNilCursor } @@ -569,13 +597,13 @@ func (cs *ChangeStream) Decode(val any) error { // Err returns the last error seen by the change stream, or nil if no errors has occurred. func (cs *ChangeStream) Err() error { if cs.err != nil { - return wrapErrors(cs.err) + return replaceErrors(cs.err) } if cs.cursor == nil { return nil } - return wrapErrors(cs.cursor.Err()) + return replaceErrors(cs.cursor.Err()) } // Close closes this change stream and the underlying cursor. Next and TryNext must not be called after Close has been @@ -591,7 +619,7 @@ func (cs *ChangeStream) Close(ctx context.Context) error { return nil // cursor is already closed } - cs.err = wrapErrors(cs.cursor.Close(ctx)) + cs.err = replaceErrors(cs.cursor.Close(ctx)) cs.cursor = nil return cs.Err() } @@ -650,7 +678,7 @@ func (cs *ChangeStream) next(ctx context.Context, nonBlocking bool) bool { if len(cs.batch) == 0 { cs.loopNext(ctx, nonBlocking) if cs.err != nil { - cs.err = wrapErrors(cs.err) + cs.err = replaceErrors(cs.err) return false } if len(cs.batch) == 0 { @@ -668,33 +696,10 @@ func (cs *ChangeStream) next(ctx context.Context, nonBlocking bool) bool { } func (cs *ChangeStream) loopNext(ctx context.Context, nonBlocking bool) { - // To avoid unnecessary socket timeouts, we attempt to short-circuit tailable - // awaitData "getMore" operations by ensuring that the maxAwaitTimeMS is less - // than the operation timeout. - // - // The specifications assume that drivers iteratively apply the timeout - // provided at the constructor level (e.g., (*collection).Find) for tailable - // awaitData cursors: - // - // If set, drivers MUST apply the timeoutMS option to the initial aggregate - // operation. Drivers MUST also apply the original timeoutMS value to each - // next call on the change stream but MUST NOT use it to derive a maxTimeMS - // field for getMore commands. - // - // The Go Driver might decide to support the above behavior with DRIVERS-2722. - // The principal concern is that it would be unexpected for users to apply an - // operation-level timeout via contexts to a constructor and then that timeout - // later be applied while working with a resulting cursor. Instead, it is more - // idiomatic to apply the timeout to the context passed to Next or TryNext. - if cs.options != nil && !nonBlocking { - maxAwaitTime := cs.cursorOptions.MaxAwaitTime - - // If maxAwaitTime is not set, this check is unnecessary. - if maxAwaitTime != nil && !mongoutil.TimeoutWithinContext(ctx, *maxAwaitTime) { - cs.err = fmt.Errorf("MaxAwaitTime must be less than the operation timeout") + if !validChangeStreamTimeouts(ctx, cs) { + cs.err = fmt.Errorf("MaxAwaitTime must be less than the operation timeout") - return - } + return } // Apply the client-level timeout if the operation-level timeout is not set. @@ -714,7 +719,7 @@ func (cs *ChangeStream) loopNext(ctx context.Context, nonBlocking bool) { return } - cs.err = wrapErrors(cs.cursor.Err()) + cs.err = replaceErrors(cs.cursor.Err()) if cs.err == nil { // Check if cursor is alive if cs.ID() == 0 { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go index cb2e5494..09535f2b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go @@ -18,7 +18,6 @@ import ( "go.mongodb.org/mongo-driver/v2/internal/httputil" "go.mongodb.org/mongo-driver/v2/internal/logger" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/ptrutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/internal/uuid" @@ -83,7 +82,7 @@ type Client struct { cryptFLE driver.Crypt metadataClientFLE *Client internalClientFLE *Client - encryptedFieldsMap map[string]any + encryptedFieldsMap map[string]interface{} authenticator driver.Authenticator } @@ -240,7 +239,7 @@ func newClient(opts ...*options.ClientOptions) (*Client, error) { if client.deployment == nil { client.deployment, err = topology.New(cfg) if err != nil { - return nil, wrapErrors(err) + return nil, replaceErrors(err) } } @@ -262,7 +261,7 @@ func (c *Client) connect() error { if connector, ok := c.deployment.(driver.Connector); ok { err := connector.Connect() if err != nil { - return wrapErrors(err) + return replaceErrors(err) } } @@ -294,7 +293,7 @@ func (c *Client) connect() error { if subscriber, ok := c.deployment.(driver.Subscriber); ok { sub, err := subscriber.Subscribe() if err != nil { - return wrapErrors(err) + return replaceErrors(err) } updateChan = sub.Updates } @@ -351,7 +350,7 @@ func (c *Client) Disconnect(ctx context.Context) error { } if disconnector, ok := c.deployment.(driver.Disconnector); ok { - return wrapErrors(disconnector.Disconnect(ctx)) + return replaceErrors(disconnector.Disconnect(ctx)) } return nil @@ -382,7 +381,7 @@ func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error { {"ping", 1}, }, options.RunCmd().SetReadPreference(rp)) - return wrapErrors(res.Err()) + return replaceErrors(res.Err()) } // StartSession starts a new session configured with the given options. @@ -435,7 +434,7 @@ func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (* sess, err := session.NewClientSession(c.sessionPool, c.id, coreOpts) if err != nil { - return nil, wrapErrors(err) + return nil, replaceErrors(err) } return &Session{ @@ -610,8 +609,7 @@ func (c *Client) newMongoCrypt(opts *options.AutoEncryptionOptions) (*mongocrypt SetEncryptedFieldsMap(cryptEncryptedFieldsMap). SetCryptSharedLibDisabled(cryptSharedLibDisabled || bypassAutoEncryption). SetCryptSharedLibOverridePath(cryptSharedLibPath). - SetHTTPClient(opts.HTTPClient). - SetKeyExpiration(opts.KeyExpiration)) + SetHTTPClient(opts.HTTPClient)) if err != nil { return nil, err } @@ -681,7 +679,7 @@ func (c *Client) Database(name string, opts ...options.Lister[options.DatabaseOp // The opts parameter can be used to specify options for this operation (see the options.ListDatabasesOptions documentation). // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/listDatabases/. -func (c *Client) ListDatabases(ctx context.Context, filter any, opts ...options.Lister[options.ListDatabasesOptions]) (ListDatabasesResult, error) { +func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...options.Lister[options.ListDatabasesOptions]) (ListDatabasesResult, error) { if ctx == nil { ctx = context.Background() } @@ -742,7 +740,7 @@ func (c *Client) ListDatabases(ctx context.Context, filter any, opts ...options. err = op.Execute(ctx) if err != nil { - return ListDatabasesResult{}, wrapErrors(err) + return ListDatabasesResult{}, replaceErrors(err) } return newListDatabasesResultFromOperation(op.Result()), nil @@ -759,7 +757,7 @@ func (c *Client) ListDatabases(ctx context.Context, filter any, opts ...options. // documentation.) // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/listDatabases/. -func (c *Client) ListDatabaseNames(ctx context.Context, filter any, opts ...options.Lister[options.ListDatabasesOptions]) ([]string, error) { +func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...options.Lister[options.ListDatabasesOptions]) ([]string, error) { opts = append(opts, options.ListDatabases().SetNameOnly(true)) res, err := c.ListDatabases(ctx, filter, opts...) @@ -842,7 +840,7 @@ func (c *Client) UseSessionWithOptions( // // The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptions // documentation). -func (c *Client) Watch(ctx context.Context, pipeline any, +func (c *Client) Watch(ctx context.Context, pipeline interface{}, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { csConfig := changeStreamConfig{ readConcern: c.readConcern, @@ -890,7 +888,7 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, } if len(writes) == 0 { - return nil, fmt.Errorf("invalid writes: %w", ErrEmptySlice) + return nil, ErrEmptySlice } bwo, err := mongoutil.NewOptions(opts...) if err != nil { @@ -958,11 +956,6 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, selector: selector, writeConcern: wc, } - if rawDataOpt := optionsutil.Value(bwo.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op.rawData = &rawData - } - } if bwo.VerboseResults == nil || !(*bwo.VerboseResults) { op.errorsOnly = true } else if !acknowledged { @@ -971,7 +964,7 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, op.result.Acknowledged = acknowledged op.result.HasVerboseResults = !op.errorsOnly err = op.execute(ctx) - return &op.result, wrapErrors(err) + return &op.result, replaceErrors(err) } // newLogger will use the LoggerOptions to create an internal logger and publish diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go index 27c3ad3c..ab2d8b6a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go @@ -30,7 +30,7 @@ const ( type clientBulkWritePair struct { namespace string - model any + model interface{} } type clientBulkWrite struct { @@ -38,24 +38,23 @@ type clientBulkWrite struct { errorsOnly bool ordered *bool bypassDocumentValidation *bool - comment any - let any + comment interface{} + let interface{} session *session.Client client *Client selector description.ServerSelector writeConcern *writeconcern.WriteConcern - rawData *bool result ClientBulkWriteResult } func (bw *clientBulkWrite) execute(ctx context.Context) error { if len(bw.writePairs) == 0 { - return fmt.Errorf("invalid writes: %w", ErrEmptySlice) + return ErrEmptySlice } - for i, m := range bw.writePairs { + for _, m := range bw.writePairs { if m.model == nil { - return fmt.Errorf("error from model at index %d: %w", i, ErrNilDocument) + return ErrNilDocument } } batches := &modelBatches{ @@ -144,10 +143,6 @@ func (bw *clientBulkWrite) newCommand() func([]byte, description.SelectedServer) } dst = bsoncore.AppendDocumentElement(dst, "let", let) } - // Set rawData for 8.2+ servers. - if bw.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *bw.rawData) - } return dst, nil } } @@ -161,7 +156,7 @@ type cursorInfo struct { N int32 NModified *int32 Upserted *struct { - ID any `bson:"_id"` + ID interface{} `bson:"_id"` } } @@ -193,7 +188,7 @@ type modelBatches struct { retryMode driver.RetryMode // RetryNone by default cursorHandlers []func(*cursorInfo, bson.Raw) bool - newIDMap map[int]any + newIDMap map[int]interface{} result *ClientBulkWriteResult writeConcernErrors []WriteConcernError @@ -266,7 +261,7 @@ func (mb *modelBatches) appendBatches(fn functionSet, dst []byte, maxCount, tota } mb.cursorHandlers = mb.cursorHandlers[:0] - mb.newIDMap = make(map[int]any) + mb.newIDMap = make(map[int]interface{}) nsMap := make(map[string]int) getNsIndex := func(namespace string) (int, bool) { @@ -301,7 +296,7 @@ func (mb *modelBatches) appendBatches(fn functionSet, dst []byte, maxCount, tota switch model := mb.writePairs[i].model.(type) { case *ClientInsertOneModel: mb.cursorHandlers = append(mb.cursorHandlers, mb.appendInsertResult) - var id any + var id interface{} id, doc, err = (&clientInsertDoc{ namespace: nsIdx, document: model.Document, @@ -476,11 +471,7 @@ func (mb *modelBatches) processResponse(ctx context.Context, resp bsoncore.Docum return err } var cursor *Cursor - cursor, err = newCursor(bCursor, mb.client.bsonOpts, mb.client.registry, - - // This op doesn't return a cursor to the user, so setting the client - // timeout should be a no-op. - withCursorOptionClientTimeout(mb.client.timeout)) + cursor, err = newCursor(bCursor, mb.client.bsonOpts, mb.client.registry) if err != nil { return err } @@ -586,10 +577,10 @@ func (mb *modelBatches) appendUpdateResult(cur *cursorInfo, raw bson.Raw) bool { type clientInsertDoc struct { namespace int - document any + document interface{} } -func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson.Registry) (any, bsoncore.Document, error) { +func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson.Registry) (interface{}, bsoncore.Document, error) { uidx, doc := bsoncore.AppendDocumentStart(nil) doc = bsoncore.AppendInt32Element(doc, "insert", int32(d.namespace)) @@ -597,7 +588,7 @@ func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson. if err != nil { return nil, nil, err } - var id any + var id interface{} f, id, err = ensureID(f, bson.NilObjectID, bsonOpts, registry) if err != nil { return nil, nil, err @@ -609,12 +600,12 @@ func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson. type clientUpdateDoc struct { namespace int - filter any - update any - hint any - arrayFilters []any + filter interface{} + update interface{} + hint interface{} + arrayFilters []interface{} collation *options.Collation - sort any + sort interface{} upsert *bool multi bool checkDollarKey bool @@ -685,9 +676,9 @@ func (d *clientUpdateDoc) marshal(bsonOpts *options.BSONOptions, registry *bson. type clientDeleteDoc struct { namespace int - filter any + filter interface{} collation *options.Collation - hint any + hint interface{} multi bool } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go index da0ea18e..87550eee 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go @@ -24,7 +24,7 @@ type ClientWriteModel interface { // // See corresponding setter methods for documentation. type ClientInsertOneModel struct { - Document any + Document interface{} } // NewClientInsertOneModel creates a new ClientInsertOneModel. @@ -37,7 +37,7 @@ func (*ClientInsertOneModel) clientWriteModel() {} // SetDocument specifies the document to be inserted. The document cannot be nil. If it does not have an _id field when // transformed into BSON, one will be added automatically to the marshalled document. The original document will not be // modified. -func (iom *ClientInsertOneModel) SetDocument(doc any) *ClientInsertOneModel { +func (iom *ClientInsertOneModel) SetDocument(doc interface{}) *ClientInsertOneModel { iom.Document = doc return iom } @@ -48,11 +48,11 @@ func (iom *ClientInsertOneModel) SetDocument(doc any) *ClientInsertOneModel { type ClientUpdateOneModel struct { Collation *options.Collation Upsert *bool - Filter any - Update any - ArrayFilters []any - Hint any - Sort any + Filter interface{} + Update interface{} + ArrayFilters []interface{} + Hint interface{} + Sort interface{} } // NewClientUpdateOneModel creates a new ClientUpdateOneModel. @@ -64,7 +64,7 @@ func (*ClientUpdateOneModel) clientWriteModel() {} // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (uom *ClientUpdateOneModel) SetHint(hint any) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetHint(hint interface{}) *ClientUpdateOneModel { uom.Hint = hint return uom } @@ -72,21 +72,21 @@ func (uom *ClientUpdateOneModel) SetHint(hint any) *ClientUpdateOneModel { // SetFilter specifies a filter to use to select the document to update. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (uom *ClientUpdateOneModel) SetFilter(filter any) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetFilter(filter interface{}) *ClientUpdateOneModel { uom.Filter = filter return uom } // SetUpdate specifies the modifications to be made to the selected document. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (uom *ClientUpdateOneModel) SetUpdate(update any) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetUpdate(update interface{}) *ClientUpdateOneModel { uom.Update = update return uom } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (uom *ClientUpdateOneModel) SetArrayFilters(filters []any) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetArrayFilters(filters []interface{}) *ClientUpdateOneModel { uom.ArrayFilters = filters return uom } @@ -110,7 +110,7 @@ func (uom *ClientUpdateOneModel) SetUpsert(upsert bool) *ClientUpdateOneModel { // matched by the sort order will be updated. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (uom *ClientUpdateOneModel) SetSort(sort any) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetSort(sort interface{}) *ClientUpdateOneModel { uom.Sort = sort return uom } @@ -121,10 +121,10 @@ func (uom *ClientUpdateOneModel) SetSort(sort any) *ClientUpdateOneModel { type ClientUpdateManyModel struct { Collation *options.Collation Upsert *bool - Filter any - Update any - ArrayFilters []any - Hint any + Filter interface{} + Update interface{} + ArrayFilters []interface{} + Hint interface{} } // NewClientUpdateManyModel creates a new ClientUpdateManyModel. @@ -136,28 +136,28 @@ func (*ClientUpdateManyModel) clientWriteModel() {} // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (umm *ClientUpdateManyModel) SetHint(hint any) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetHint(hint interface{}) *ClientUpdateManyModel { umm.Hint = hint return umm } // SetFilter specifies a filter to use to select documents to update. The filter must be a document containing query // operators. It cannot be nil. -func (umm *ClientUpdateManyModel) SetFilter(filter any) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetFilter(filter interface{}) *ClientUpdateManyModel { umm.Filter = filter return umm } // SetUpdate specifies the modifications to be made to the selected documents. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (umm *ClientUpdateManyModel) SetUpdate(update any) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetUpdate(update interface{}) *ClientUpdateManyModel { umm.Update = update return umm } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (umm *ClientUpdateManyModel) SetArrayFilters(filters []any) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetArrayFilters(filters []interface{}) *ClientUpdateManyModel { umm.ArrayFilters = filters return umm } @@ -183,10 +183,10 @@ func (umm *ClientUpdateManyModel) SetUpsert(upsert bool) *ClientUpdateManyModel type ClientReplaceOneModel struct { Collation *options.Collation Upsert *bool - Filter any - Replacement any - Hint any - Sort any + Filter interface{} + Replacement interface{} + Hint interface{} + Sort interface{} } // NewClientReplaceOneModel creates a new ClientReplaceOneModel. @@ -198,7 +198,7 @@ func (*ClientReplaceOneModel) clientWriteModel() {} // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (rom *ClientReplaceOneModel) SetHint(hint any) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetHint(hint interface{}) *ClientReplaceOneModel { rom.Hint = hint return rom } @@ -206,14 +206,14 @@ func (rom *ClientReplaceOneModel) SetHint(hint any) *ClientReplaceOneModel { // SetFilter specifies a filter to use to select the document to replace. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (rom *ClientReplaceOneModel) SetFilter(filter any) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetFilter(filter interface{}) *ClientReplaceOneModel { rom.Filter = filter return rom } // SetReplacement specifies a document that will be used to replace the selected document. It cannot be nil and cannot // contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). -func (rom *ClientReplaceOneModel) SetReplacement(rep any) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetReplacement(rep interface{}) *ClientReplaceOneModel { rom.Replacement = rep return rom } @@ -237,7 +237,7 @@ func (rom *ClientReplaceOneModel) SetUpsert(upsert bool) *ClientReplaceOneModel // matched by the sort order will be replaced. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (rom *ClientReplaceOneModel) SetSort(sort any) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetSort(sort interface{}) *ClientReplaceOneModel { rom.Sort = sort return rom } @@ -246,9 +246,9 @@ func (rom *ClientReplaceOneModel) SetSort(sort any) *ClientReplaceOneModel { // // See corresponding setter methods for documentation. type ClientDeleteOneModel struct { - Filter any + Filter interface{} Collation *options.Collation - Hint any + Hint interface{} } // NewClientDeleteOneModel creates a new ClientDeleteOneModel. @@ -261,7 +261,7 @@ func (*ClientDeleteOneModel) clientWriteModel() {} // SetFilter specifies a filter to use to select the document to delete. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (dom *ClientDeleteOneModel) SetFilter(filter any) *ClientDeleteOneModel { +func (dom *ClientDeleteOneModel) SetFilter(filter interface{}) *ClientDeleteOneModel { dom.Filter = filter return dom } @@ -275,7 +275,7 @@ func (dom *ClientDeleteOneModel) SetCollation(collation *options.Collation) *Cli // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (dom *ClientDeleteOneModel) SetHint(hint any) *ClientDeleteOneModel { +func (dom *ClientDeleteOneModel) SetHint(hint interface{}) *ClientDeleteOneModel { dom.Hint = hint return dom } @@ -284,9 +284,9 @@ func (dom *ClientDeleteOneModel) SetHint(hint any) *ClientDeleteOneModel { // // See corresponding setter methods for documentation. type ClientDeleteManyModel struct { - Filter any + Filter interface{} Collation *options.Collation - Hint any + Hint interface{} } // NewClientDeleteManyModel creates a new ClientDeleteManyModel. @@ -298,7 +298,7 @@ func (*ClientDeleteManyModel) clientWriteModel() {} // SetFilter specifies a filter to use to select documents to delete. The filter must be a document containing query // operators. It cannot be nil. -func (dmm *ClientDeleteManyModel) SetFilter(filter any) *ClientDeleteManyModel { +func (dmm *ClientDeleteManyModel) SetFilter(filter interface{}) *ClientDeleteManyModel { dmm.Filter = filter return dmm } @@ -312,7 +312,7 @@ func (dmm *ClientDeleteManyModel) SetCollation(collation *options.Collation) *Cl // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (dmm *ClientDeleteManyModel) SetHint(hint any) *ClientDeleteManyModel { +func (dmm *ClientDeleteManyModel) SetHint(hint interface{}) *ClientDeleteManyModel { dmm.Hint = hint return dmm } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go index 32851fff..07c18529 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go @@ -59,8 +59,7 @@ func NewClientEncryption(keyVaultClient *Client, opts ...options.Lister[options. // ClientEncryption because it's only needed for AutoEncryption and we don't expect users to // have the crypt_shared library installed if they're using ClientEncryption. SetCryptSharedLibDisabled(true). - SetHTTPClient(cea.HTTPClient). - SetKeyExpiration(cea.KeyExpiration)) + SetHTTPClient(cea.HTTPClient)) if err != nil { return nil, err } @@ -82,7 +81,7 @@ func NewClientEncryption(keyVaultClient *Client, opts ...options.Lister[options. // It returns the created collection and the encrypted fields document used to create it. func (ce *ClientEncryption) CreateEncryptedCollection(ctx context.Context, db *Database, coll string, createOpts options.Lister[options.CreateCollectionOptions], - kmsProvider string, masterKey any) (*Collection, bson.M, error) { + kmsProvider string, masterKey interface{}) (*Collection, bson.M, error) { if ce.closed { return nil, nil, ErrClientDisconnected } @@ -273,7 +272,7 @@ func (ce *ClientEncryption) Encrypt( // {$and: [{$gt: [, ]}, {$lt: [, ]}] // $gt may also be $gte. $lt may also be $lte. // Only supported for queryType "range" -func (ce *ClientEncryption) EncryptExpression(ctx context.Context, expr any, result any, opts ...options.Lister[options.EncryptOptions]) error { +func (ce *ClientEncryption) EncryptExpression(ctx context.Context, expr interface{}, result interface{}, opts ...options.Lister[options.EncryptOptions]) error { if ce.closed { return ErrClientDisconnected } @@ -444,7 +443,7 @@ func setRewrapManyDataKeyWriteModels(rewrappedDocuments []bsoncore.Document, wri // libmongocrypt 1.5.2 is required. An error is returned if the detected version of libmongocrypt is less than 1.5.2. func (ce *ClientEncryption) RewrapManyDataKey( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.RewrapManyDataKeyOptions], ) (*RewrapManyDataKeyResult, error) { // libmongocrypt versions 1.5.0 and 1.5.1 have a severe bug in RewrapManyDataKey. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go index ef4188d6..a9279f13 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go @@ -17,7 +17,6 @@ import ( "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/internal/csfle" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/mongo/readconcern" @@ -47,7 +46,7 @@ type Collection struct { // aggregateParams is used to store information to configure an Aggregate operation. type aggregateParams struct { ctx context.Context - pipeline any + pipeline interface{} client *Client bsonOpts *options.BSONOptions registry *bson.Registry @@ -194,7 +193,7 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, opts ...options.Lister[options.BulkWriteOptions]) (*BulkWriteResult, error) { if len(models) == 0 { - return nil, fmt.Errorf("invalid models: %w", ErrEmptySlice) + return nil, ErrEmptySlice } if ctx == nil { @@ -222,9 +221,9 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, selector := makePinnedSelector(sess, coll.writeSelector) - for i, model := range models { + for _, model := range models { if model == nil { - return nil, fmt.Errorf("invalid model at index %d: %w", i, ErrNilDocument) + return nil, ErrNilDocument } } @@ -246,28 +245,23 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, writeConcern: wc, let: args.Let, } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op.rawData = &rawData - } - } err = op.execute(ctx) - return &op.result, wrapErrors(err) + return &op.result, replaceErrors(err) } func (coll *Collection) insert( ctx context.Context, - documents []any, + documents []interface{}, opts ...options.Lister[options.InsertManyOptions], -) ([]any, error) { +) ([]interface{}, error) { if ctx == nil { ctx = context.Background() } - result := make([]any, len(documents)) + result := make([]interface{}, len(documents)) docs := make([]bsoncore.Document, len(documents)) for i, doc := range documents { @@ -330,11 +324,6 @@ func (coll *Collection) insert( if args.Ordered != nil { op = op.Ordered(*args.Ordered) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if coll.client.retryWrites { retry = driver.RetryOncePerCommand @@ -371,7 +360,7 @@ func (coll *Collection) insert( // The opts parameter can be used to specify options for the operation (see the options.InsertOneOptions documentation.) // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/insert/. -func (coll *Collection) InsertOne(ctx context.Context, document any, +func (coll *Collection) InsertOne(ctx context.Context, document interface{}, opts ...options.Lister[options.InsertOneOptions]) (*InsertOneResult, error) { args, err := mongoutil.NewOptions(opts...) @@ -386,14 +375,7 @@ func (coll *Collection) InsertOne(ctx context.Context, document any, if args.Comment != nil { imOpts.SetComment(args.Comment) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - imOpts.Opts = append(imOpts.Opts, func(opts *options.InsertManyOptions) error { - optionsutil.WithValue(opts.Internal, "rawData", rawDataOpt) - - return nil - }) - } - res, err := coll.insert(ctx, []any{document}, imOpts) + res, err := coll.insert(ctx, []interface{}{document}, imOpts) rr, err := processWriteError(err) if rr&rrOne == 0 && rr.isAcknowledged() { @@ -419,19 +401,19 @@ func (coll *Collection) InsertOne(ctx context.Context, document any, // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/insert/. func (coll *Collection) InsertMany( ctx context.Context, - documents any, + documents interface{}, opts ...options.Lister[options.InsertManyOptions], ) (*InsertManyResult, error) { dv := reflect.ValueOf(documents) if dv.Kind() != reflect.Slice { - return nil, fmt.Errorf("invalid documents: %w", ErrNotSlice) + return nil, ErrNotSlice } if dv.Len() == 0 { - return nil, fmt.Errorf("invalid documents: %w", ErrEmptySlice) + return nil, ErrEmptySlice } - docSlice := make([]any, 0, dv.Len()) + docSlice := make([]interface{}, 0, dv.Len()) for i := 0; i < dv.Len(); i++ { docSlice = append(docSlice, dv.Index(i).Interface()) } @@ -469,7 +451,7 @@ func (coll *Collection) InsertMany( func (coll *Collection) delete( ctx context.Context, - filter any, + filter interface{}, deleteOne bool, expectedRr returnResult, args *options.DeleteManyOptions, @@ -552,11 +534,6 @@ func (coll *Collection) delete( } op = op.Let(let) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } // deleteMany cannot be retried retryMode := driver.RetryNone @@ -586,7 +563,7 @@ func (coll *Collection) delete( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/delete/. func (coll *Collection) DeleteOne( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.DeleteOneOptions], ) (*DeleteResult, error) { args, err := mongoutil.NewOptions[options.DeleteOneOptions](opts...) @@ -598,7 +575,6 @@ func (coll *Collection) DeleteOne( Comment: args.Comment, Hint: args.Hint, Let: args.Let, - Internal: args.Internal, } return coll.delete(ctx, filter, true, rrOne, deleteOptions) @@ -616,7 +592,7 @@ func (coll *Collection) DeleteOne( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/delete/. func (coll *Collection) DeleteMany( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.DeleteManyOptions], ) (*DeleteResult, error) { args, err := mongoutil.NewOptions[options.DeleteManyOptions](opts...) @@ -630,11 +606,11 @@ func (coll *Collection) DeleteMany( func (coll *Collection) updateOrReplace( ctx context.Context, filter bsoncore.Document, - update any, + update interface{}, multi bool, expectedRr returnResult, checkDollarKey bool, - sort any, + sort interface{}, args *options.UpdateManyOptions, ) (*UpdateResult, error) { @@ -705,11 +681,6 @@ func (coll *Collection) updateOrReplace( } op = op.Comment(comment) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone // retryable writes are only enabled updateOne/replaceOne operations if !multi && coll.client.retryWrites { @@ -753,12 +724,12 @@ func (coll *Collection) updateOrReplace( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) UpdateByID( ctx context.Context, - id any, - update any, + id interface{}, + update interface{}, opts ...options.Lister[options.UpdateOneOptions], ) (*UpdateResult, error) { if id == nil { - return nil, fmt.Errorf("invalid id: %w", ErrNilValue) + return nil, ErrNilValue } return coll.UpdateOne(ctx, bson.D{{"_id", id}}, update, opts...) } @@ -779,8 +750,8 @@ func (coll *Collection) UpdateByID( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) UpdateOne( ctx context.Context, - filter any, - update any, + filter interface{}, + update interface{}, opts ...options.Lister[options.UpdateOneOptions], ) (*UpdateResult, error) { if ctx == nil { @@ -804,7 +775,6 @@ func (coll *Collection) UpdateOne( Hint: args.Hint, Upsert: args.Upsert, Let: args.Let, - Internal: args.Internal, } return coll.updateOrReplace(ctx, f, update, false, rrOne, true, args.Sort, updateOptions) @@ -825,8 +795,8 @@ func (coll *Collection) UpdateOne( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) UpdateMany( ctx context.Context, - filter any, - update any, + filter interface{}, + update interface{}, opts ...options.Lister[options.UpdateManyOptions], ) (*UpdateResult, error) { if ctx == nil { @@ -861,8 +831,8 @@ func (coll *Collection) UpdateMany( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) ReplaceOne( ctx context.Context, - filter any, - replacement any, + filter interface{}, + replacement interface{}, opts ...options.Lister[options.ReplaceOptions], ) (*UpdateResult, error) { if ctx == nil { @@ -895,7 +865,6 @@ func (coll *Collection) ReplaceOne( Hint: args.Hint, Let: args.Let, Comment: args.Comment, - Internal: args.Internal, } return coll.updateOrReplace(ctx, f, r, false, rrOne, false, args.Sort, updateOptions) @@ -914,7 +883,7 @@ func (coll *Collection) ReplaceOne( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/aggregate/. func (coll *Collection) Aggregate( ctx context.Context, - pipeline any, + pipeline interface{}, opts ...options.Lister[options.AggregateOptions], ) (*Cursor, error) { a := aggregateParams{ @@ -1067,11 +1036,6 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption } op.CustomOptions(customOptions) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if a.retryRead && !hasOutputStage { @@ -1081,25 +1045,18 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption err = op.Execute(a.ctx) if err != nil { - var wce driver.WriteCommandError - if errors.As(err, &wce) && wce.WriteConcernError != nil { + if wce, ok := err.(driver.WriteCommandError); ok && wce.WriteConcernError != nil { return nil, *convertDriverWriteConcernError(wce.WriteConcernError) } - return nil, wrapErrors(err) + return nil, replaceErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { - return nil, wrapErrors(err) + return nil, replaceErrors(err) } - cursor, err := newCursorWithSession(bc, a.client.bsonOpts, a.registry, sess, - - // The only way the server will return a tailable/awaitData cursor for an - // aggregate operation is for the first stage in the pipeline to - // be $changeStream, this is the only time maxAwaitTimeMS should be applied. - // For this reason, we pass the client timeout to the cursor. - withCursorOptionClientTimeout(a.client.timeout)) - return cursor, wrapErrors(err) + cursor, err := newCursorWithSession(bc, a.client.bsonOpts, a.registry, sess) + return cursor, replaceErrors(err) } // CountDocuments returns the number of documents in the collection. For a fast count of the documents in the @@ -1110,7 +1067,7 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption // result in a full collection scan. // // The opts parameter can be used to specify options for the operation (see the options.CountOptions documentation). -func (coll *Collection) CountDocuments(ctx context.Context, filter any, +func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, opts ...options.Lister[options.CountOptions]) (int64, error) { if ctx == nil { ctx = context.Background() @@ -1166,11 +1123,6 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter any, } op.Hint(hintVal) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if coll.client.retryReads { retry = driver.RetryOncePerCommand @@ -1179,7 +1131,7 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter any, err = op.Execute(ctx) if err != nil { - return 0, wrapErrors(err) + return 0, replaceErrors(err) } batch := op.ResultCursorResponse().FirstBatch @@ -1252,11 +1204,6 @@ func (coll *Collection) EstimatedDocumentCount( } op = op.Comment(comment) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if coll.client.retryReads { @@ -1265,7 +1212,7 @@ func (coll *Collection) EstimatedDocumentCount( op.Retry(retry) err = op.Execute(ctx) - return op.Result().N, wrapErrors(err) + return op.Result().N, replaceErrors(err) } // Distinct executes a distinct command to find the unique values for a specified field in the collection. @@ -1281,7 +1228,7 @@ func (coll *Collection) EstimatedDocumentCount( func (coll *Collection) Distinct( ctx context.Context, fieldName string, - filter any, + filter interface{}, opts ...options.Lister[options.DistinctOptions], ) *DistinctResult { if ctx == nil { @@ -1346,11 +1293,6 @@ func (coll *Collection) Distinct( } op.Hint(hint) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if coll.client.retryReads { retry = driver.RetryOncePerCommand @@ -1359,7 +1301,7 @@ func (coll *Collection) Distinct( err = op.Execute(ctx) if err != nil { - return &DistinctResult{err: wrapErrors(err)} + return &DistinctResult{err: replaceErrors(err)} } arr, ok := op.Result().Values.ArrayOK() @@ -1384,7 +1326,7 @@ func (coll *Collection) Distinct( // The opts parameter can be used to specify options for the operation (see the options.FindOptions documentation). // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/find/. -func (coll *Collection) Find(ctx context.Context, filter any, +func (coll *Collection) Find(ctx context.Context, filter interface{}, opts ...options.Lister[options.FindOptions]) (*Cursor, error) { args, err := mongoutil.NewOptions(opts...) if err != nil { @@ -1400,7 +1342,7 @@ func (coll *Collection) Find(ctx context.Context, filter any, func (coll *Collection) find( ctx context.Context, - filter any, + filter interface{}, omitMaxTimeMS bool, args *options.FindOptions, ) (cur *Cursor, err error) { @@ -1554,11 +1496,6 @@ func (coll *Collection) find( } op.Sort(sort) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if coll.client.retryReads { retry = driver.RetryOncePerCommand @@ -1566,16 +1503,14 @@ func (coll *Collection) find( op = op.Retry(retry) if err = op.Execute(ctx); err != nil { - return nil, wrapErrors(err) + return nil, replaceErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { - return nil, wrapErrors(err) + return nil, replaceErrors(err) } - - return newCursorWithSession(bc, coll.bsonOpts, coll.registry, sess, - withCursorOptionClientTimeout(coll.client.timeout)) + return newCursorWithSession(bc, coll.bsonOpts, coll.registry, sess) } func newFindArgsFromFindOneArgs(args *options.FindOneOptions) *options.FindOptions { @@ -1594,7 +1529,6 @@ func newFindArgsFromFindOneArgs(args *options.FindOneOptions) *options.FindOptio v.ShowRecordID = args.ShowRecordID v.Skip = args.Skip v.Sort = args.Sort - v.Internal = args.Internal } return v } @@ -1608,7 +1542,7 @@ func newFindArgsFromFindOneArgs(args *options.FindOneOptions) *options.FindOptio // The opts parameter can be used to specify options for this operation (see the options.FindOneOptions documentation). // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/find/. -func (coll *Collection) FindOne(ctx context.Context, filter any, +func (coll *Collection) FindOne(ctx context.Context, filter interface{}, opts ...options.Lister[options.FindOneOptions]) *SingleResult { if ctx == nil { @@ -1625,7 +1559,7 @@ func (coll *Collection) FindOne(ctx context.Context, filter any, cur: cursor, bsonOpts: coll.bsonOpts, reg: coll.registry, - err: wrapErrors(err), + err: replaceErrors(err), } } @@ -1699,7 +1633,7 @@ func (coll *Collection) findAndModify(ctx context.Context, op *operation.FindAnd // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/findAndModify/. func (coll *Collection) FindOneAndDelete( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.FindOneAndDeleteOptions]) *SingleResult { f, err := marshal(filter, coll.bsonOpts, coll.registry) @@ -1757,11 +1691,6 @@ func (coll *Collection) FindOneAndDelete( } op = op.Let(let) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } return coll.findAndModify(ctx, op) } @@ -1782,8 +1711,8 @@ func (coll *Collection) FindOneAndDelete( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/findAndModify/. func (coll *Collection) FindOneAndReplace( ctx context.Context, - filter any, - replacement any, + filter interface{}, + replacement interface{}, opts ...options.Lister[options.FindOneAndReplaceOptions], ) *SingleResult { @@ -1859,11 +1788,6 @@ func (coll *Collection) FindOneAndReplace( } op = op.Let(let) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } return coll.findAndModify(ctx, op) } @@ -1885,8 +1809,8 @@ func (coll *Collection) FindOneAndReplace( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/findAndModify/. func (coll *Collection) FindOneAndUpdate( ctx context.Context, - filter any, - update any, + filter interface{}, + update interface{}, opts ...options.Lister[options.FindOneAndUpdateOptions]) *SingleResult { if ctx == nil { @@ -1973,11 +1897,6 @@ func (coll *Collection) FindOneAndUpdate( } op = op.Let(let) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } return coll.findAndModify(ctx, op) } @@ -1995,7 +1914,7 @@ func (coll *Collection) FindOneAndUpdate( // // The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptions // documentation). -func (coll *Collection) Watch(ctx context.Context, pipeline any, +func (coll *Collection) Watch(ctx context.Context, pipeline interface{}, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { csConfig := changeStreamConfig{ @@ -2056,7 +1975,7 @@ func (coll *Collection) Drop(ctx context.Context, opts ...options.Lister[options } // dropEncryptedCollection drops a collection with EncryptedFields. -func (coll *Collection) dropEncryptedCollection(ctx context.Context, ef any) error { +func (coll *Collection) dropEncryptedCollection(ctx context.Context, ef interface{}) error { efBSON, err := marshal(ef, coll.bsonOpts, coll.registry) if err != nil { return fmt.Errorf("error transforming document: %w", err) @@ -2122,9 +2041,9 @@ func (coll *Collection) drop(ctx context.Context) error { err = op.Execute(ctx) // ignore namespace not found errors - var driverErr driver.Error - if !errors.As(err, &driverErr) || !driverErr.NamespaceNotFound() { - return wrapErrors(err) + driverErr, ok := err.(driver.Error) + if !ok || (ok && !driverErr.NamespaceNotFound()) { + return replaceErrors(err) } return nil } @@ -2249,7 +2168,7 @@ func makeOutputAggregateSelector( // isUnorderedMap returns true if val is a map with more than 1 element. It is typically used to // check for unordered Go values that are used in nested command documents where different field // orders mean different things. Examples are the "sort" and "hint" fields. -func isUnorderedMap(val any) bool { +func isUnorderedMap(val interface{}) bool { refValue := reflect.ValueOf(val) return refValue.Kind() == reflect.Map && refValue.Len() > 1 } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go index bb77f4a2..5134c4fe 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go @@ -16,7 +16,6 @@ import ( "time" "go.mongodb.org/mongo-driver/v2/bson" - "go.mongodb.org/mongo-driver/v2/internal/mongoutil" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" @@ -31,41 +30,22 @@ type Cursor struct { // to Next or TryNext. If continued access is required, a copy must be made. Current bson.Raw - bc batchCursor - batch *bsoncore.Iterator - batchLength int - bsonOpts *options.BSONOptions - registry *bson.Registry - clientSession *session.Client - clientTimeout time.Duration - hasClientTimeout bool + bc batchCursor + batch *bsoncore.Iterator + batchLength int + bsonOpts *options.BSONOptions + registry *bson.Registry + clientSession *session.Client err error } -type cursorOptions struct { - clientTimeout time.Duration - hasClientTimeout bool -} - -type cursorOption func(*cursorOptions) - -func withCursorOptionClientTimeout(dur *time.Duration) cursorOption { - return func(opts *cursorOptions) { - if dur != nil && *dur > 0 { - opts.clientTimeout = *dur - opts.hasClientTimeout = true - } - } -} - func newCursor( bc batchCursor, bsonOpts *options.BSONOptions, registry *bson.Registry, - opts ...cursorOption, ) (*Cursor, error) { - return newCursorWithSession(bc, bsonOpts, registry, nil, opts...) + return newCursorWithSession(bc, bsonOpts, registry, nil) } func newCursorWithSession( @@ -73,7 +53,6 @@ func newCursorWithSession( bsonOpts *options.BSONOptions, registry *bson.Registry, clientSession *session.Client, - opts ...cursorOption, ) (*Cursor, error) { if registry == nil { registry = defaultRegistry @@ -81,19 +60,11 @@ func newCursorWithSession( if bc == nil { return nil, errors.New("batch cursor must not be nil") } - - cursorOpts := &cursorOptions{} - for _, opt := range opts { - opt(cursorOpts) - } - c := &Cursor{ - bc: bc, - bsonOpts: bsonOpts, - registry: registry, - clientSession: clientSession, - clientTimeout: cursorOpts.clientTimeout, - hasClientTimeout: cursorOpts.hasClientTimeout, + bc: bc, + bsonOpts: bsonOpts, + registry: registry, + clientSession: clientSession, } if bc.ID() == 0 { c.closeImplicitSession() @@ -114,7 +85,7 @@ func newEmptyCursor() *Cursor { // bson.NewRegistry() will be used. // // The documents parameter must be a slice of documents. The slice may be nil or empty, but all elements must be non-nil. -func NewCursorFromDocuments(documents []any, preloadedErr error, registry *bson.Registry) (*Cursor, error) { +func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registry *bson.Registry) (*Cursor, error) { if registry == nil { registry = defaultRegistry } @@ -126,7 +97,7 @@ func NewCursorFromDocuments(documents []any, preloadedErr error, registry *bson. for i, doc := range documents { switch t := doc.(type) { case nil: - return nil, fmt.Errorf("invalid document at index %d: %w", i, ErrNilDocument) + return nil, ErrNilDocument case []byte: // Slight optimization so we'll just use MarshalBSON and not go through the codec machinery. doc = bson.Raw(t) @@ -168,17 +139,11 @@ func NewCursorFromDocuments(documents []any, preloadedErr error, registry *bson. // ID returns the ID of this cursor, or 0 if the cursor has been closed or exhausted. func (c *Cursor) ID() int64 { return c.bc.ID() } -// Next gets the next document for this cursor. It returns true if there were no -// errors and the cursor has not been exhausted. +// Next gets the next document for this cursor. It returns true if there were no errors and the cursor has not been +// exhausted. // -// Next blocks until a document is available or an error occurs. If the context -// expires, the cursor's error will be set to ctx.Err(). In case of an error, -// Next will return false. -// -// If MaxAwaitTime is set, the operation will be bound by the Context's -// deadline. If the context does not have a deadline, the operation will be -// bound by the client-level timeout, if one is set. If MaxAwaitTime is greater -// than the user-provided timeout, Next will return false. +// Next blocks until a document is available or an error occurs. If the context expires, the cursor's error will +// be set to ctx.Err(). In case of an error, Next will return false. // // If Next returns false, subsequent calls will also return false. func (c *Cursor) Next(ctx context.Context) bool { @@ -210,41 +175,6 @@ func (c *Cursor) next(ctx context.Context, nonBlocking bool) bool { if ctx == nil { ctx = context.Background() } - - // If the context does not have a deadline we defer to a client-level timeout, - // if one is set. - if _, ok := ctx.Deadline(); !ok && c.hasClientTimeout { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, c.clientTimeout) - - defer cancel() - } - - // To avoid unnecessary socket timeouts, we attempt to short-circuit tailable - // awaitData "getMore" operations by ensuring that the maxAwaitTimeMS is less - // than the operation timeout. - // - // The specifications assume that drivers iteratively apply the timeout - // provided at the constructor level (e.g., (*collection).Find) for tailable - // awaitData cursors: - // - // If set, drivers MUST apply the timeoutMS option to the initial aggregate - // operation. Drivers MUST also apply the original timeoutMS value to each - // next call on the change stream but MUST NOT use it to derive a maxTimeMS - // field for getMore commands. - // - // The Go Driver might decide to support the above behavior with DRIVERS-2722. - // The principal concern is that it would be unexpected for users to apply an - // operation-level timeout via contexts to a constructor and then that timeout - // later be applied while working with a resulting cursor. Instead, it is more - // idiomatic to apply the timeout to the context passed to Next or TryNext. - maxAwaitTime := c.bc.MaxAwaitTime() // - if maxAwaitTime != nil && !nonBlocking && !mongoutil.TimeoutWithinContext(ctx, *maxAwaitTime) { - c.err = fmt.Errorf("MaxAwaitTime must be less than the operation timeout") - - return false - } - val, err := c.batch.Next() switch { case err == nil: @@ -264,7 +194,7 @@ func (c *Cursor) next(ctx context.Context, nonBlocking bool) bool { // 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 = wrapErrors(c.bc.Err()) + c.err = replaceErrors(c.bc.Err()) if c.err != nil { return false } @@ -346,7 +276,7 @@ func getDecoder( // Decode will unmarshal the current document into val and return any errors from the unmarshalling process without any // modification. If val is nil or is a typed nil, an error will be returned. -func (c *Cursor) Decode(val any) error { +func (c *Cursor) Decode(val interface{}) error { dec := getDecoder(c.Current, c.bsonOpts, c.registry) return dec.Decode(val) @@ -359,7 +289,7 @@ func (c *Cursor) Err() error { return c.err } // the first call, any subsequent calls will not change the state. func (c *Cursor) Close(ctx context.Context) error { defer c.closeImplicitSession() - return wrapErrors(c.bc.Close(ctx)) + return replaceErrors(c.bc.Close(ctx)) } // All iterates the cursor and decodes each document into results. The results parameter must be a pointer to a slice. @@ -368,7 +298,7 @@ func (c *Cursor) Close(ctx context.Context) error { // cursor has been iterated, any previously iterated documents will not be included in results. // // This method requires driver version >= 1.1.0. -func (c *Cursor) All(ctx context.Context, results any) error { +func (c *Cursor) All(ctx context.Context, results interface{}) error { resultsVal := reflect.ValueOf(results) if resultsVal.Kind() != reflect.Ptr { return fmt.Errorf("results argument must be a pointer to a slice, but was a %s", resultsVal.Kind()) @@ -406,7 +336,7 @@ func (c *Cursor) All(ctx context.Context, results any) error { batch = c.bc.Batch() } - if err = wrapErrors(c.bc.Err()); err != nil { + if err = replaceErrors(c.bc.Err()); err != nil { return err } @@ -477,7 +407,7 @@ func (c *Cursor) SetMaxAwaitTime(dur time.Duration) { // SetComment will set a user-configurable comment that can be used to identify // the operation in server logs. -func (c *Cursor) SetComment(comment any) { +func (c *Cursor) SetComment(comment interface{}) { c.bc.SetComment(comment) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go index e42097bb..414971c8 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go @@ -16,7 +16,6 @@ import ( "go.mongodb.org/mongo-driver/v2/internal/csfle" "go.mongodb.org/mongo-driver/v2/internal/csot" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/mongo/readconcern" @@ -111,15 +110,13 @@ func (db *Database) Name() string { return db.name } -// Collection returns a handle for a collection with the given name and options. -// -// If the collection does not exist on the server, it will be created when a -// write operation is performed. +// Collection gets a handle for a collection with the given name configured with the given CollectionOptions. func (db *Database) Collection(name string, opts ...options.Lister[options.CollectionOptions]) *Collection { return newCollection(db, name, opts...) } -// Aggregate executes an aggregate command the database. +// Aggregate executes an aggregate command the database. This requires MongoDB version >= 3.6 and driver version >= +// 1.1.0. // // The pipeline parameter must be a slice of documents, each representing an aggregation stage. The pipeline // cannot be nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, the @@ -132,7 +129,7 @@ func (db *Database) Collection(name string, opts ...options.Lister[options.Colle // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/aggregate/. func (db *Database) Aggregate( ctx context.Context, - pipeline any, + pipeline interface{}, opts ...options.Lister[options.AggregateOptions], ) (*Cursor, error) { a := aggregateParams{ @@ -154,7 +151,7 @@ func (db *Database) Aggregate( func (db *Database) processRunCommand( ctx context.Context, - cmd any, + cmd interface{}, cursorCommand bool, opts ...options.Lister[options.RunCmdOptions], ) (*operation.Command, *session.Client, error) { @@ -237,7 +234,7 @@ func (db *Database) processRunCommand( // - maxTimeMS when Timeout is set on the Client func (db *Database) RunCommand( ctx context.Context, - runCommand any, + runCommand interface{}, opts ...options.Lister[options.RunCmdOptions], ) *SingleResult { if ctx == nil { @@ -279,7 +276,7 @@ func (db *Database) RunCommand( // - maxTimeMS when Timeout is set on the Client func (db *Database) RunCommandCursor( ctx context.Context, - runCommand any, + runCommand interface{}, opts ...options.Lister[options.RunCmdOptions], ) (*Cursor, error) { if ctx == nil { @@ -289,7 +286,7 @@ func (db *Database) RunCommandCursor( op, sess, err := db.processRunCommand(ctx, runCommand, true, opts...) if err != nil { closeImplicitSession(sess) - return nil, wrapErrors(err) + return nil, replaceErrors(err) } if err = op.Execute(ctx); err != nil { @@ -298,17 +295,16 @@ func (db *Database) RunCommandCursor( return nil, errors.New( "database response does not contain a cursor; try using RunCommand instead") } - return nil, wrapErrors(err) + return nil, replaceErrors(err) } bc, err := op.ResultCursor() if err != nil { closeImplicitSession(sess) - return nil, wrapErrors(err) + return nil, replaceErrors(err) } - cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess, - withCursorOptionClientTimeout(db.client.timeout)) - return cursor, wrapErrors(err) + cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess) + return cursor, replaceErrors(err) } // Drop drops the database on the server. This method ignores "namespace not found" errors so it is safe to drop @@ -347,9 +343,9 @@ func (db *Database) Drop(ctx context.Context) error { err = op.Execute(ctx) - var driverErr driver.Error - if err != nil && (!errors.As(err, &driverErr) || !driverErr.NamespaceNotFound()) { - return wrapErrors(err) + driverErr, ok := err.(driver.Error) + if err != nil && (!ok || !driverErr.NamespaceNotFound()) { + return replaceErrors(err) } return nil } @@ -367,7 +363,7 @@ func (db *Database) Drop(ctx context.Context) error { // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/listCollections/. func (db *Database) ListCollectionSpecifications( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.ListCollectionsOptions], ) ([]CollectionSpecification, error) { cursor, err := db.ListCollections(ctx, filter, opts...) @@ -430,7 +426,7 @@ func (db *Database) ListCollectionSpecifications( // MongoDB version 2.6. func (db *Database) ListCollections( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.ListCollectionsOptions], ) (*Cursor, error) { if ctx == nil { @@ -489,11 +485,6 @@ func (db *Database) ListCollections( if args.AuthorizedCollections != nil { op = op.AuthorizedCollections(*args.AuthorizedCollections) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if db.client.retryReads { @@ -504,17 +495,16 @@ func (db *Database) ListCollections( err = op.Execute(ctx) if err != nil { closeImplicitSession(sess) - return nil, wrapErrors(err) + return nil, replaceErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { closeImplicitSession(sess) - return nil, wrapErrors(err) + return nil, replaceErrors(err) } - cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess, - withCursorOptionClientTimeout(db.client.timeout)) - return cursor, wrapErrors(err) + cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess) + return cursor, replaceErrors(err) } // ListCollectionNames executes a listCollections command and returns a slice containing the names of the collections @@ -533,7 +523,7 @@ func (db *Database) ListCollections( // MongoDB version 2.6. func (db *Database) ListCollectionNames( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.ListCollectionsOptions], ) ([]string, error) { opts = append(opts, options.ListCollections().SetNameOnly(true)) @@ -577,7 +567,7 @@ func (db *Database) ListCollectionNames( // // The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptions // documentation). -func (db *Database) Watch(ctx context.Context, pipeline any, +func (db *Database) Watch(ctx context.Context, pipeline interface{}, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { csConfig := changeStreamConfig{ @@ -593,15 +583,14 @@ func (db *Database) Watch(ctx context.Context, pipeline any, return newChangeStream(ctx, csConfig, pipeline, opts...) } -// CreateCollection creates a new collection on the server with the specified -// name and options. +// CreateCollection executes a create command to explicitly create a new collection with the specified name on the +// server. If the collection being created already exists, this method will return a mongo.CommandError. This method +// requires driver version 1.4.0 or higher. // -// MongoDB versions < 7.0 will return an error if the collection already exists. -// MongoDB versions >= 7.0 will not return an error if an existing collection -// created with the same name and options already exists. +// The opts parameter can be used to specify options for the operation (see the options.CreateCollectionOptions +// documentation). // -// For more information about the command, see -// https://www.mongodb.com/docs/manual/reference/command/create/. +// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/create/. func (db *Database) CreateCollection(ctx context.Context, name string, opts ...options.Lister[options.CreateCollectionOptions]) error { args, err := mongoutil.NewOptions(opts...) if err != nil { @@ -624,7 +613,7 @@ func (db *Database) CreateCollection(ctx context.Context, name string, opts ...o // getEncryptedFieldsFromServer tries to get an "encryptedFields" document associated with collectionName by running the "listCollections" command. // Returns nil and no error if the listCollections command succeeds, but "encryptedFields" is not present. -func (db *Database) getEncryptedFieldsFromServer(ctx context.Context, collectionName string) (any, error) { +func (db *Database) getEncryptedFieldsFromServer(ctx context.Context, collectionName string) (interface{}, error) { // Check if collection has an EncryptedFields configured server-side. collSpecs, err := db.ListCollectionSpecifications(ctx, bson.D{{"name", collectionName}}) if err != nil { @@ -654,7 +643,7 @@ func (db *Database) getEncryptedFieldsFromServer(ctx context.Context, collection // getEncryptedFieldsFromMap tries to get an "encryptedFields" document associated with collectionName by checking the client EncryptedFieldsMap. // Returns nil and no error if an EncryptedFieldsMap is not configured, or does not contain an entry for collectionName. -func (db *Database) getEncryptedFieldsFromMap(collectionName string) any { +func (db *Database) getEncryptedFieldsFromMap(collectionName string) interface{} { // Check the EncryptedFieldsMap efMap := db.client.encryptedFieldsMap if efMap == nil { @@ -674,7 +663,7 @@ func (db *Database) getEncryptedFieldsFromMap(collectionName string) any { func (db *Database) createCollectionWithEncryptedFields( ctx context.Context, name string, - ef any, + ef interface{}, opts ...options.Lister[options.CreateCollectionOptions], ) error { efBSON, err := marshal(ef, db.bsonOpts, db.registry) @@ -884,21 +873,20 @@ func (db *Database) createCollectionOperation( return op, nil } -// CreateView creates a view on the server. +// CreateView executes a create command to explicitly create a view on the server. See +// https://www.mongodb.com/docs/manual/core/views/ for more information about views. This method requires driver version >= +// 1.4.0 and MongoDB version >= 3.4. +// +// The viewName parameter specifies the name of the view to create. // -// The viewName parameter specifies the name of the view to create. The viewOn -// parameter specifies the name of the collection or view on which this view -// will be created. The pipeline parameter specifies an aggregation pipeline -// that will be exececuted against the source collection or view to create this -// view. +// # The viewOn parameter specifies the name of the collection or view on which this view will be created // -// MongoDB versions < 7.0 will return an error if the view already exists. -// MongoDB versions >= 7.0 will not return an error if an existing view created -// with the same name and options already exists. +// The pipeline parameter specifies an aggregation pipeline that will be exececuted against the source collection or +// view to create this view. // -// See https://www.mongodb.com/docs/manual/core/views/ for more information -// about views. -func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline any, +// The opts parameter can be used to specify options for the operation (see the options.CreateViewOptions +// documentation). +func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline interface{}, opts ...options.Lister[options.CreateViewOptions]) error { pipelineArray, _, err := marshalAggregatePipeline(pipeline, db.bsonOpts, db.registry) @@ -952,7 +940,7 @@ func (db *Database) executeCreateOperation(ctx context.Context, op *operation.Cr Deployment(db.client.deployment). Crypt(db.client.cryptFLE) - return wrapErrors(op.Execute(ctx)) + return replaceErrors(op.Execute(ctx)) } // GridFSBucket is used to construct a GridFS bucket which can be used as a diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go index 3756d58f..21e06b06 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go @@ -73,8 +73,8 @@ // if err != nil { return err } // // do something with result... // -// All Client, Collection, and Database methods that take parameters of type any -// will return ErrNilDocument if nil is passed in for an any. +// 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. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go index 234445ab..07d713fd 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go @@ -12,7 +12,6 @@ import ( "errors" "fmt" "net" - "reflect" "strings" "go.mongodb.org/mongo-driver/v2/bson" @@ -25,35 +24,17 @@ import ( // ErrClientDisconnected is returned when disconnected Client is used to run an operation. var ErrClientDisconnected = errors.New("client is disconnected") -// InvalidArgumentError wraps an invalid argument error. -type InvalidArgumentError struct { - wrapped error -} - -// Error implements the error interface. -func (e InvalidArgumentError) Error() string { - return e.wrapped.Error() -} - -// Unwrap returns the underlying error. -func (e InvalidArgumentError) Unwrap() error { - return e.wrapped -} - -// ErrMultipleIndexDrop is returned if multiple indexes would be dropped from a call to IndexView.DropOne. -var ErrMultipleIndexDrop error = InvalidArgumentError{errors.New("multiple indexes would be dropped")} - // ErrNilDocument is returned when a nil document is passed to a CRUD method. -var ErrNilDocument error = InvalidArgumentError{errors.New("document is nil")} +var ErrNilDocument = errors.New("document is nil") // ErrNilValue is returned when a nil value is passed to a CRUD method. -var ErrNilValue error = InvalidArgumentError{errors.New("value is nil")} +var ErrNilValue = errors.New("value is nil") // ErrEmptySlice is returned when an empty slice is passed to a CRUD method that requires a non-empty slice. -var ErrEmptySlice error = InvalidArgumentError{errors.New("must provide at least one element in input slice")} +var ErrEmptySlice = errors.New("must provide at least one element in input slice") // ErrNotSlice is returned when a type other than slice is passed to InsertMany. -var ErrNotSlice error = InvalidArgumentError{errors.New("must provide a non-empty slice")} +var ErrNotSlice = errors.New("must provide a non-empty slice") // ErrMapForOrderedArgument is returned when a map with multiple keys is passed to a CRUD method for an ordered parameter type ErrMapForOrderedArgument struct { @@ -65,11 +46,7 @@ func (e ErrMapForOrderedArgument) Error() string { return fmt.Sprintf("multi-key map passed in for ordered parameter %v", e.ParamName) } -// wrapErrors wraps error types and values that are defined in "internal" and -// "x" packages with error types and values that are defined in this package. -// That allows users to inspect the errors using errors.Is/errors.As without -// relying on "internal" or "x" packages. -func wrapErrors(err error) error { +func replaceErrors(err error) error { // Return nil when err is nil to avoid costly reflection logic below. if err == nil { return nil @@ -80,45 +57,29 @@ func wrapErrors(err error) error { // ignored. For non-DDL write commands (insert, update, etc), acknowledgement // should be be propagated at the result-level: e.g., // SingleResult.Acknowledged. - if errors.Is(err, driver.ErrUnacknowledgedWrite) { + if err == driver.ErrUnacknowledgedWrite { return nil } + if errors.Is(err, topology.ErrTopologyClosed) { return ErrClientDisconnected } - - var de driver.Error - if errors.As(err, &de) { + if de, ok := err.(driver.Error); ok { return CommandError{ Code: de.Code, Message: de.Message, Labels: de.Labels, Name: de.Name, - Wrapped: err, + Wrapped: de.Wrapped, Raw: bson.Raw(de.Raw), - - // Set wrappedMsgOnly=true here so that the Code and Message are not - // repeated multiple times in the error string. We expect that the - // wrapped driver.Error already contains that info in the error - // string. - wrappedMsgOnly: true, } } - - var qe driver.QueryFailureError - if errors.As(err, &qe) { + if qe, ok := err.(driver.QueryFailureError); ok { // qe.Message is "command failure" ce := CommandError{ Name: qe.Message, - Wrapped: err, + Wrapped: qe.Wrapped, Raw: bson.Raw(qe.Response), - - // Don't set wrappedMsgOnly=true here because the code below adds - // additional error context that is not provided by the - // driver.QueryFailureError. Additionally, driver.QueryFailureError - // is only returned when parsing OP_QUERY replies (OP_REPLY), so - // it's unlikely this block will ever be run now that MongoDB 3.6 is - // no longer supported. } dollarErr, err := qe.Response.LookupErr("$err") @@ -132,37 +93,18 @@ func wrapErrors(err error) error { return ce } - - var me mongocrypt.Error - if errors.As(err, &me) { - return MongocryptError{ - Code: me.Code, - Message: me.Message, - wrapped: err, - - // Set wrappedMsgOnly=true here so that the Code and Message are not - // repeated multiple times in the error string. We expect that the - // wrapped mongocrypt.Error already contains that info in the error - // string. - wrappedMsgOnly: true, - } + if me, ok := err.(mongocrypt.Error); ok { + return MongocryptError{Code: me.Code, Message: me.Message} } if errors.Is(err, codecutil.ErrNilValue) { return ErrNilValue } - var marshalErr codecutil.MarshalError - if errors.As(err, &marshalErr) { + if marshalErr, ok := err.(codecutil.MarshalError); ok { return MarshalError{ Value: marshalErr.Value, - Err: err, - - // Set wrappedMsgOnly=true here so that the Value is not repeated - // multiple times in the error string. We expect that the wrapped - // codecutil.MarshalError already contains that info in the error - // string. - wrappedMsgOnly: true, + Err: marshalErr.Err, } } @@ -235,67 +177,17 @@ func IsNetworkError(err error) bool { return errorHasLabel(err, "NetworkError") } -// MarshalError is returned when attempting to marshal a value into a document -// results in an error. -type MarshalError struct { - Value any - Err error - - // If wrappedMsgOnly is true, Error() only returns the error message from - // the "Err" error. - // - // This is typically only set by the wrapErrors function, which uses - // MarshalError to wrap codecutil.MarshalError, allowing users to access the - // "Value" from the underlying error but preventing duplication in the error - // string. - wrappedMsgOnly bool -} - -// Error implements the error interface. -func (me MarshalError) Error() string { - // If the MarshalError was created with wrappedMsgOnly=true, only return the - // error from the wrapped error. See the MarshalError.wrappedMsgOnly docs - // for more info. - if me.wrappedMsgOnly { - return me.Err.Error() - } - - return fmt.Sprintf("cannot marshal type %s to a BSON Document: %v", reflect.TypeOf(me.Value), me.Err) -} - -func (me MarshalError) Unwrap() error { return me.Err } - // MongocryptError represents an libmongocrypt error during in-use encryption. type MongocryptError struct { Code int32 Message string - wrapped error - - // If wrappedMsgOnly is true, Error() only returns the error message from - // the "wrapped" error. - // - // This is typically only set by the wrapErrors function, which uses - // MarshalError to wrap mongocrypt.Error, allowing users to access the - // "Code" and "Message" from the underlying error but preventing duplication - // in the error string. - wrappedMsgOnly bool } // Error implements the error interface. func (m MongocryptError) Error() string { - // If the MongocryptError was created with wrappedMsgOnly=true, only return - // the error from the wrapped error. See the MongocryptError.wrappedMsgOnly - // docs for more info. - if m.wrappedMsgOnly { - return m.wrapped.Error() - } - return fmt.Sprintf("mongocrypt error %d: %v", m.Code, m.Message) } -// Unwrap returns the underlying error. -func (m MongocryptError) Unwrap() error { return m.wrapped } - // EncryptionKeyVaultError represents an error while communicating with the key vault collection during in-use // encryption. type EncryptionKeyVaultError struct { @@ -379,38 +271,14 @@ type CommandError struct { Name string // A human-readable name corresponding to the error code Wrapped error // The underlying error, if one exists. Raw bson.Raw // The original server response containing the error. - - // If wrappedMsgOnly is true, Error() only returns the error message from - // the "Wrapped" error. - // - // This is typically only set by the wrapErrors function, which uses - // CommandError to wrap driver.Error, allowing users to access the "Code", - // "Message", "Labels", "Name", and "Raw" from the underlying error but - // preventing duplication in the error string. - wrappedMsgOnly bool } // Error implements the error interface. func (e CommandError) Error() string { - // If the CommandError was created with wrappedMsgOnly=true, only return the - // error from the wrapped error. See the CommandError.wrappedMsgOnly docs - // for more info. - if e.wrappedMsgOnly { - return e.Wrapped.Error() - } - - var msg string if e.Name != "" { - msg += fmt.Sprintf("(%v)", e.Name) + return fmt.Sprintf("(%v) %v", e.Name, e.Message) } - if e.Message != "" { - msg += " " + e.Message - } - if e.Wrapped != nil { - msg += ": " + e.Wrapped.Error() - } - - return msg + return e.Message } // Unwrap returns the underlying error. @@ -853,13 +721,13 @@ func processWriteError(err error) (returnResult, error) { // ignored. For non-DDL write commands (insert, update, etc), acknowledgement // should be be propagated at the result-level: e.g., // SingleResult.Acknowledged. - if errors.Is(err, driver.ErrUnacknowledgedWrite) { + if err == driver.ErrUnacknowledgedWrite { return rrAllUnacknowledged, nil } - var wce driver.WriteCommandError - if !errors.As(err, &wce) { - return rrNone, wrapErrors(err) + wce, ok := err.(driver.WriteCommandError) + if !ok { + return rrNone, replaceErrors(err) } return rrMany, WriteException{ diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go index 74230770..8bb418ad 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go @@ -80,7 +80,7 @@ func (b *GridFSBucket) OpenUploadStream( // client-level timeout will be used to cap the lifetime of the stream. func (b *GridFSBucket) OpenUploadStreamWithID( ctx context.Context, - fileID any, + fileID interface{}, filename string, opts ...options.Lister[options.GridFSUploadOptions], ) (*GridFSUploadStream, error) { @@ -129,7 +129,7 @@ func (b *GridFSBucket) UploadFromStream( // client-level timeout will be used to cap the lifetime of the stream. func (b *GridFSBucket) UploadFromStreamWithID( ctx context.Context, - fileID any, + fileID interface{}, filename string, source io.Reader, opts ...options.Lister[options.GridFSUploadOptions], @@ -170,7 +170,7 @@ func (b *GridFSBucket) UploadFromStreamWithID( // The context provided to this method controls the entire lifetime of an // upload stream io.Writer. If the context does set a deadline, then the // client-level timeout will be used to cap the lifetime of the stream. -func (b *GridFSBucket) OpenDownloadStream(ctx context.Context, fileID any) (*GridFSDownloadStream, error) { +func (b *GridFSBucket) OpenDownloadStream(ctx context.Context, fileID interface{}) (*GridFSDownloadStream, error) { return b.openDownloadStream(ctx, bson.D{{"_id", fileID}}) } @@ -185,7 +185,7 @@ func (b *GridFSBucket) OpenDownloadStream(ctx context.Context, fileID any) (*Gri // The context provided to this method controls the entire lifetime of an // upload stream io.Writer. If the context does set a deadline, then the // client-level timeout will be used to cap the lifetime of the stream. -func (b *GridFSBucket) DownloadToStream(ctx context.Context, fileID any, stream io.Writer) (int64, error) { +func (b *GridFSBucket) DownloadToStream(ctx context.Context, fileID interface{}, stream io.Writer) (int64, error) { ds, err := b.OpenDownloadStream(ctx, fileID) if err != nil { return 0, err @@ -254,7 +254,7 @@ func (b *GridFSBucket) DownloadToStreamByName( // Delete deletes all chunks and metadata associated with the file with the // given file ID and runs the underlying delete operations with the provided // context. -func (b *GridFSBucket) Delete(ctx context.Context, fileID any) error { +func (b *GridFSBucket) Delete(ctx context.Context, fileID interface{}) error { ctx, cancel := csot.WithTimeout(ctx, b.db.client.timeout) defer cancel() @@ -274,7 +274,7 @@ func (b *GridFSBucket) Delete(ctx context.Context, fileID any) error { // runs the underlying find query with the provided context. func (b *GridFSBucket) Find( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.GridFSFindOptions], ) (*Cursor, error) { args, err := mongoutil.NewOptions[options.GridFSFindOptions](opts...) @@ -306,7 +306,7 @@ func (b *GridFSBucket) Find( } // Rename renames the stored file with the specified file ID. -func (b *GridFSBucket) Rename(ctx context.Context, fileID any, newFilename string) error { +func (b *GridFSBucket) Rename(ctx context.Context, fileID interface{}, newFilename string) error { res, err := b.filesColl.UpdateOne(ctx, bson.D{{"_id", fileID}}, bson.D{{"$set", bson.D{{"filename", newFilename}}}}, @@ -348,7 +348,7 @@ func (b *GridFSBucket) GetChunksCollection() *Collection { func (b *GridFSBucket) openDownloadStream( ctx context.Context, - filter any, + filter interface{}, opts ...options.Lister[options.FindOneOptions], ) (*GridFSDownloadStream, error) { ctx, cancel := csot.WithTimeout(ctx, b.db.client.timeout) @@ -398,12 +398,12 @@ func (b *GridFSBucket) downloadToStream(ds *GridFSDownloadStream, stream io.Writ return copied, ds.Close() } -func (b *GridFSBucket) deleteChunks(ctx context.Context, fileID any) error { +func (b *GridFSBucket) deleteChunks(ctx context.Context, fileID interface{}) error { _, err := b.chunksColl.DeleteMany(ctx, bson.D{{"files_id", fileID}}) return err } -func (b *GridFSBucket) findChunks(ctx context.Context, fileID any) (*Cursor, error) { +func (b *GridFSBucket) findChunks(ctx context.Context, fileID interface{}) (*Cursor, error) { chunksCursor, err := b.chunksColl.Find(ctx, bson.D{{"files_id", fileID}}, options.Find().SetSort(bson.D{{"n", 1}})) // sort by chunk index diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go index c7967b74..29df84cc 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go @@ -53,7 +53,7 @@ type GridFSDownloadStream struct { type GridFSFile struct { // ID is the file's ID. This will match the file ID specified when uploading the file. If an upload helper that // does not require a file ID was used, this field will be a bson.ObjectID. - ID any + ID interface{} // Length is the length of this file in bytes. Length int64 @@ -73,18 +73,16 @@ type GridFSFile struct { Metadata bson.Raw } -var _ bson.Unmarshaler = &GridFSFile{} - // findFileResponse is a temporary type used to unmarshal documents from the // files collection and can be transformed into a File instance. This type // exists to avoid adding BSON struct tags to the exported File type. type findFileResponse struct { - ID any `bson:"_id"` - Length int64 `bson:"length"` - ChunkSize int32 `bson:"chunkSize"` - UploadDate time.Time `bson:"uploadDate"` - Name string `bson:"filename"` - Metadata bson.Raw `bson:"metadata"` + ID interface{} `bson:"_id"` + Length int64 `bson:"length"` + ChunkSize int32 `bson:"chunkSize"` + UploadDate time.Time `bson:"uploadDate"` + Name string `bson:"filename"` + Metadata bson.Raw `bson:"metadata"` } func newFileFromResponse(resp findFileResponse) *GridFSFile { @@ -98,23 +96,6 @@ func newFileFromResponse(resp findFileResponse) *GridFSFile { } } -// UnmarshalBSON implements the bson.Unmarshaler interface. -func (f *GridFSFile) UnmarshalBSON(data []byte) error { - var temp findFileResponse - if err := bson.Unmarshal(data, &temp); err != nil { - return err - } - - f.ID = temp.ID - f.Length = temp.Length - f.ChunkSize = temp.ChunkSize - f.UploadDate = temp.UploadDate - f.Name = temp.Name - f.Metadata = temp.Metadata - - return nil -} - func newGridFSDownloadStream( ctx context.Context, cancel context.CancelFunc, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go index ba7883d9..c1f92774 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go @@ -29,7 +29,7 @@ var ErrStreamClosed = errors.New("stream is closed or aborted") // metadata. type GridFSUploadStream struct { *upload // chunk size and metadata - FileID any + FileID interface{} chunkIndex int chunksColl *Collection // collection to store file chunks @@ -48,7 +48,7 @@ func newUploadStream( ctx context.Context, cancel context.CancelFunc, up *upload, - fileID any, + fileID interface{}, filename string, chunks, files *Collection, ) *GridFSUploadStream { @@ -150,7 +150,7 @@ func (us *GridFSUploadStream) uploadChunks(ctx context.Context, uploadPartial bo numChunks = int(math.Floor(chunks)) } - docs := make([]any, numChunks) + docs := make([]interface{}, numChunks) begChunkIndex := us.chunkIndex for i := 0; i < us.bufferIndex; i += int(us.chunkSize) { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go index f8529c16..748957da 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go @@ -14,7 +14,6 @@ import ( "strconv" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/mongo/readpref" @@ -30,10 +29,11 @@ import ( var ErrInvalidIndexValue = errors.New("invalid index value") // ErrNonStringIndexName is returned if an index is created with a name that is not a string. -// -// Deprecated: it will be removed in the next major release var ErrNonStringIndexName = errors.New("index name must be a string") +// ErrMultipleIndexDrop is returned if multiple indexes would be dropped from a call to IndexView.DropOne. +var ErrMultipleIndexDrop = errors.New("multiple indexes would be dropped") + // IndexView is a type that can be used to create, drop, and list indexes on a collection. An IndexView for a collection // can be created by a call to Collection.Indexes(). type IndexView struct { @@ -45,12 +45,19 @@ type IndexModel struct { // A document describing which keys should be used for the index. It cannot be nil. This must be an order-preserving // type such as bson.D. Map types such as bson.M are not valid. See https://www.mongodb.com/docs/manual/indexes/#indexes // for examples of valid documents. - Keys any + Keys interface{} // The options to use to create the index. Options *options.IndexOptionsBuilder } +func isNamespaceNotFoundError(err error) bool { + if de, ok := err.(driver.Error); ok { + return de.Code == 26 + } + return false +} + // List executes a listIndexes command and returns a cursor over the indexes in the collection. // // The opts parameter can be used to specify options for this operation (see the options.ListIndexesOptions @@ -102,11 +109,6 @@ func (iv IndexView) List(ctx context.Context, opts ...options.Lister[options.Lis op = op.BatchSize(*args.BatchSize) cursorOpts.BatchSize = *args.BatchSize } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } retry := driver.RetryNone if iv.coll.client.retryReads { @@ -118,26 +120,20 @@ func (iv IndexView) List(ctx context.Context, opts ...options.Lister[options.Lis if err != nil { // for namespaceNotFound errors, return an empty cursor and do not throw an error closeImplicitSession(sess) - var de driver.Error - if errors.As(err, &de) && de.NamespaceNotFound() { + if isNamespaceNotFoundError(err) { return newEmptyCursor(), nil } - return nil, wrapErrors(err) + return nil, replaceErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { closeImplicitSession(sess) - return nil, wrapErrors(err) + return nil, replaceErrors(err) } - cursor, err := newCursorWithSession(bc, iv.coll.bsonOpts, iv.coll.registry, sess, - - // This value is included for completeness, but a server will never return - // a tailable awaitData cursor from a listIndexes operation. - withCursorOptionClientTimeout(iv.coll.client.timeout)) - - return cursor, wrapErrors(err) + cursor, err := newCursorWithSession(bc, iv.coll.bsonOpts, iv.coll.registry, sess) + return cursor, replaceErrors(err) } // ListSpecifications executes a List command and returns a slice of returned IndexSpecifications @@ -290,11 +286,6 @@ func (iv IndexView) CreateMany( op.CommitQuorum(commitQuorum) } - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } _, err = processWriteError(op.Execute(ctx)) if err != nil { @@ -392,12 +383,7 @@ func (iv IndexView) createOptionsDoc(opts options.Lister[options.IndexOptions]) return optsDoc, nil } -func (iv IndexView) drop(ctx context.Context, index any, opts ...options.Lister[options.DropIndexesOptions]) error { - args, err := mongoutil.NewOptions[options.DropIndexesOptions](opts...) - if err != nil { - return fmt.Errorf("failed to construct options from builder: %w", err) - } - +func (iv IndexView) drop(ctx context.Context, index any, _ ...options.Lister[options.DropIndexesOptions]) error { if ctx == nil { ctx = context.Background() } @@ -408,7 +394,7 @@ func (iv IndexView) drop(ctx context.Context, index any, opts ...options.Lister[ defer sess.EndSession() } - err = iv.coll.client.validSession(sess) + err := iv.coll.client.validSession(sess) if err != nil { return err } @@ -429,15 +415,9 @@ func (iv IndexView) drop(ctx context.Context, index any, opts ...options.Lister[ Deployment(iv.coll.client.deployment).ServerAPI(iv.coll.client.serverAPI). Timeout(iv.coll.client.timeout).Crypt(iv.coll.client.cryptFLE).Authenticator(iv.coll.client.authenticator) - if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { - if rawData, ok := rawDataOpt.(bool); ok { - op = op.RawData(rawData) - } - } - err = op.Execute(ctx) if err != nil { - return wrapErrors(err) + return replaceErrors(err) } return nil @@ -470,7 +450,7 @@ func (iv IndexView) DropOne( // DropWithKey drops a collection index by key using the dropIndexes operation. // // This function is useful to drop an index using its key specification instead of its name. -func (iv IndexView) DropWithKey(ctx context.Context, keySpecDocument any, opts ...options.Lister[options.DropIndexesOptions]) error { +func (iv IndexView) DropWithKey(ctx context.Context, keySpecDocument interface{}, opts ...options.Lister[options.DropIndexesOptions]) error { doc, err := marshal(keySpecDocument, iv.coll.bsonOpts, iv.coll.registry) if err != nil { return err diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go index 703115fd..260576bd 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go @@ -31,6 +31,18 @@ type Dialer interface { DialContext(ctx context.Context, network, address string) (net.Conn, error) } +// MarshalError is returned when attempting to marshal a value into a document +// results in an error. +type MarshalError struct { + Value interface{} + Err error +} + +// Error implements the error interface. +func (me MarshalError) Error() string { + return fmt.Sprintf("cannot marshal 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 // helper and is intended for serializing to BSON. // @@ -71,9 +83,6 @@ func getEncoder( if opts.OmitZeroStruct { enc.OmitZeroStruct() } - if opts.OmitEmpty { - enc.OmitEmpty() - } if opts.StringifyMapKeysWithFmt { enc.StringifyMapKeysWithFmt() } @@ -103,7 +112,7 @@ func newEncoderFn(opts *options.BSONOptions, registry *bson.Registry) codecutil. // If bsonOpts and registry are specified, the encoder is configured with the requested behaviors. // If they are nil, the default behaviors are used. func marshal( - val any, + val interface{}, bsonOpts *options.BSONOptions, registry *bson.Registry, ) (bsoncore.Document, error) { @@ -140,17 +149,17 @@ func ensureID( oid bson.ObjectID, bsonOpts *options.BSONOptions, reg *bson.Registry, -) (bsoncore.Document, any, error) { +) (bsoncore.Document, interface{}, error) { if reg == nil { reg = defaultRegistry } // Try to find the "_id" element. If it exists, try to unmarshal just the - // "_id" field as an any and return it along with the unmodified + // "_id" field as an interface{} and return it along with the unmodified // BSON document. if _, err := doc.LookupErr("_id"); err == nil { var id struct { - ID any `bson:"_id"` + ID interface{} `bson:"_id"` } dec := getDecoder(doc, bsonOpts, reg) err = dec.Decode(&id) @@ -205,7 +214,7 @@ func ensureNoDollarKey(doc bsoncore.Document) error { } func marshalAggregatePipeline( - pipeline any, + pipeline interface{}, bsonOpts *options.BSONOptions, registry *bson.Registry, ) (bsoncore.Document, bool, error) { @@ -293,7 +302,7 @@ func marshalAggregatePipeline( } func marshalUpdateValue( - update any, + update interface{}, bsonOpts *options.BSONOptions, registry *bson.Registry, dollarKeysAllowed bool, @@ -383,7 +392,7 @@ func marshalUpdateValue( } func marshalValue( - val any, + val interface{}, bsonOpts *options.BSONOptions, registry *bson.Registry, ) (bsoncore.Value, error) { @@ -392,7 +401,7 @@ func marshalValue( // Build the aggregation pipeline for the CountDocument command. func countDocumentsAggregatePipeline( - filter any, + filter interface{}, encOpts *options.BSONOptions, registry *bson.Registry, args *options.CountOptions, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go index 66aa12b9..9e6e9daf 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go @@ -132,7 +132,7 @@ func (mc *mongocryptdClient) spawnProcess() error { } // createSpawnArgs creates arguments to spawn mcryptClient. It returns the path and a slice of arguments. -func createSpawnArgs(opts map[string]any) (string, []string) { +func createSpawnArgs(opts map[string]interface{}) (string, []string) { var spawnArgs []string // get command path diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go index 58ca97d6..c49951dc 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go @@ -10,7 +10,6 @@ import ( "time" "go.mongodb.org/mongo-driver/v2/bson" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" ) // AggregateOptions represents arguments that can be used to configure an @@ -23,14 +22,10 @@ type AggregateOptions struct { BypassDocumentValidation *bool Collation *Collation MaxAwaitTime *time.Duration - Comment any - Hint any - Let any + Comment interface{} + Hint interface{} + Let interface{} Custom bson.M - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // AggregateOptionsBuilder contains options to configure aggregate operations. @@ -75,7 +70,8 @@ func (ao *AggregateOptionsBuilder) SetBatchSize(i int32) *AggregateOptionsBuilde } // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes -// executed as part of the operation will opt out of document-level validation on the server. The default value +// executed as part of the operation will opt out of document-level validation on the server. This +// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value // is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about // document validation. func (ao *AggregateOptionsBuilder) SetBypassDocumentValidation(b bool) *AggregateOptionsBuilder { @@ -88,8 +84,9 @@ func (ao *AggregateOptionsBuilder) SetBypassDocumentValidation(b bool) *Aggregat return ao } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For previous +// server versions, the driver will return an error if this option is used. The default value is nil, // which means the default collation of the collection will be used. func (ao *AggregateOptionsBuilder) SetCollation(c *Collation) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { @@ -102,7 +99,8 @@ func (ao *AggregateOptionsBuilder) SetCollation(c *Collation) *AggregateOptionsB } // SetMaxAwaitTime sets the value for the MaxAwaitTime field. Specifies maximum amount of time -// that the server should wait for new documents to satisfy a tailable cursor query. +// that the server should wait for new documents to satisfy a tailable cursor query. This option is +// only valid for MongoDB versions >= 3.2 and is ignored for previous server versions. func (ao *AggregateOptionsBuilder) SetMaxAwaitTime(d time.Duration) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.MaxAwaitTime = &d @@ -116,7 +114,7 @@ func (ao *AggregateOptionsBuilder) SetMaxAwaitTime(d time.Duration) *AggregateOp // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil, // which means that no comment will be included in the logs. -func (ao *AggregateOptionsBuilder) SetComment(comment any) *AggregateOptionsBuilder { +func (ao *AggregateOptionsBuilder) SetComment(comment interface{}) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.Comment = comment @@ -130,7 +128,7 @@ func (ao *AggregateOptionsBuilder) SetComment(comment any) *AggregateOptionsBuil // either be the index name as a string or the index specification as a document. The hint does not apply to // $lookup and $graphLookup aggregation stages. The driver will return an error if the hint parameter // is a multi-key map. The default value is nil, which means that no hint will be sent. -func (ao *AggregateOptionsBuilder) SetHint(h any) *AggregateOptionsBuilder { +func (ao *AggregateOptionsBuilder) SetHint(h interface{}) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.Hint = h @@ -145,7 +143,7 @@ func (ao *AggregateOptionsBuilder) SetHint(h any) *AggregateOptionsBuilder { // option. This must be a document mapping parameter names to values. Values must be constant or closed // expressions that do not reference document fields. Parameters can then be accessed as variables in // an aggregate expression context (e.g. "$$var"). -func (ao *AggregateOptionsBuilder) SetLet(let any) *AggregateOptionsBuilder { +func (ao *AggregateOptionsBuilder) SetLet(let interface{}) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.Let = let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go index db3508fb..c630659c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go @@ -9,7 +9,6 @@ package options import ( "crypto/tls" "net/http" - "time" "go.mongodb.org/mongo-driver/v2/internal/httputil" ) @@ -33,15 +32,14 @@ import ( type AutoEncryptionOptions struct { KeyVaultClientOptions *ClientOptions KeyVaultNamespace string - KmsProviders map[string]map[string]any - SchemaMap map[string]any + KmsProviders map[string]map[string]interface{} + SchemaMap map[string]interface{} BypassAutoEncryption *bool - ExtraOptions map[string]any + ExtraOptions map[string]interface{} TLSConfig map[string]*tls.Config HTTPClient *http.Client - EncryptedFieldsMap map[string]any + EncryptedFieldsMap map[string]interface{} BypassQueryAnalysis *bool - KeyExpiration *time.Duration } // AutoEncryption creates a new AutoEncryptionOptions configured with default values. @@ -74,7 +72,7 @@ func (a *AutoEncryptionOptions) SetKeyVaultNamespace(ns string) *AutoEncryptionO } // SetKmsProviders specifies options for KMS providers. This is required. -func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string]any) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string]interface{}) *AutoEncryptionOptions { a.KmsProviders = providers return a @@ -87,7 +85,7 @@ func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string] // Supplying a schemaMap provides more security than relying on JSON Schemas obtained from the server. It protects // against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted // data that should be encrypted. -func (a *AutoEncryptionOptions) SetSchemaMap(schemaMap map[string]any) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetSchemaMap(schemaMap map[string]interface{}) *AutoEncryptionOptions { a.SchemaMap = schemaMap return a @@ -136,7 +134,7 @@ func (a *AutoEncryptionOptions) SetBypassAutoEncryption(bypass bool) *AutoEncryp // absolute path to the directory containing the linked libmongocrypt library. Setting an override // path disables the default system library search path. If an override path is specified but the // crypt_shared library cannot be loaded, Client creation will return an error. Must be a string. -func (a *AutoEncryptionOptions) SetExtraOptions(extraOpts map[string]any) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetExtraOptions(extraOpts map[string]interface{}) *AutoEncryptionOptions { a.ExtraOptions = extraOpts return a @@ -153,7 +151,7 @@ func (a *AutoEncryptionOptions) SetTLSConfig(cfg map[string]*tls.Config) *AutoEn // SetEncryptedFieldsMap specifies a map from namespace to local EncryptedFieldsMap document. // EncryptedFieldsMap is used for Queryable Encryption. -func (a *AutoEncryptionOptions) SetEncryptedFieldsMap(ef map[string]any) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetEncryptedFieldsMap(ef map[string]interface{}) *AutoEncryptionOptions { a.EncryptedFieldsMap = ef return a @@ -166,11 +164,3 @@ func (a *AutoEncryptionOptions) SetBypassQueryAnalysis(bypass bool) *AutoEncrypt return a } - -// SetKeyExpiration specifies duration for the key expiration. 0 or negative value means "never expire". -// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up. -func (a *AutoEncryptionOptions) SetKeyExpiration(expiration time.Duration) *AutoEncryptionOptions { - a.KeyExpiration = &expiration - - return a -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go index cbdc7f48..11dd6c1b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go @@ -6,8 +6,6 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // DefaultOrdered is the default value for the Ordered option in BulkWriteOptions. var DefaultOrdered = true @@ -17,13 +15,9 @@ var DefaultOrdered = true // See corresponding setter methods for documentation. type BulkWriteOptions struct { BypassDocumentValidation *bool - Comment any + Comment interface{} Ordered *bool - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Let interface{} } // BulkWriteOptionsBuilder contains options to configure bulk write operations. @@ -49,7 +43,7 @@ func (b *BulkWriteOptionsBuilder) List() []func(*BulkWriteOptions) error { // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help tracethe operation. The default value is nil, // which means that no comment will be included in the logs. -func (b *BulkWriteOptionsBuilder) SetComment(comment any) *BulkWriteOptionsBuilder { +func (b *BulkWriteOptionsBuilder) SetComment(comment interface{}) *BulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error { opts.Comment = comment @@ -72,7 +66,8 @@ func (b *BulkWriteOptionsBuilder) SetOrdered(ordered bool) *BulkWriteOptionsBuil } // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes -// executed as part of the operation will opt out of document-level validation on the server. The default value is +// executed as part of the operation will opt out of document-level validation on the server. This option +// is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is // false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document // validation. func (b *BulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) *BulkWriteOptionsBuilder { @@ -89,7 +84,7 @@ func (b *BulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) *Bulk // This option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using this option. // This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not // reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (b *BulkWriteOptionsBuilder) SetLet(let any) *BulkWriteOptionsBuilder { +func (b *BulkWriteOptionsBuilder) SetLet(let interface{}) *BulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error { opts.Let = &let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go index 9e5bb93b..66f1899f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go @@ -18,14 +18,14 @@ import ( type ChangeStreamOptions struct { BatchSize *int32 Collation *Collation - Comment any + Comment interface{} FullDocument *FullDocument FullDocumentBeforeChange *FullDocument MaxAwaitTime *time.Duration - ResumeAfter any + ResumeAfter interface{} ShowExpandedEvents *bool StartAtOperationTime *bson.Timestamp - StartAfter any + StartAfter interface{} Custom bson.M CustomPipeline bson.M } @@ -57,9 +57,10 @@ func (cso *ChangeStreamOptionsBuilder) SetBatchSize(i int32) *ChangeStreamOption return cso } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string comparisons +// during the operation. This option is only valid for MongoDB versions >= 3.4. For previous server versions, +// the driver will return an error if this option is used. The default value is nil, which means the default +// collation of the collection will be used. func (cso *ChangeStreamOptionsBuilder) SetCollation(c Collation) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.Collation = &c @@ -71,7 +72,7 @@ func (cso *ChangeStreamOptionsBuilder) SetCollation(c Collation) *ChangeStreamOp // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil, // which means that no comment will be included in the logs. -func (cso *ChangeStreamOptionsBuilder) SetComment(comment any) *ChangeStreamOptionsBuilder { +func (cso *ChangeStreamOptionsBuilder) SetComment(comment interface{}) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.Comment = comment return nil @@ -114,7 +115,7 @@ func (cso *ChangeStreamOptionsBuilder) SetMaxAwaitTime(d time.Duration) *ChangeS // SetResumeAfter sets the value for the ResumeAfter field. Specifies a document specifying the logical starting // point for the change stream. Only changes corresponding to an oplog entry immediately after the resume token // will be returned. If this is specified, StartAtOperationTime and StartAfter must not be set. -func (cso *ChangeStreamOptionsBuilder) SetResumeAfter(rt any) *ChangeStreamOptionsBuilder { +func (cso *ChangeStreamOptionsBuilder) SetResumeAfter(rt interface{}) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.ResumeAfter = rt return nil @@ -151,7 +152,7 @@ func (cso *ChangeStreamOptionsBuilder) SetStartAtOperationTime(t *bson.Timestamp // the collection has been dropped and recreated or renamed. Only changes corresponding to an oplog entry // immediately after the specified token will be returned. If this is specified, ResumeAfter and // StartAtOperationTime must not be set. This option is only valid for MongoDB versions >= 4.1.1. -func (cso *ChangeStreamOptionsBuilder) SetStartAfter(sa any) *ChangeStreamOptionsBuilder { +func (cso *ChangeStreamOptionsBuilder) SetStartAfter(sa interface{}) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.StartAfter = sa return nil diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go index 90d6c241..a55ac27f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go @@ -7,7 +7,6 @@ package options import ( - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" ) @@ -16,15 +15,11 @@ import ( // See corresponding setter methods for documentation. type ClientBulkWriteOptions struct { BypassDocumentValidation *bool - Comment any + Comment interface{} Ordered *bool - Let any + Let interface{} WriteConcern *writeconcern.WriteConcern VerboseResults *bool - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // ClientBulkWriteOptionsBuilder contains options to configure client-level bulk @@ -51,7 +46,7 @@ func (b *ClientBulkWriteOptionsBuilder) List() []func(*ClientBulkWriteOptions) e // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help tracethe operation. The default value is nil, // which means that no comment will be included in the logs. -func (b *ClientBulkWriteOptionsBuilder) SetComment(comment any) *ClientBulkWriteOptionsBuilder { +func (b *ClientBulkWriteOptionsBuilder) SetComment(comment interface{}) *ClientBulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error { opts.Comment = comment @@ -90,7 +85,7 @@ func (b *ClientBulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) // SetLet sets the value for the Let field. Let specifies parameters for all update and delete commands in the BulkWrite. // This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not // reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (b *ClientBulkWriteOptionsBuilder) SetLet(let any) *ClientBulkWriteOptionsBuilder { +func (b *ClientBulkWriteOptionsBuilder) SetLet(let interface{}) *ClientBulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error { opts.Let = &let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go index a6c477a7..3f9b3745 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go @@ -10,7 +10,6 @@ import ( "crypto/tls" "fmt" "net/http" - "time" "go.mongodb.org/mongo-driver/v2/internal/httputil" ) @@ -20,10 +19,9 @@ import ( // See corresponding setter methods for documentation. type ClientEncryptionOptions struct { KeyVaultNamespace string - KmsProviders map[string]map[string]any + KmsProviders map[string]map[string]interface{} TLSConfig map[string]*tls.Config HTTPClient *http.Client - KeyExpiration *time.Duration } // ClientEncryptionOptionsBuilder contains options to configure client @@ -60,7 +58,7 @@ func (c *ClientEncryptionOptionsBuilder) SetKeyVaultNamespace(ns string) *Client } // SetKmsProviders specifies options for KMS providers. This is required. -func (c *ClientEncryptionOptionsBuilder) SetKmsProviders(providers map[string]map[string]any) *ClientEncryptionOptionsBuilder { +func (c *ClientEncryptionOptionsBuilder) SetKmsProviders(providers map[string]map[string]interface{}) *ClientEncryptionOptionsBuilder { c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error { opts.KmsProviders = providers return nil @@ -82,18 +80,6 @@ func (c *ClientEncryptionOptionsBuilder) SetTLSConfig(cfg map[string]*tls.Config return c } -// SetKeyExpiration specifies duration for the key expiration. 0 or negative value means "never expire". -// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up. -func (c *ClientEncryptionOptionsBuilder) SetKeyExpiration(expiration time.Duration) *ClientEncryptionOptionsBuilder { - c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error { - opts.KeyExpiration = &expiration - - return nil - }) - - return c -} - // BuildTLSConfig specifies tls.Config options for each KMS provider to use to configure TLS on all connections created // to the KMS provider. The input map should contain a mapping from each KMS provider to a document containing the necessary // options, as follows: @@ -117,7 +103,7 @@ func (c *ClientEncryptionOptionsBuilder) SetKeyExpiration(expiration time.Durati // to be considered trusted when making a TLS connection (e.g. "tlsCaFile=/path/to/caFile"). // // This should only be used to set custom TLS options. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12. -func BuildTLSConfig(tlsOpts map[string]any) (*tls.Config, error) { +func BuildTLSConfig(tlsOpts map[string]interface{}) (*tls.Config, error) { // use TLS min version 1.2 to enforce more secure hash algorithms and advanced cipher suites cfg := &tls.Config{MinVersion: tls.VersionTLS12} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go index adc880a5..9623562e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go @@ -26,7 +26,6 @@ import ( "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/httputil" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/mongo/readconcern" "go.mongodb.org/mongo-driver/v2/mongo/readpref" "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" @@ -68,7 +67,7 @@ type ContextDialer interface { // Credential can be used to provide authentication options when configuring a Client. // // AuthMechanism: the mechanism to use for authentication. Supported values include "SCRAM-SHA-256", "SCRAM-SHA-1", -// "PLAIN", "GSSAPI", "MONGODB-X509", and "MONGODB-AWS". This can also be set through the "authMechanism" +// "MONGODB-CR", "PLAIN", "GSSAPI", "MONGODB-X509", and "MONGODB-AWS". This can also be set through the "authMechanism" // URI option. (e.g. "authMechanism=PLAIN"). For more information, see // https://www.mongodb.com/docs/manual/core/authentication-mechanisms/. // @@ -183,12 +182,9 @@ type BSONOptions struct { // OmitZeroStruct causes the driver to consider the zero value for a struct // (e.g. MyStruct{}) as empty and omit it from the marshaled BSON when the - // "omitempty" struct tag option or the "OmitEmpty" field is set. + // "omitempty" struct tag option is set. OmitZeroStruct bool - // OmitEmpty causes the driver to omit empty values from the marshaled BSON. - OmitEmpty bool - // StringifyMapKeysWithFmt causes the driver to convert Go map keys to BSON // document field name strings using fmt.Sprint instead of the default // string conversion logic. @@ -207,7 +203,7 @@ type BSONOptions struct { // DefaultDocumentM causes the driver to always unmarshal documents into the // bson.M type. This behavior is restricted to data typed as - // "any" or "map[string]any". + // "interface{}" or "map[string]interface{}". DefaultDocumentM bool // ObjectIDAsHexString causes the Decoder to decode object IDs to their hex @@ -287,22 +283,14 @@ type ClientOptions struct { // encryption. // // Deprecated: This option is for internal use only and should not be set (see GODRIVER-2149). It may be - // changed in any release. This option will be removed in 3.0 and replaced with the Custom options.Options - // pattern: SetInternalClientOptions(clientOptions, "crypt", myCrypt) + // changed or removed in any release. Crypt driver.Crypt // Deployment specifies a custom deployment to use for the new Client. // - // Deprecated: This option is for internal use only and should not be set. It may be changed in any release. - // This option will be removed in 3.0 and replaced with the Custom options.Options pattern: - // SetInternalClientOptions(clientOptions, "deployment", myDeployment) - Deployment driver.Deployment - - // Custom specifies internal options for the new Client. - // // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any // release. - Custom optionsutil.Options + Deployment driver.Deployment connString *connstring.ConnString err error @@ -311,7 +299,7 @@ type ClientOptions struct { // Client creates a new ClientOptions instance. func Client() *ClientOptions { opts := &ClientOptions{} - opts = opts.SetHTTPClient(httputil.NewHTTPClient()) + opts = opts.SetHTTPClient(httputil.DefaultHTTPClient) return opts } @@ -605,45 +593,24 @@ func (c *ClientOptions) Validate() error { return fmt.Errorf("cannot set both OIDCMachineCallback and OIDCHumanCallback, only one may be specified") } if c.Auth.OIDCHumanCallback == nil && c.Auth.AuthMechanismProperties[auth.AllowedHostsProp] != "" { - return fmt.Errorf("cannot specify ALLOWED_HOSTS without an OIDCHumanCallback") - } - if c.Auth.OIDCMachineCallback == nil && c.Auth.OIDCHumanCallback == nil && c.Auth.AuthMechanismProperties[auth.EnvironmentProp] == "" { - return errors.New("must specify at least one of OIDCMachineCallback, OIDCHumanCallback, or ENVIRONMENT authMechanismProperty") - } - - // Return an error if an unsupported authMechanismProperty is specified - // for MONGODB-OIDC. - for prop := range c.Auth.AuthMechanismProperties { - switch prop { - case auth.AllowedHostsProp, auth.EnvironmentProp, auth.ResourceProp: - default: - return fmt.Errorf("auth mechanism property %q is not valid for MONGODB-OIDC", prop) - } + return fmt.Errorf("Cannot specify ALLOWED_HOSTS without an OIDCHumanCallback") } - if env, ok := c.Auth.AuthMechanismProperties[auth.EnvironmentProp]; ok { switch env { case auth.GCPEnvironmentValue, auth.AzureEnvironmentValue: - if c.Auth.AuthMechanismProperties[auth.ResourceProp] == "" { - return fmt.Errorf("%q must be set for the %s %q", auth.ResourceProp, env, auth.EnvironmentProp) - } - fallthrough - case auth.K8SEnvironmentValue: if c.Auth.OIDCMachineCallback != nil { return fmt.Errorf("OIDCMachineCallback cannot be specified with the %s %q", env, auth.EnvironmentProp) } if c.Auth.OIDCHumanCallback != nil { return fmt.Errorf("OIDCHumanCallback cannot be specified with the %s %q", env, auth.EnvironmentProp) } - case auth.TestEnvironmentValue: + if c.Auth.AuthMechanismProperties[auth.ResourceProp] == "" { + return fmt.Errorf("%q must be set for the %s %q", auth.ResourceProp, env, auth.EnvironmentProp) + } + default: if c.Auth.AuthMechanismProperties[auth.ResourceProp] != "" { return fmt.Errorf("%q must not be set for the %s %q", auth.ResourceProp, env, auth.EnvironmentProp) } - if c.Auth.Username != "" { - return fmt.Errorf("must not specify username for %s %q", env, auth.EnvironmentProp) - } - default: - return fmt.Errorf("the %s %q is not supported for MONGODB-OIDC", env, auth.EnvironmentProp) } } } @@ -695,9 +662,9 @@ func (c *ClientOptions) SetAuth(auth Credential) *ClientOptions { // SetCompressors sets the compressors that can be used when communicating with a server. Valid values are: // -// 1. "snappy" +// 1. "snappy" - requires server version >= 3.4 // -// 2. "zlib" +// 2. "zlib" - requires server version >= 3.6 // // 3. "zstd" - requires server version >= 4.2, and driver version >= 1.2.0 with cgo support enabled or driver // version >= 1.3.0 without cgo. @@ -929,8 +896,9 @@ func (c *ClientOptions) SetReplicaSet(s string) *ClientOptions { // DeleteManyModel instances to be considered retryable. Unacknowledged writes will not be retried, even if this option // is set to true. // -// This option only works on a replica set or sharded cluster and will be ignored for any other cluster type. -// This can also be set through the "retryWrites" URI option (e.g. "retryWrites=true"). The default is true. +// This option requires server version >= 3.6 and a replica set or sharded cluster and will be ignored for any other +// cluster type. This can also be set through the "retryWrites" URI option (e.g. "retryWrites=true"). The default is +// true. func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions { c.RetryWrites = &b @@ -944,7 +912,7 @@ func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions { // EstimatedDocumentCount, Watch (for Client, Database, and Collection), ListCollections, and ListDatabases. Note that // operations run through RunCommand are not retried. // -// The default is true. +// This option requires server version >= 3.6 and driver version >= 1.1.0. The default is true. func (c *ClientOptions) SetRetryReads(b bool) *ClientOptions { c.RetryReads = &b diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go index 9cf5924a..8f92b62f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go @@ -6,22 +6,16 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // CountOptions represents arguments that can be used to configure a // CountDocuments operation. // // See corresponding setter methods for documentation. type CountOptions struct { Collation *Collation - Comment any - Hint any + Comment interface{} + Hint interface{} Limit *int64 Skip *int64 - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // CountOptionsBuilder contains options to configure count operations. Each @@ -41,9 +35,10 @@ func (co *CountOptionsBuilder) List() []func(*CountOptions) error { return co.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string comparisons +// during the operation. This option is only valid for MongoDB versions >= 3.4. For previous server versions, +// the driver will return an error if this option is used. The default value is nil, which means the default +// collation of the collection will be used. func (co *CountOptionsBuilder) SetCollation(c *Collation) *CountOptionsBuilder { co.Opts = append(co.Opts, func(opts *CountOptions) error { opts.Collation = c @@ -57,7 +52,7 @@ func (co *CountOptionsBuilder) SetCollation(c *Collation) *CountOptionsBuilder { // SetComment sets the value for the Comment field. Specifies a string or document that will be included // in server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil, // which means that no comment will be included in the logs. -func (co *CountOptionsBuilder) SetComment(comment any) *CountOptionsBuilder { +func (co *CountOptionsBuilder) SetComment(comment interface{}) *CountOptionsBuilder { co.Opts = append(co.Opts, func(opts *CountOptions) error { opts.Comment = comment @@ -71,7 +66,7 @@ func (co *CountOptionsBuilder) SetComment(comment any) *CountOptionsBuilder { // either be the index name as a string or the index specification as a document. The driver will return // an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint // will be sent. -func (co *CountOptionsBuilder) SetHint(h any) *CountOptionsBuilder { +func (co *CountOptionsBuilder) SetHint(h interface{}) *CountOptionsBuilder { co.Opts = append(co.Opts, func(opts *CountOptions) error { opts.Hint = h diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go index 4bac0d04..fd0aad57 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go @@ -16,7 +16,7 @@ import ( // // See corresponding setter methods for documentation. type DefaultIndexOptions struct { - StorageEngine any + StorageEngine interface{} } // DefaultIndexOptionsBuilder contains options to configure default index @@ -39,7 +39,7 @@ func (d *DefaultIndexOptionsBuilder) List() []func(*DefaultIndexOptions) error { // SetStorageEngine sets the value for the StorageEngine field. Specifies the storage engine to use for // the index. The value must be a document in the form {: }. The default // value is nil, which means that the default storage engine will be used. -func (d *DefaultIndexOptionsBuilder) SetStorageEngine(storageEngine any) *DefaultIndexOptionsBuilder { +func (d *DefaultIndexOptionsBuilder) SetStorageEngine(storageEngine interface{}) *DefaultIndexOptionsBuilder { d.Opts = append(d.Opts, func(opts *DefaultIndexOptions) error { opts.StorageEngine = storageEngine @@ -149,18 +149,18 @@ func (tso *TimeSeriesOptionsBuilder) SetBucketRounding(dur time.Duration) *TimeS type CreateCollectionOptions struct { Capped *bool Collation *Collation - ChangeStreamPreAndPostImages any + ChangeStreamPreAndPostImages interface{} DefaultIndexOptions *DefaultIndexOptionsBuilder MaxDocuments *int64 SizeInBytes *int64 - StorageEngine any + StorageEngine interface{} ValidationAction *string ValidationLevel *string - Validator any + Validator interface{} ExpireAfterSeconds *int64 TimeSeriesOptions *TimeSeriesOptionsBuilder - EncryptedFields any - ClusteredIndex any + EncryptedFields interface{} + ClusteredIndex interface{} } // CreateCollectionOptionsBuilder contains options to configure a new @@ -193,8 +193,9 @@ func (c *CreateCollectionOptionsBuilder) SetCapped(capped bool) *CreateCollectio return c } -// SetCollation sets the value for the Collation field. Specifies the default -// collation for the new collection. The default value is nil. +// SetCollation sets the value for the Collation field. Specifies the default collation for the new +// collection. This option is only valid for MongoDB versions >= 3.4. For previous server versions, +// the driver will return an error if this option is used. The default value is nil. func (c *CreateCollectionOptionsBuilder) SetCollation(collation *Collation) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.Collation = collation @@ -211,7 +212,7 @@ func (c *CreateCollectionOptionsBuilder) SetCollation(collation *Collation) *Cre // option is only valid for MongoDB versions >= 6.0. The default value is nil, which means that // change streams opened against the collection will not return pre- and post-images of updated // documents in any way. -func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi any) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi interface{}) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ChangeStreamPreAndPostImages = &csppi @@ -221,9 +222,9 @@ func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi a return c } -// SetDefaultIndexOptions sets the value for the DefaultIndexOptions field. -// Specifies a default configuration for indexes on the collection. The default -// value is nil, meaning indexes will be configured using server defaults. +// SetDefaultIndexOptions sets the value for the DefaultIndexOptions field. Specifies a default +// configuration for indexes on the collection. This option is only valid for MongoDB versions +// >= 3.4. The default value is nil, meaning indexes will be configured using server defaults. func (c *CreateCollectionOptionsBuilder) SetDefaultIndexOptions(iopts *DefaultIndexOptionsBuilder) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.DefaultIndexOptions = iopts @@ -264,7 +265,7 @@ func (c *CreateCollectionOptionsBuilder) SetSizeInBytes(size int64) *CreateColle // SetStorageEngine sets the value for the StorageEngine field. Specifies the storage engine to use for // the index. The value must be a document in the form {: }. The default // value is nil, which means that the default storage engine will be used. -func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine any) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine interface{}) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.StorageEngine = &storageEngine @@ -277,7 +278,7 @@ func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine any) *Cr // SetValidationAction sets the value for the ValidationAction field. Specifies what should happen if a // document being inserted does not pass validation. Valid values are "error" and "warn". See // https://www.mongodb.com/docs/manual/core/schema-validation/#accept-or-reject-invalid-documents for more -// information. The default value is "error". +// information. This option is only valid for MongoDB versions >= 3.2. The default value is "error". func (c *CreateCollectionOptionsBuilder) SetValidationAction(action string) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ValidationAction = &action @@ -291,7 +292,7 @@ func (c *CreateCollectionOptionsBuilder) SetValidationAction(action string) *Cre // SetValidationLevel sets the value for the ValidationLevel field. Specifies how strictly the server applies // validation rules to existing documents in the collection during update operations. Valid values are "off", // "strict", and "moderate". See https://www.mongodb.com/docs/manual/core/schema-validation/#existing-documents -// for more information. The default value is "strict". +// for more information. This option is only valid for MongoDB versions >= 3.2. The default value is "strict". func (c *CreateCollectionOptionsBuilder) SetValidationLevel(level string) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ValidationLevel = &level @@ -304,8 +305,9 @@ func (c *CreateCollectionOptionsBuilder) SetValidationLevel(level string) *Creat // SetValidator sets the value for the Validator field. Sets a document specifying validation rules for the // collection. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about -// schema validation. The default value is nil, meaning no validator will be used for the collection. -func (c *CreateCollectionOptionsBuilder) SetValidator(validator any) *CreateCollectionOptionsBuilder { +// schema validation. This option is only valid for MongoDB versions >= 3.2. The default value is nil, +// meaning no validator will be used for the collection. +func (c *CreateCollectionOptionsBuilder) SetValidator(validator interface{}) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.Validator = validator @@ -351,7 +353,7 @@ func (c *CreateCollectionOptionsBuilder) SetTimeSeriesOptions(timeSeriesOpts *Ti // SetEncryptedFields sets the encrypted fields for encrypted collections. // // This option is only valid for MongoDB versions >= 6.0 -func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields interface{}) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.EncryptedFields = encryptedFields @@ -365,7 +367,7 @@ func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) // to create a collection with a clustered index. // // This option is only valid for MongoDB versions >= 5.3 -func (c *CreateCollectionOptionsBuilder) SetClusteredIndex(clusteredIndex any) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetClusteredIndex(clusteredIndex interface{}) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ClusteredIndex = clusteredIndex @@ -400,8 +402,9 @@ func (c *CreateViewOptionsBuilder) List() []func(*CreateViewOptions) error { return c.Opts } -// SetCollation sets the value for the Collation field. Specifies the default -// collation for the new collection. The default value is nil. +// SetCollation sets the value for the Collation field. Specifies the default collation for the new +// collection. This option is only valid for MongoDB versions >= 3.4. For previous server versions, +// the driver will return an error if this option is used. The default value is nil. func (c *CreateViewOptionsBuilder) SetCollation(collation *Collation) *CreateViewOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateViewOptions) error { opts.Collation = collation diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go index 8d24f9d1..b7b2a192 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go @@ -10,7 +10,7 @@ package options // // See corresponding setter methods for documentation. type DataKeyOptions struct { - MasterKey any + MasterKey interface{} KeyAltNames []string KeyMaterial []byte } @@ -71,7 +71,7 @@ func (dk *DataKeyOptionsBuilder) List() []func(*DataKeyOptions) error { // } // // If unset, "keyVersion" defaults to the key's primary version and "endpoint" defaults to "cloudkms.googleapis.com". -func (dk *DataKeyOptionsBuilder) SetMasterKey(masterKey any) *DataKeyOptionsBuilder { +func (dk *DataKeyOptionsBuilder) SetMasterKey(masterKey interface{}) *DataKeyOptionsBuilder { dk.Opts = append(dk.Opts, func(opts *DataKeyOptions) error { opts.MasterKey = masterKey diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go index 2206abb2..f0d88043 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go @@ -6,21 +6,15 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // DeleteOneOptions represents arguments that can be used to configure DeleteOne // operations. // // See corresponding setter methods for documentation. type DeleteOneOptions struct { Collation *Collation - Comment any - Hint any - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Comment interface{} + Hint interface{} + Let interface{} } // DeleteOneOptionsBuilder contains options to configure DeleteOne operations. Each @@ -40,9 +34,11 @@ func (do *DeleteOneOptionsBuilder) List() []func(*DeleteOneOptions) error { return do.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for +// string comparisons during the operation. This option is only valid for MongoDB +// versions >= 3.4. For previous server versions, the driver will return an error if this +// option is used. The default value is nil, which means the default collation of the +// collection will be used. func (do *DeleteOneOptionsBuilder) SetCollation(c *Collation) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Collation = c @@ -56,7 +52,7 @@ func (do *DeleteOneOptionsBuilder) SetCollation(c *Collation) *DeleteOneOptionsB // SetComment sets the value for the Comment field. Specifies a string or document that will // be included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (do *DeleteOneOptionsBuilder) SetComment(comment any) *DeleteOneOptionsBuilder { +func (do *DeleteOneOptionsBuilder) SetComment(comment interface{}) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Comment = comment @@ -66,15 +62,14 @@ func (do *DeleteOneOptionsBuilder) SetComment(comment any) *DeleteOneOptionsBuil return do } -// SetHint sets the value for the Hint field. Specifies the index to use for the -// operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions -// >= 4.4. Server versions < 4.4 will return an error if this option is -// specified. The driver will return an error if this option is specified during -// an unacknowledged write operation. The driver will return an error if the -// hint parameter is a multi-key map. The default value is nil, which means that -// no hint will be sent. -func (do *DeleteOneOptionsBuilder) SetHint(hint any) *DeleteOneOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the operation. This +// should either be the index name as a string or the index specification as a document. This option +// is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an error if this +// option is specified. For server versions < 3.4, the driver will return a client-side error if this +// option is specified. The driver will return an error if this option is specified during an +// unacknowledged write operation. The driver will return an error if the hint parameter is a +// multi-key map. The default value is nil, which means that no hint will be sent. +func (do *DeleteOneOptionsBuilder) SetHint(hint interface{}) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Hint = hint @@ -89,7 +84,7 @@ func (do *DeleteOneOptionsBuilder) SetHint(hint any) *DeleteOneOptionsBuilder { // this option. This must be a document mapping parameter names to values. Values must be constant // or closed expressions that do not reference document fields. Parameters can then be accessed as // variables in an aggregate expression context (e.g. "$$var"). -func (do *DeleteOneOptionsBuilder) SetLet(let any) *DeleteOneOptionsBuilder { +func (do *DeleteOneOptionsBuilder) SetLet(let interface{}) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Let = let @@ -105,13 +100,9 @@ func (do *DeleteOneOptionsBuilder) SetLet(let any) *DeleteOneOptionsBuilder { // See corresponding setter methods for documentation. type DeleteManyOptions struct { Collation *Collation - Comment any - Hint any - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Comment interface{} + Hint interface{} + Let interface{} } // DeleteManyOptionsBuilder contains options to configure DeleteMany operations. @@ -131,9 +122,10 @@ func (do *DeleteManyOptionsBuilder) List() []func(*DeleteManyOptions) error { return do.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. +// For previous server versions, the driver will return an error if this option is used. The +// default value is nil, which means the default collation of the collection will be used. func (do *DeleteManyOptionsBuilder) SetCollation(c *Collation) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Collation = c @@ -147,7 +139,7 @@ func (do *DeleteManyOptionsBuilder) SetCollation(c *Collation) *DeleteManyOption // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (do *DeleteManyOptionsBuilder) SetComment(comment any) *DeleteManyOptionsBuilder { +func (do *DeleteManyOptionsBuilder) SetComment(comment interface{}) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Comment = comment @@ -157,15 +149,15 @@ func (do *DeleteManyOptionsBuilder) SetComment(comment any) *DeleteManyOptionsBu return do } -// SetHint sets the value for the Hint field. Specifies the index to use for the -// operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions -// >= 4.4. Server versions < 4.4 will return an error if this option is -// specified. The driver will return an error if this option is specified during -// an unacknowledged write operation. The driver will return an error if the -// hint parameter is a multi-key map. The default value is nil, which means that -// no hint will be sent. -func (do *DeleteManyOptionsBuilder) SetHint(hint any) *DeleteManyOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the operation. +// This should either be the index name as a string or the index specification as a document. +// This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an +// error if this option is specified. For server versions < 3.4, the driver will return a +// client-side error if this option is specified. The driver will return an error if this option +// is specified during an unacknowledged write operation. The driver will return an error if the +// hint parameter is a multi-key map. The default value is nil, which means that no hint will +// be sent. +func (do *DeleteManyOptionsBuilder) SetHint(hint interface{}) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Hint = hint @@ -180,7 +172,7 @@ func (do *DeleteManyOptionsBuilder) SetHint(hint any) *DeleteManyOptionsBuilder // for using this option. This must be a document mapping parameter names to values. Values // must be constant or closed expressions that do not reference document fields. Parameters // can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (do *DeleteManyOptionsBuilder) SetLet(let any) *DeleteManyOptionsBuilder { +func (do *DeleteManyOptionsBuilder) SetLet(let interface{}) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Let = let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go index 476c1048..0b9167d5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go @@ -6,20 +6,14 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // DistinctOptions represents arguments that can be used to configure a Distinct // operation. // // See corresponding setter methods for documentation. type DistinctOptions struct { Collation *Collation - Comment any - Hint any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Comment interface{} + Hint interface{} } // DistinctOptionsBuilder contains options to configure distinct operations. Each @@ -39,9 +33,11 @@ func (do *DistinctOptionsBuilder) List() []func(*DistinctOptions) error { return do.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use +// for string comparisons during the operation. This option is only valid for MongoDB +// versions >= 3.4. For previous server versions, the driver will return an error if +// this option is used. The default value is nil, which means the default collation +// of the collection will be used. func (do *DistinctOptionsBuilder) SetCollation(c *Collation) *DistinctOptionsBuilder { do.Opts = append(do.Opts, func(opts *DistinctOptions) error { opts.Collation = c @@ -56,7 +52,7 @@ func (do *DistinctOptionsBuilder) SetCollation(c *Collation) *DistinctOptionsBui // will be included in server logs, profiling logs, and currentOp queries to help trace // the operation. The default value is nil, which means that no comment will be included // in the logs. -func (do *DistinctOptionsBuilder) SetComment(comment any) *DistinctOptionsBuilder { +func (do *DistinctOptionsBuilder) SetComment(comment interface{}) *DistinctOptionsBuilder { do.Opts = append(do.Opts, func(opts *DistinctOptions) error { opts.Comment = comment @@ -74,7 +70,7 @@ func (do *DistinctOptionsBuilder) SetComment(comment any) *DistinctOptionsBuilde // means that no index hint will be sent. // // SetHint sets the Hint field. -func (do *DistinctOptionsBuilder) SetHint(hint any) *DistinctOptionsBuilder { +func (do *DistinctOptionsBuilder) SetHint(hint interface{}) *DistinctOptionsBuilder { do.Opts = append(do.Opts, func(opts *DistinctOptions) error { opts.Hint = hint diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go index 013b4bbb..4619b6b6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go @@ -11,7 +11,7 @@ package options // // See corresponding setter methods for documentation. type DropCollectionOptions struct { - EncryptedFields any + EncryptedFields interface{} } // DropCollectionOptionsBuilder contains options to configure collection drop @@ -34,7 +34,7 @@ func (d *DropCollectionOptionsBuilder) List() []func(*DropCollectionOptions) err // SetEncryptedFields sets the encrypted fields for encrypted collections. // // This option is only valid for MongoDB versions >= 6.0 -func (d *DropCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) *DropCollectionOptionsBuilder { +func (d *DropCollectionOptionsBuilder) SetEncryptedFields(encryptedFields interface{}) *DropCollectionOptionsBuilder { d.Opts = append(d.Opts, func(opts *DropCollectionOptions) error { opts.EncryptedFields = encryptedFields diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go index 2fd8f87d..2bee45a8 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go @@ -6,18 +6,12 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // EstimatedDocumentCountOptions represents arguments that can be used to configure // an EstimatedDocumentCount operation. // // See corresponding setter methods for documentation. type EstimatedDocumentCountOptions struct { - Comment any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Comment interface{} } // EstimatedDocumentCountOptionsBuilder contains options to estimate document @@ -41,7 +35,7 @@ func (eco *EstimatedDocumentCountOptionsBuilder) List() []func(*EstimatedDocumen // that will be included in server logs, profiling logs, and currentOp queries to help // trace the operation. The default is nil, which means that no comment will be // included in the logs. -func (eco *EstimatedDocumentCountOptionsBuilder) SetComment(comment any) *EstimatedDocumentCountOptionsBuilder { +func (eco *EstimatedDocumentCountOptionsBuilder) SetComment(comment interface{}) *EstimatedDocumentCountOptionsBuilder { eco.Opts = append(eco.Opts, func(opts *EstimatedDocumentCountOptions) error { opts.Comment = comment diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go index b295bd51..92701c9d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go @@ -8,8 +8,6 @@ package options import ( "time" - - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" ) // FindOptions represents arguments that can be used to configure a Find @@ -19,28 +17,24 @@ import ( type FindOptions struct { AllowPartialResults *bool Collation *Collation - Comment any - Hint any - Max any + Comment interface{} + Hint interface{} + Max interface{} MaxAwaitTime *time.Duration - Min any + Min interface{} OplogReplay *bool - Projection any + Projection interface{} ReturnKey *bool ShowRecordID *bool Skip *int64 - Sort any + Sort interface{} // The above are in common with FindOneopts. AllowDiskUse *bool BatchSize *int32 CursorType *CursorType - Let any + Let interface{} Limit *int64 NoCursorTimeout *bool - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // FindOptionsBuilder represents functional options that configure an Findopts. @@ -58,11 +52,11 @@ func (f *FindOptionsBuilder) List() []func(*FindOptions) error { return f.Opts } -// SetAllowDiskUse sets the value for the AllowDiskUse field. AllowDiskUse -// specifies whether the server can write temporary data to disk while executing -// the Find operation. This option is only valid for MongoDB versions >= 4.4. -// Server versions < 4.4 will return an error if this option is specified. The -// default value is false. +// SetAllowDiskUse sets the value for the AllowDiskUse field. AllowDiskUse specifies whether the +// server can write temporary data to disk while executing the Find operation. This option is only +// valid for MongoDB versions >= 4.4. Server versions >= 3.2 will report an error if this option +// is specified. For server versions < 3.2, the driver will return a client-side error if this +// option is specified. The default value is false. func (f *FindOptionsBuilder) SetAllowDiskUse(b bool) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.AllowDiskUse = &b @@ -92,10 +86,10 @@ func (f *FindOptionsBuilder) SetBatchSize(i int32) *FindOptionsBuilder { return f } -// SetCollation sets the value for the Collation field. Collation specifies a -// collation to use for string comparisons during the operation. The default -// value is nil, which means the default collation of the collection will be -// used. +// SetCollation sets the value for the Collation field. Collation specifies a collation to use for +// string comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. +// For previous server versions, the driver will return an error if this option is used. The +// default value is nil, which means the default collation of the collection will be used. func (f *FindOptionsBuilder) SetCollation(collation *Collation) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Collation = collation @@ -107,7 +101,7 @@ func (f *FindOptionsBuilder) SetCollation(collation *Collation) *FindOptionsBuil // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default is nil, which means that no comment will be included in the logs. -func (f *FindOptionsBuilder) SetComment(comment any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetComment(comment interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Comment = &comment return nil @@ -130,7 +124,7 @@ func (f *FindOptionsBuilder) SetCursorType(ct CursorType) *FindOptionsBuilder { // This should either be the index name as a string or the index specification as a document. // The driver will return an error if the hint parameter is a multi-key map. The default // value is nil, which means that no hint will be sent. -func (f *FindOptionsBuilder) SetHint(hint any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetHint(hint interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Hint = hint return nil @@ -143,7 +137,7 @@ func (f *FindOptionsBuilder) SetHint(hint any) *FindOptionsBuilder { // for using this option. This must be a document mapping parameter names to values. Values // must be constant or closed expressions that do not reference document fields. Parameters // can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (f *FindOptionsBuilder) SetLet(let any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetLet(let interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Let = let return nil @@ -165,7 +159,7 @@ func (f *FindOptionsBuilder) SetLimit(i int64) *FindOptionsBuilder { // SetMax sets the value for the Max field. Max is a document specifying the exclusive upper bound // for a specific index. The default value is nil, which means that there is no maximum value. -func (f *FindOptionsBuilder) SetMax(max any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetMax(max interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Max = max return nil @@ -173,11 +167,11 @@ func (f *FindOptionsBuilder) SetMax(max any) *FindOptionsBuilder { return f } -// SetMaxAwaitTime sets the value for the MaxAwaitTime field. MaxAwaitTime is -// the maximum amount of time that the server should wait for new documents to -// satisfy a tailable cursor query. This option is only valid for tailable await -// cursors (see the CursorType option for more information). For other cursor -// types, this option is ignored. +// SetMaxAwaitTime sets the value for the MaxAwaitTime field. MaxAwaitTime is the maximum amount of +// time that the server should wait for new documents to satisfy a tailable cursor query. This +// option is only valid for tailable await cursors (see the CursorType option for more information) +// and MongoDB versions >= 3.2. For other cursor types or previous server versions, this option +// is ignored. func (f *FindOptionsBuilder) SetMaxAwaitTime(d time.Duration) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.MaxAwaitTime = &d @@ -188,7 +182,7 @@ func (f *FindOptionsBuilder) SetMaxAwaitTime(d time.Duration) *FindOptionsBuilde // SetMin sets the value for the Min field. Min is a document specifying the inclusive lower bound // for a specific index. The default value is 0, which means that there is no minimum value. -func (f *FindOptionsBuilder) SetMin(min any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetMin(min interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Min = min return nil @@ -223,7 +217,7 @@ func (f *FindOptionsBuilder) SetOplogReplay(b bool) *FindOptionsBuilder { // SetProjection sets the value for the Projection field. Projection is a document describing // which fields will be included in the documents returned by the Find operation. The // default value is nil, which means all fields will be included. -func (f *FindOptionsBuilder) SetProjection(projection any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetProjection(projection interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Projection = projection return nil @@ -266,7 +260,7 @@ func (f *FindOptionsBuilder) SetSkip(i int64) *FindOptionsBuilder { // SetSort sets the value for the Sort field. Sort is a document specifying the order in which // documents should be returned. The sort parameter is evaluated sequentially, so the driver will // return an error if it is a multi-key map (which is unordeded). The default value is nil. -func (f *FindOptionsBuilder) SetSort(sort any) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetSort(sort interface{}) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Sort = sort return nil @@ -281,20 +275,16 @@ func (f *FindOptionsBuilder) SetSort(sort any) *FindOptionsBuilder { type FindOneOptions struct { AllowPartialResults *bool Collation *Collation - Comment any - Hint any - Max any - Min any + Comment interface{} + Hint interface{} + Max interface{} + Min interface{} OplogReplay *bool - Projection any + Projection interface{} ReturnKey *bool ShowRecordID *bool Skip *int64 - Sort any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Sort interface{} } // FindOneOptionsBuilder represents functional options that configure an @@ -324,9 +314,10 @@ func (f *FindOneOptionsBuilder) SetAllowPartialResults(b bool) *FindOneOptionsBu return f } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For +// previous server versions, the driver will return an error if this option is used. The +// default value is nil, which means the default collation of the collection will be used. func (f *FindOneOptionsBuilder) SetCollation(collation *Collation) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Collation = collation @@ -338,7 +329,7 @@ func (f *FindOneOptionsBuilder) SetCollation(collation *Collation) *FindOneOptio // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default is nil, which means that no comment will be included in the logs. -func (f *FindOneOptionsBuilder) SetComment(comment any) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetComment(comment interface{}) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Comment = &comment return nil @@ -350,7 +341,7 @@ func (f *FindOneOptionsBuilder) SetComment(comment any) *FindOneOptionsBuilder { // This should either be the index name as a string or the index specification as a document. // The driver will return an error if the hint parameter is a multi-key map. The default value // is nil, which means that no hint will be sent. -func (f *FindOneOptionsBuilder) SetHint(hint any) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetHint(hint interface{}) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Hint = hint return nil @@ -360,7 +351,7 @@ func (f *FindOneOptionsBuilder) SetHint(hint any) *FindOneOptionsBuilder { // SetMax sets the value for the Max field. Sets a document specifying the exclusive upper bound // for a specific index. The default value is nil, which means that there is no maximum value. -func (f *FindOneOptionsBuilder) SetMax(max any) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetMax(max interface{}) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Max = max return nil @@ -370,7 +361,7 @@ func (f *FindOneOptionsBuilder) SetMax(max any) *FindOneOptionsBuilder { // SetMin sets the value for the Min field. Sets a document specifying the inclusive lower bound // for a specific index. The default value is 0, which means that there is no minimum value. -func (f *FindOneOptionsBuilder) SetMin(min any) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetMin(min interface{}) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Min = min return nil @@ -394,7 +385,7 @@ func (f *FindOneOptionsBuilder) SetOplogReplay(b bool) *FindOneOptionsBuilder { // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneOptionsBuilder) SetProjection(projection any) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetProjection(projection interface{}) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Projection = projection return nil @@ -438,7 +429,7 @@ func (f *FindOneOptionsBuilder) SetSkip(i int64) *FindOneOptionsBuilder { // apply to the query. The first document in the sorted order will be returned. The sort // parameter is evaluated sequentially, so the driver will return an error if it is a multi- // key map (which is unordeded). The default value is nil. -func (f *FindOneOptionsBuilder) SetSort(sort any) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetSort(sort interface{}) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Sort = sort return nil @@ -453,17 +444,13 @@ func (f *FindOneOptionsBuilder) SetSort(sort any) *FindOneOptionsBuilder { type FindOneAndReplaceOptions struct { BypassDocumentValidation *bool Collation *Collation - Comment any - Projection any + Comment interface{} + Projection interface{} ReturnDocument *ReturnDocument - Sort any + Sort interface{} Upsert *bool - Hint any - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Hint interface{} + Let interface{} } // FindOneAndReplaceOptionsBuilder contains options to perform a findAndModify @@ -484,7 +471,8 @@ func (f *FindOneAndReplaceOptionsBuilder) List() []func(*FindOneAndReplaceOption } // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes -// executed as part of the operation will opt out of document-level validation on the server. The +// executed as part of the operation will opt out of document-level validation on the server. This +// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The // default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more // information about document validation. func (f *FindOneAndReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *FindOneAndReplaceOptionsBuilder { @@ -497,9 +485,10 @@ func (f *FindOneAndReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *F return f } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. +// For previous server versions, the driver will return an error if this option is used. The +// default value is nil, which means the default collation of the collection will be used. func (f *FindOneAndReplaceOptionsBuilder) SetCollation(collation *Collation) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Collation = collation @@ -513,7 +502,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetCollation(collation *Collation) *Fi // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment any) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment interface{}) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Comment = comment @@ -526,7 +515,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment any) *FindOneAndRep // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneAndReplaceOptionsBuilder) SetProjection(projection any) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetProjection(projection interface{}) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Projection = projection @@ -554,7 +543,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetReturnDocument(rd ReturnDocument) * // If set, the first document in the sorted order will be replaced. The sort parameter is evaluated // sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *FindOneAndReplaceOptionsBuilder) SetSort(sort any) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetSort(sort interface{}) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Sort = sort @@ -584,7 +573,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetUpsert(b bool) *FindOneAndReplaceOp // with during an unacknowledged write operation. The driver will return an error if the // hint parameter is a multi-key map. The default value is nil, which means that no hint // will be sent. -func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint any) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint interface{}) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Hint = hint @@ -600,7 +589,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint any) *FindOneAndReplaceOp // parameter names to values. Values must be constant or closed expressions that do not // reference document fields. Parameters can then be accessed as variables in an // aggregate expression context (e.g. "$$var"). -func (f *FindOneAndReplaceOptionsBuilder) SetLet(let any) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetLet(let interface{}) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Let = let @@ -615,20 +604,16 @@ func (f *FindOneAndReplaceOptionsBuilder) SetLet(let any) *FindOneAndReplaceOpti // // See corresponding setter methods for documentation. type FindOneAndUpdateOptions struct { - ArrayFilters []any + ArrayFilters []interface{} BypassDocumentValidation *bool Collation *Collation - Comment any - Projection any + Comment interface{} + Projection interface{} ReturnDocument *ReturnDocument - Sort any + Sort interface{} Upsert *bool - Hint any - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Hint interface{} + Let interface{} } // FindOneAndUpdateOptionsBuilder contains options to configure a @@ -648,11 +633,12 @@ func (f *FindOneAndUpdateOptionsBuilder) List() []func(*FindOneAndUpdateOptions) return f.Opts } -// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a -// set of filters specifying to which array elements an update should apply. The -// default value is nil, which means the update will apply to all array -// elements. -func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []any) *FindOneAndUpdateOptionsBuilder { +// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a set of filters +// specifying to which array elements an update should apply. This option is only valid for +// MongoDB versions >= 3.6. For previous server versions, the driver will return an error if +// this option is used. The default value is nil, which means the update will apply to all +// array elements. +func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []interface{}) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.ArrayFilters = filters @@ -664,6 +650,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []any) *FindOne // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. +// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ // for more information about document validation. func (f *FindOneAndUpdateOptionsBuilder) SetBypassDocumentValidation(b bool) *FindOneAndUpdateOptionsBuilder { @@ -676,9 +663,10 @@ func (f *FindOneAndUpdateOptionsBuilder) SetBypassDocumentValidation(b bool) *Fi return f } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For +// previous server versions, the driver will return an error if this option is used. The default +// value is nil, which means the default collation of the collection will be used. func (f *FindOneAndUpdateOptionsBuilder) SetCollation(collation *Collation) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Collation = collation @@ -692,7 +680,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetCollation(collation *Collation) *Fin // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment any) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment interface{}) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Comment = comment @@ -705,7 +693,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment any) *FindOneAndUpda // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneAndUpdateOptionsBuilder) SetProjection(projection any) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetProjection(projection interface{}) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Projection = projection @@ -733,7 +721,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetReturnDocument(rd ReturnDocument) *F // If set, the first document in the sorted order will be updated. The sort parameter is evaluated // sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *FindOneAndUpdateOptionsBuilder) SetSort(sort any) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetSort(sort interface{}) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Sort = sort @@ -763,7 +751,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetUpsert(b bool) *FindOneAndUpdateOpti // with during an unacknowledged write operation. The driver will return an error if the // hint parameter is a multi-key map. The default value is nil, which means that no hint // will be sent. -func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint any) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint interface{}) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Hint = hint @@ -779,7 +767,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint any) *FindOneAndUpdateOpti // to values. Values must be constant or closed expressions that do not reference document // fields. Parameters can then be accessed as variables in an aggregate expression context // (e.g. "$$var"). -func (f *FindOneAndUpdateOptionsBuilder) SetLet(let any) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetLet(let interface{}) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Let = let @@ -795,15 +783,11 @@ func (f *FindOneAndUpdateOptionsBuilder) SetLet(let any) *FindOneAndUpdateOption // See corresponding setter methods for documentation. type FindOneAndDeleteOptions struct { Collation *Collation - Comment any - Projection any - Sort any - Hint any - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Comment interface{} + Projection interface{} + Sort interface{} + Hint interface{} + Let interface{} } // FindOneAndDeleteOptionsBuilder contains options to configure delete @@ -823,9 +807,10 @@ func (f *FindOneAndDeleteOptionsBuilder) List() []func(*FindOneAndDeleteOptions) return f.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. +// For previous server versions, the driver will return an error if this option is used. The +// default value is nil, which means the default collation of the collection will be used. func (f *FindOneAndDeleteOptionsBuilder) SetCollation(collation *Collation) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Collation = collation @@ -839,7 +824,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetCollation(collation *Collation) *Fin // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment any) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment interface{}) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Comment = comment @@ -852,7 +837,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment any) *FindOneAndDele // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection any) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection interface{}) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Projection = projection @@ -867,7 +852,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection any) *FindOneA // If set, the first document in the sorted order will be deleted. The sort parameter is evaluated // sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort any) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort interface{}) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Sort = sort @@ -884,7 +869,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort any) *FindOneAndDeleteOpti // error if this option is specified. The driver will return an error if this option is used // with during an unacknowledged write operation. The driver will return an error if the hint // parameter is a multi-key map. The default value is nil, which means that no hint will be sent. -func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint any) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint interface{}) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Hint = hint @@ -899,7 +884,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint any) *FindOneAndDeleteOpti // report an error for using this option. This must be a document mapping parameter names to // values. Values must be constant or closed expressions that do not reference document fields. // Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (f *FindOneAndDeleteOptionsBuilder) SetLet(let any) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetLet(let interface{}) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Let = let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go index 676596cb..43af42b4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go @@ -123,7 +123,7 @@ func (b *BucketOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *BucketO // See corresponding setter methods for documentation. type GridFSUploadOptions struct { ChunkSizeBytes *int32 - Metadata any + Metadata interface{} Registry *bson.Registry } @@ -163,7 +163,7 @@ func (u *GridFSUploadOptionsBuilder) SetChunkSizeBytes(i int32) *GridFSUploadOpt // that will be stored in the "metadata" field of the document in the files collection. // The default value is nil, which means that the document in the files collection will // not contain a "metadata" field. -func (u *GridFSUploadOptionsBuilder) SetMetadata(doc any) *GridFSUploadOptionsBuilder { +func (u *GridFSUploadOptionsBuilder) SetMetadata(doc interface{}) *GridFSUploadOptionsBuilder { u.Opts = append(u.Opts, func(opts *GridFSUploadOptions) error { opts.Metadata = doc @@ -242,7 +242,7 @@ type GridFSFindOptions struct { Limit *int32 NoCursorTimeout *bool Skip *int32 - Sort any + Sort interface{} } // GridFSFindOptionsBuilder contains options to configure find operations. Each @@ -331,7 +331,7 @@ func (f *GridFSFindOptionsBuilder) SetSkip(i int32) *GridFSFindOptionsBuilder { // in which documents should be returned. The sort parameter is evaluated sequentially, // so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *GridFSFindOptionsBuilder) SetSort(sort any) *GridFSFindOptionsBuilder { +func (f *GridFSFindOptionsBuilder) SetSort(sort interface{}) *GridFSFindOptionsBuilder { f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error { opts.Sort = sort diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go index 309a77ba..48ddac0b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go @@ -6,18 +6,12 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // CreateIndexesOptions represents arguments that can be used to configure // IndexView.CreateOne and IndexView.CreateMany operations. // // See corresponding setter methods for documentation. type CreateIndexesOptions struct { - CommitQuorum any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + CommitQuorum interface{} } // CreateIndexesOptionsBuilder contains options to create indexes. Each option @@ -127,11 +121,7 @@ func (c *CreateIndexesOptionsBuilder) SetCommitQuorumVotingMembers() *CreateInde // DropIndexesOptions represents arguments that can be used to configure // IndexView.DropOne and IndexView.DropAll operations. -type DropIndexesOptions struct { - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options -} +type DropIndexesOptions struct{} // DropIndexesOptionsBuilder contains options to configure dropping indexes. // Each option can be set through setter functions. See documentation for each @@ -156,10 +146,6 @@ func (d *DropIndexesOptionsBuilder) List() []func(*DropIndexesOptions) error { // See corresponding setter methods for documentation. type ListIndexesOptions struct { BatchSize *int32 - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // ListIndexesOptionsBuilder contains options to configure count operations. Each @@ -199,21 +185,21 @@ type IndexOptions struct { ExpireAfterSeconds *int32 Name *string Sparse *bool - StorageEngine any + StorageEngine interface{} Unique *bool Version *int32 DefaultLanguage *string LanguageOverride *string TextVersion *int32 - Weights any + Weights interface{} SphereVersion *int32 Bits *int32 Max *float64 Min *float64 BucketSize *int32 - PartialFilterExpression any + PartialFilterExpression interface{} Collation *Collation - WildcardProjection any + WildcardProjection interface{} Hidden *bool } @@ -276,8 +262,9 @@ func (i *IndexOptionsBuilder) SetSparse(sparse bool) *IndexOptionsBuilder { // SetStorageEngine sets the value for the StorageEngine field. Specifies the // storage engine to use for the index. The value must be a document in the form // {: }. The default value is nil, which means that -// the default storage engine will be used. -func (i *IndexOptionsBuilder) SetStorageEngine(engine any) *IndexOptionsBuilder { +// the default storage engine will be used. This option is only applicable for +// MongoDB versions >= 3.0 and is ignored for previous server versions. +func (i *IndexOptionsBuilder) SetStorageEngine(engine interface{}) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.StorageEngine = engine @@ -359,7 +346,7 @@ func (i *IndexOptionsBuilder) SetTextVersion(version int32) *IndexOptionsBuilder // terms of the score. This option is only applicable for text indexes and is ignored // for other index types. The default value is nil, which means that every field will // have a weight of 1. -func (i *IndexOptionsBuilder) SetWeights(weights any) *IndexOptionsBuilder { +func (i *IndexOptionsBuilder) SetWeights(weights interface{}) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.Weights = weights @@ -437,8 +424,9 @@ func (i *IndexOptionsBuilder) SetBucketSize(bucketSize int32) *IndexOptionsBuild } // SetPartialFilterExpression sets the value for the PartialFilterExpression field. Sets -// a document that defines which collection documents the index should reference. -func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression any) *IndexOptionsBuilder { +// a document that defines which collection documents the index should reference. This +// option is only valid for MongoDB versions >= 3.2 and is ignored for previous server versions. +func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression interface{}) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.PartialFilterExpression = expression @@ -449,7 +437,8 @@ func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression any) *IndexO } // SetCollation sets the value for the Collation field. Specifies the collation to use for -// string comparisons for the index. +// string comparisons for the index. This option is only valid for MongoDB versions >= 3.4. +// For previous server versions, the driver will return an error if this option is used. func (i *IndexOptionsBuilder) SetCollation(collation *Collation) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.Collation = collation @@ -462,7 +451,7 @@ func (i *IndexOptionsBuilder) SetCollation(collation *Collation) *IndexOptionsBu // SetWildcardProjection sets the value for the WildcardProjection field. Sets a document // that defines the wildcard projection for the index. -func (i *IndexOptionsBuilder) SetWildcardProjection(wildcardProjection any) *IndexOptionsBuilder { +func (i *IndexOptionsBuilder) SetWildcardProjection(wildcardProjection interface{}) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.WildcardProjection = wildcardProjection diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go index 532f2850..43b87470 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go @@ -6,19 +6,13 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // InsertOneOptions represents arguments that can be used to configure an InsertOne // operation. // // See corresponding setter methods for documentation. type InsertOneOptions struct { BypassDocumentValidation *bool - Comment any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Comment interface{} } // InsertOneOptionsBuilder represents functional options that configure an @@ -39,7 +33,8 @@ func (ioo *InsertOneOptionsBuilder) List() []func(*InsertOneOptions) error { // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the -// server. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ +// server. This option is valid for MongoDB versions >= 3.2 and is ignored for previous server +// versions. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ // for more information about document validation. func (ioo *InsertOneOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertOneOptionsBuilder { ioo.Opts = append(ioo.Opts, func(opts *InsertOneOptions) error { @@ -51,7 +46,7 @@ func (ioo *InsertOneOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertO // SetComment sets the value for the Comment field. Specifies a string or document that will be included in server logs, profiling logs, and currentOp queries to help trace // the operation. The default value is nil, which means that no comment will be included in the logs. -func (ioo *InsertOneOptionsBuilder) SetComment(comment any) *InsertOneOptionsBuilder { +func (ioo *InsertOneOptionsBuilder) SetComment(comment interface{}) *InsertOneOptionsBuilder { ioo.Opts = append(ioo.Opts, func(opts *InsertOneOptions) error { opts.Comment = &comment return nil @@ -65,12 +60,8 @@ func (ioo *InsertOneOptionsBuilder) SetComment(comment any) *InsertOneOptionsBui // See corresponding setter methods for documentation. type InsertManyOptions struct { BypassDocumentValidation *bool - Comment any + Comment interface{} Ordered *bool - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // InsertManyOptionsBuilder contains options to configure insert operations. @@ -95,7 +86,8 @@ func (imo *InsertManyOptionsBuilder) List() []func(*InsertManyOptions) error { // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the -// server. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ +// server. This option is valid for MongoDB versions >= 3.2 and is ignored for previous server +// versions. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ // for more information about document validation. func (imo *InsertManyOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertManyOptionsBuilder { imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error { @@ -110,7 +102,7 @@ func (imo *InsertManyOptionsBuilder) SetBypassDocumentValidation(b bool) *Insert // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (imo *InsertManyOptionsBuilder) SetComment(comment any) *InsertManyOptionsBuilder { +func (imo *InsertManyOptionsBuilder) SetComment(comment interface{}) *InsertManyOptionsBuilder { imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error { opts.Comment = comment diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go index 14f96cc6..2106b2f9 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go @@ -6,8 +6,6 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // ListCollectionsOptions represents arguments that can be used to configure a // ListCollections operation. // @@ -16,10 +14,6 @@ type ListCollectionsOptions struct { NameOnly *bool BatchSize *int32 AuthorizedCollections *bool - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options } // ListCollectionsOptionsBuilder contains options to configure list collection diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go index 0eb7ce42..3a5c0806 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go @@ -63,10 +63,10 @@ type LogSink interface { // // "Level V(0) is the default, and logger.V(0).Info() has the same // meaning as logger.Info()." - Info(level int, message string, keysAndValues ...any) + Info(level int, message string, keysAndValues ...interface{}) // Error logs an error message with the given key/value pairs - Error(err error, message string, keysAndValues ...any) + Error(err error, message string, keysAndValues ...interface{}) } // LoggerOptions represent arguments used to configure Logging in the Go Driver. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go index 794a77eb..0416d071 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go @@ -6,8 +6,6 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // ReplaceOptions represents arguments that can be used to configure a ReplaceOne // operation. // @@ -15,15 +13,11 @@ import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" type ReplaceOptions struct { BypassDocumentValidation *bool Collation *Collation - Comment any - Hint any + Comment interface{} + Hint interface{} Upsert *bool - Let any - Sort any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Let interface{} + Sort interface{} } // ReplaceOptionsBuilder contains options to configure replace operations. Each @@ -45,6 +39,7 @@ func (ro *ReplaceOptionsBuilder) List() []func(*ReplaceOptions) error { // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. +// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for // more information about document validation. func (ro *ReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *ReplaceOptionsBuilder { @@ -57,9 +52,10 @@ func (ro *ReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *ReplaceOpt return ro } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For +// previous server versions, the driver will return an error if this option is used. The +// default value is nil, which means the default collation of the collection will be used. func (ro *ReplaceOptionsBuilder) SetCollation(c *Collation) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Collation = c @@ -73,7 +69,7 @@ func (ro *ReplaceOptionsBuilder) SetCollation(c *Collation) *ReplaceOptionsBuild // SetComment sets the value for the Comment field. Specifies a string or document that will // be included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (ro *ReplaceOptionsBuilder) SetComment(comment any) *ReplaceOptionsBuilder { +func (ro *ReplaceOptionsBuilder) SetComment(comment interface{}) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Comment = comment @@ -83,15 +79,15 @@ func (ro *ReplaceOptionsBuilder) SetComment(comment any) *ReplaceOptionsBuilder return ro } -// SetHint sets the value for the Hint field. Specifies the index to use for the -// operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions -// >= 4.2. Server versions < 4.2 will return an error if this option is -// specified. The driver will return an error if this option is specified during -// an unacknowledged write operation. The driver will return an error if the -// hint parameter is a multi-key map. The default value is nil, which means that -// no hint will be sent. -func (ro *ReplaceOptionsBuilder) SetHint(h any) *ReplaceOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the operation. +// This should either be the index name as a string or the index specification as a document. +// This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return +// an error if this option is specified. For server versions < 3.4, the driver will return a +// client-side error if this option is specified. The driver will return an error if this option +// is specified during an unacknowledged write operation. The driver will return an error if +// the hint parameter is a multi-key map. The default value is nil, which means that no hint +// will be sent. +func (ro *ReplaceOptionsBuilder) SetHint(h interface{}) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Hint = h @@ -118,7 +114,7 @@ func (ro *ReplaceOptionsBuilder) SetUpsert(b bool) *ReplaceOptionsBuilder { // for using this option. This must be a document mapping parameter names to values. Values // must be constant or closed expressions that do not reference document fields. Parameters // can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (ro *ReplaceOptionsBuilder) SetLet(l any) *ReplaceOptionsBuilder { +func (ro *ReplaceOptionsBuilder) SetLet(l interface{}) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Let = l @@ -133,7 +129,7 @@ func (ro *ReplaceOptionsBuilder) SetLet(l any) *ReplaceOptionsBuilder { // set, the first document in the sorted order will be replaced. This option is only valid for MongoDB // versions >= 8.0. The sort parameter is evaluated sequentially, so the driver will return an error // if it is a multi-key map (which is unordeded). The default value is nil. -func (ro *ReplaceOptionsBuilder) SetSort(s any) *ReplaceOptionsBuilder { +func (ro *ReplaceOptionsBuilder) SetSort(s interface{}) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Sort = s diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go index 3dab855f..08d5bfc1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go @@ -12,7 +12,7 @@ package options // See corresponding setter methods for documentation. type RewrapManyDataKeyOptions struct { Provider *string - MasterKey any + MasterKey interface{} } // RewrapManyDataKeyOptionsBuilder contains options to configure rewraping a @@ -46,7 +46,7 @@ func (rmdko *RewrapManyDataKeyOptionsBuilder) SetProvider(provider string) *Rewr // SetMasterKey sets the value for the MasterKey field. MasterKey identifies the new masterKey. // If omitted, rewraps with the current masterKey. -func (rmdko *RewrapManyDataKeyOptionsBuilder) SetMasterKey(masterKey any) *RewrapManyDataKeyOptionsBuilder { +func (rmdko *RewrapManyDataKeyOptionsBuilder) SetMasterKey(masterKey interface{}) *RewrapManyDataKeyOptionsBuilder { rmdko.Opts = append(rmdko.Opts, func(opts *RewrapManyDataKeyOptions) error { opts.MasterKey = masterKey diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go index c5d15b7a..bbf721b2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go @@ -6,25 +6,19 @@ package options -import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" - // UpdateOneOptions represents arguments that can be used to configure UpdateOne // operations. // // See corresponding setter methods for documentation. type UpdateOneOptions struct { - ArrayFilters []any + ArrayFilters []interface{} BypassDocumentValidation *bool Collation *Collation - Comment any - Hint any + Comment interface{} + Hint interface{} Upsert *bool - Let any - Sort any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Let interface{} + Sort interface{} } // UpdateOneOptionsBuilder contains options to configure UpdateOne operations. @@ -44,11 +38,11 @@ func (uo *UpdateOneOptionsBuilder) List() []func(*UpdateOneOptions) error { return uo.Opts } -// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a -// set of filters specifying to which array elements an update should apply. The -// default value is nil, which means the update will apply to all array -// elements. -func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []any) *UpdateOneOptionsBuilder { +// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a set of filters +// specifying to which array elements an update should apply. This option is only valid for MongoDB +// versions >= 3.6. For previous server versions, the driver will return an error if this option is +// used. The default value is nil, which means the update will apply to all array elements. +func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []interface{}) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.ArrayFilters = af @@ -60,6 +54,7 @@ func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []any) *UpdateOneOptionsBu // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. +// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for // more information about document validation. func (uo *UpdateOneOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateOneOptionsBuilder { @@ -72,9 +67,10 @@ func (uo *UpdateOneOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateOn return uo } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For +// previous server versions, the driver will return an error if this option is used. The default +// value is nil, which means the default collation of the collection will be used. func (uo *UpdateOneOptionsBuilder) SetCollation(c *Collation) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Collation = c @@ -88,7 +84,7 @@ func (uo *UpdateOneOptionsBuilder) SetCollation(c *Collation) *UpdateOneOptionsB // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (uo *UpdateOneOptionsBuilder) SetComment(comment any) *UpdateOneOptionsBuilder { +func (uo *UpdateOneOptionsBuilder) SetComment(comment interface{}) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Comment = comment @@ -98,15 +94,14 @@ func (uo *UpdateOneOptionsBuilder) SetComment(comment any) *UpdateOneOptionsBuil return uo } -// SetHint sets the value for the Hint field. Specifies the index to use for the -// operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions -// >= 4.2. Server versions < 4.2 will return an error if this option is -// specified. The driver will return an error if this option is specified during -// an unacknowledged write operation. The driver will return an error if the -// hint parameter is a multi-key map. The default value is nil, which means that -// no hint will be sent. -func (uo *UpdateOneOptionsBuilder) SetHint(h any) *UpdateOneOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the operation. This +// should either be the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error +// if this option is specified. For server versions < 3.4, the driver will return a client-side +// error if this option is specified. The driver will return an error if this option is specified +// during an unacknowledged write operation. The driver will return an error if the hint parameter +// is a multi-key map. The default value is nil, which means that no hint will be sent. +func (uo *UpdateOneOptionsBuilder) SetHint(h interface{}) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Hint = h @@ -133,7 +128,7 @@ func (uo *UpdateOneOptionsBuilder) SetUpsert(b bool) *UpdateOneOptionsBuilder { // this option. This must be a document mapping parameter names to values. Values must be constant // or closed expressions that do not reference document fields. Parameters can then be accessed // as variables in an aggregate expression context (e.g. "$$var"). -func (uo *UpdateOneOptionsBuilder) SetLet(l any) *UpdateOneOptionsBuilder { +func (uo *UpdateOneOptionsBuilder) SetLet(l interface{}) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Let = l @@ -148,7 +143,7 @@ func (uo *UpdateOneOptionsBuilder) SetLet(l any) *UpdateOneOptionsBuilder { // set, the first document in the sorted order will be updated. This option is only valid for MongoDB // versions >= 8.0. The sort parameter is evaluated sequentially, so the driver will return an error // if it is a multi-key map (which is unordeded). The default value is nil. -func (uo *UpdateOneOptionsBuilder) SetSort(s any) *UpdateOneOptionsBuilder { +func (uo *UpdateOneOptionsBuilder) SetSort(s interface{}) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Sort = s @@ -163,17 +158,13 @@ func (uo *UpdateOneOptionsBuilder) SetSort(s any) *UpdateOneOptionsBuilder { // // See corresponding setter methods for documentation. type UpdateManyOptions struct { - ArrayFilters []any + ArrayFilters []interface{} BypassDocumentValidation *bool Collation *Collation - Comment any - Hint any + Comment interface{} + Hint interface{} Upsert *bool - Let any - - // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any - // release. - Internal optionsutil.Options + Let interface{} } // UpdateManyOptionsBuilder contains options to configure UpdateMany operations. @@ -193,11 +184,11 @@ func (uo *UpdateManyOptionsBuilder) List() []func(*UpdateManyOptions) error { return uo.Opts } -// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a -// set of filters specifying to which array elements an update should apply. The -// default value is nil, which means the update will apply to all array -// elements. -func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []any) *UpdateManyOptionsBuilder { +// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a set of filters +// specifying to which array elements an update should apply. This option is only valid for MongoDB +// versions >= 3.6. For previous server versions, the driver will return an error if this option is +// used. The default value is nil, which means the update will apply to all array elements. +func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []interface{}) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.ArrayFilters = af @@ -209,6 +200,7 @@ func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []any) *UpdateManyOptions // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. +// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for // more information about document validation. func (uo *UpdateManyOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateManyOptionsBuilder { @@ -221,9 +213,10 @@ func (uo *UpdateManyOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateM return uo } -// SetCollation sets the value for the Collation field. Specifies a collation to -// use for string comparisons during the operation. The default value is nil, -// which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to use for string +// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For +// previous server versions, the driver will return an error if this option is used. The default +// value is nil, which means the default collation of the collection will be used. func (uo *UpdateManyOptionsBuilder) SetCollation(c *Collation) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Collation = c @@ -237,7 +230,7 @@ func (uo *UpdateManyOptionsBuilder) SetCollation(c *Collation) *UpdateManyOption // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (uo *UpdateManyOptionsBuilder) SetComment(comment any) *UpdateManyOptionsBuilder { +func (uo *UpdateManyOptionsBuilder) SetComment(comment interface{}) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Comment = comment @@ -247,15 +240,14 @@ func (uo *UpdateManyOptionsBuilder) SetComment(comment any) *UpdateManyOptionsBu return uo } -// SetHint sets the value for the Hint field. Specifies the index to use for the -// operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions -// >= 4.2. Server versions < 4.2 will return an error if this option is -// specified. The driver will return an error if this option is specified during -// an unacknowledged write operation. The driver will return an error if the -// hint parameter is a multi-key map. The default value is nil, which means that -// no hint will be sent. -func (uo *UpdateManyOptionsBuilder) SetHint(h any) *UpdateManyOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the operation. This +// should either be the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error +// if this option is specified. For server versions < 3.4, the driver will return a client-side +// error if this option is specified. The driver will return an error if this option is specified +// during an unacknowledged write operation. The driver will return an error if the hint parameter +// is a multi-key map. The default value is nil, which means that no hint will be sent. +func (uo *UpdateManyOptionsBuilder) SetHint(h interface{}) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Hint = h @@ -282,7 +274,7 @@ func (uo *UpdateManyOptionsBuilder) SetUpsert(b bool) *UpdateManyOptionsBuilder // this option. This must be a document mapping parameter names to values. Values must be constant // or closed expressions that do not reference document fields. Parameters can then be accessed // as variables in an aggregate expression context (e.g. "$$var"). -func (uo *UpdateManyOptionsBuilder) SetLet(l any) *UpdateManyOptionsBuilder { +func (uo *UpdateManyOptionsBuilder) SetLet(l interface{}) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Let = l diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go index 5cd9c9f6..f4671d5d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go @@ -71,15 +71,10 @@ func WithTagSets(tagSets ...tag.Set) Option { } } -// WithHedgeEnabled specifies whether or not hedged reads should be enabled in -// the server. This feature requires MongoDB server version 4.4 or higher. For -// more information about hedged reads, see -// https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/#mongos-hedged-reads. -// If not specified, the default is to not send a value to the server, which -// will result in the server defaults being used. -// -// Deprecated: Hedged reads are deprecated in MongoDB 8.0 and may be removed in -// a future MongoDB version. +// WithHedgeEnabled specifies whether or not hedged reads should be enabled in the server. This feature requires MongoDB +// server version 4.4 or higher. For more information about hedged reads, see +// https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/#mongos-hedged-reads. If not specified, the default +// is to not send a value to the server, which will result in the server defaults being used. func WithHedgeEnabled(hedgeEnabled bool) Option { return func(rp *ReadPref) error { rp.hedgeEnabled = &hedgeEnabled diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go index 5f2320e2..47e5b0cb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go @@ -103,12 +103,8 @@ func (r *ReadPref) TagSets() []tag.Set { return r.tagSets } -// HedgeEnabled returns whether or not hedged reads are enabled for this read -// preference. If this option was not specified during read preference -// construction, nil is returned. -// -// Deprecated: Hedged reads are deprecated in MongoDB 8.0 and may be removed in -// a future MongoDB version. +// HedgeEnabled returns whether or not hedged reads are enabled for this read preference. If this option was not +// specified during read preference construction, nil is returned. func (r *ReadPref) HedgeEnabled() *bool { return r.hedgeEnabled } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go index e50157e6..d8407ef5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go @@ -50,14 +50,14 @@ type ClientBulkWriteResult struct { // ClientBulkWriteInsertResult is the result type returned by a client-level bulk write of InsertOne operation. type ClientBulkWriteInsertResult struct { // The _id of the inserted document. A value generated by the driver will be of type primitive.ObjectID. - InsertedID any + InsertedID interface{} } // ClientBulkWriteUpdateResult is the result type returned from a client-level bulk write of UpdateOne, UpdateMany, and ReplaceOne operation. type ClientBulkWriteUpdateResult struct { - MatchedCount int64 // The number of documents matched by the filter. - ModifiedCount int64 // The number of documents modified by the operation. - UpsertedID any // The _id field of the upserted document, or nil if no upsert was done. + MatchedCount int64 // The number of documents matched by the filter. + ModifiedCount int64 // The number of documents modified by the operation. + UpsertedID interface{} // The _id field of the upserted document, or nil if no upsert was done. } // ClientBulkWriteDeleteResult is the result type returned by a client-level bulk write DeleteOne and DeleteMany operation. @@ -83,7 +83,7 @@ type BulkWriteResult struct { UpsertedCount int64 // A map of operation index to the _id of each upserted document. - UpsertedIDs map[int64]any + UpsertedIDs map[int64]interface{} // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -93,7 +93,7 @@ type BulkWriteResult struct { // InsertOneResult is the result type returned by an InsertOne operation. type InsertOneResult struct { // The _id of the inserted document. A value generated by the driver will be of type bson.ObjectID. - InsertedID any + InsertedID interface{} // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -103,7 +103,7 @@ type InsertOneResult struct { // InsertManyResult is a result type returned by an InsertMany operation. type InsertManyResult struct { // The _id values of the inserted documents. Values generated by the driver will be of type bson.ObjectID. - InsertedIDs []any + InsertedIDs []interface{} // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -159,10 +159,10 @@ type DatabaseSpecification struct { // UpdateResult is the result type returned from UpdateOne, UpdateMany, and ReplaceOne operations. type UpdateResult struct { - MatchedCount int64 // The number of documents matched by the filter. - ModifiedCount int64 // The number of documents modified by the operation. - UpsertedCount int64 // The number of documents upserted by the operation. - UpsertedID any // The _id field of the upserted document, or nil if no upsert was done. + MatchedCount int64 // The number of documents matched by the filter. + ModifiedCount int64 // The number of documents modified by the operation. + UpsertedCount int64 // The number of documents upserted by the operation. + UpsertedID interface{} // The _id field of the upserted document, or nil if no upsert was done. // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -220,10 +220,11 @@ type CollectionSpecification struct { // The type of the collection. This will either be "collection" or "view". Type string - // Whether or not the collection is readOnly. + // Whether or not the collection is readOnly. This will be false for MongoDB versions < 3.4. ReadOnly bool - // The collection UUID as a bson.Binary with subtype 4. + // The collection UUID. This field will be nil for MongoDB versions < 3.6. For versions 3.6 and higher, this will + // be a bson.Binary with Subtype 4. UUID *bson.Binary // A document containing the options used to construct the collection. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go index 5df3b8fb..f62e4769 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go @@ -8,7 +8,6 @@ package mongo import ( "context" - "errors" "fmt" "strconv" @@ -37,7 +36,7 @@ type SearchIndexView struct { type SearchIndexModel struct { // A document describing the definition for the search index. It cannot be nil. // See https://www.mongodb.com/docs/atlas/atlas-search/create-index/ for reference. - Definition any + Definition interface{} // The search index options. Options *options.SearchIndexesOptionsBuilder @@ -230,8 +229,7 @@ func (siv SearchIndexView) DropOne( Timeout(siv.coll.client.timeout).Authenticator(siv.coll.client.authenticator) err = op.Execute(ctx) - var de driver.Error - if errors.As(err, &de) && de.NamespaceNotFound() { + if de, ok := err.(driver.Error); ok && de.NamespaceNotFound() { return nil } return err @@ -250,7 +248,7 @@ func (siv SearchIndexView) DropOne( func (siv SearchIndexView) UpdateOne( ctx context.Context, name string, - definition any, + definition interface{}, _ ...options.Lister[options.UpdateSearchIndexOptions], ) error { if definition == nil { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go index db08f125..fb4da5bb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go @@ -126,9 +126,9 @@ func (s *Session) EndSession(ctx context.Context) { // see the Client.StartSession method documentation. func (s *Session) WithTransaction( ctx context.Context, - fn func(ctx context.Context) (any, error), + fn func(ctx context.Context) (interface{}, error), opts ...options.Lister[options.TransactionOptions], -) (any, error) { +) (interface{}, error) { timeout := time.NewTimer(withTransactionTimeout) defer timeout.Stop() var err error @@ -193,8 +193,7 @@ func (s *Session) WithTransaction( default: } - var cerr CommandError - if errors.As(err, &cerr) { + if cerr, ok := err.(CommandError); ok { if cerr.HasErrorLabel(driver.UnknownTransactionCommitResult) && !cerr.IsMaxTimeMSExpiredError() { continue } @@ -292,7 +291,7 @@ func (s *Session) CommitTransaction(ctx context.Context) error { // Return error without updating transaction state if it is a timeout, as the transaction has not // actually been committed. if IsTimeout(err) { - return wrapErrors(err) + return replaceErrors(err) } s.clientSession.Committing = false commitErr := s.clientSession.CommitTransaction() @@ -301,7 +300,7 @@ func (s *Session) CommitTransaction(ctx context.Context) error { s.clientSession.UpdateCommitTransactionWriteConcern() if err != nil { - return wrapErrors(err) + return replaceErrors(err) } return commitErr } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go index 5cae2984..40b5a5c5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go @@ -41,7 +41,7 @@ type SingleResult struct { // // The document parameter must be a non-nil document. func NewSingleResultFromDocument( - document any, + document interface{}, err error, registry *bson.Registry, ) *SingleResult { @@ -52,7 +52,7 @@ func NewSingleResultFromDocument( registry = defaultRegistry } - cur, createErr := NewCursorFromDocuments([]any{document}, err, registry) + cur, createErr := NewCursorFromDocuments([]interface{}{document}, err, registry) if createErr != nil { return &SingleResult{err: createErr} } @@ -70,7 +70,7 @@ func NewSingleResultFromDocument( // // If the operation was successful and returned a document, Decode will return any errors from the unmarshalling process // without any modification. If v is nil or is a typed nil, an error will be returned. -func (sr *SingleResult) Decode(v any) error { +func (sr *SingleResult) Decode(v interface{}) error { if sr.err != nil { return sr.err } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go index 208f230e..00e60e1c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go @@ -36,7 +36,7 @@ type WriteConcern struct { // // For more information about the "w" option, see // https://www.mongodb.com/docs/manual/reference/write-concern/#w-option - W any + W interface{} // Journal requests acknowledgment from MongoDB that the write operation has // been written to the on-disk journal. It sets the "j" option in a MongoDB diff --git a/vendor/go.mongodb.org/mongo-driver/v2/version/version.go b/vendor/go.mongodb.org/mongo-driver/v2/version/version.go index 2b483845..be3f65c3 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/version/version.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/version/version.go @@ -11,4 +11,4 @@ package version // Driver is the current version of the driver. -var Driver = "2.3.1" +var Driver = "2.1.0" diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go index bfedbc86..0efbdc0f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go @@ -9,6 +9,7 @@ package bsoncore import ( "fmt" "io" + "math" "strconv" "strings" ) @@ -82,79 +83,55 @@ func (a Array) DebugString() string { // String outputs an ExtendedJSON version of Array. If the Array is not valid, this method // returns an empty string. func (a Array) String() string { - str, _ := a.StringN(-1) - return str + return a.StringN(math.MaxInt) } -// StringN stringifies an array. If N is non-negative, it will truncate the string to N bytes. -// Otherwise, it will return the full string representation. The second return value indicates -// whether the string was truncated or not. -func (a Array) StringN(n int) (string, bool) { - length, rem, ok := ReadLength(a) - if !ok || length < 5 { - return "", false - } - length -= 4 // length bytes - length-- // final null byte - - if n == 0 { - return "", true +// StringN stringifies an array upto N bytes +func (a Array) StringN(n int) string { + if lens, _, _ := ReadLength(a); lens < 5 || n <= 0 { + return "" } var buf strings.Builder buf.WriteByte('[') - var truncated bool + length, rem, _ := ReadLength(a) // We know we have enough bytes to read the length + length -= 4 + var elem Element - var str string - first := true - for length > 0 && !truncated { - needStrLen := -1 - // Set needStrLen if n is positive, meaning we want to limit the string length. - if n > 0 { - // Stop stringifying if we reach the limit, that also ensures needStrLen is - // greater than 0 if we need to limit the length. - if buf.Len() >= n { - truncated = true - break - } - needStrLen = n - buf.Len() - } + var ok bool - // Append a comma if this is not the first element. - if !first { - buf.WriteByte(',') - // If we are truncating, we need to account for the comma in the length. - if needStrLen > 0 { - needStrLen-- - if needStrLen == 0 { - truncated = true - break - } + if n > 0 { + for length > 1 { + elem, rem, ok = ReadElement(rem) + + length -= int32(len(elem)) + if !ok { + return "" } - } - elem, rem, ok = ReadElement(rem) - length -= int32(len(elem)) - // Exit on malformed element. - if !ok || length < 0 { - return "", false - } + str := elem.Value().StringN(n - buf.Len()) + + buf.WriteString(str) - // Delegate to StringN() on the element. - str, truncated = elem.Value().StringN(needStrLen) - buf.WriteString(str) + if buf.Len() == n { + return buf.String() + } - first = false + if length > 1 { + buf.WriteByte(',') + } + } + if length != 1 { // Missing final null byte or inaccurate length + return "" + } } - if n <= 0 || (buf.Len() < n && !truncated) { + if buf.Len()+1 <= n { buf.WriteByte(']') - } else { - truncated = true } - return buf.String(), truncated + return buf.String() } // Values returns this array as a slice of values. The returned slice will contain valid values. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go index 03e78e59..6a59908d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go @@ -10,8 +10,11 @@ import ( "errors" "fmt" "io" + "math" "strconv" "strings" + + "go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil" ) // ValidationError is an error type returned when attempting to validate a document or array. @@ -261,79 +264,58 @@ func (d Document) DebugString() string { // String outputs an ExtendedJSON version of Document. If the document is not valid, this method // returns an empty string. func (d Document) String() string { - str, _ := d.StringN(-1) - return str + return d.StringN(math.MaxInt) } -// StringN stringifies a document. If N is non-negative, it will truncate the string to N bytes. -// Otherwise, it will return the full string representation. The second return value indicates -// whether the string was truncated or not. -func (d Document) StringN(n int) (string, bool) { - length, rem, ok := ReadLength(d) - if !ok || length < 5 { - return "", false - } - length -= 4 // length bytes - length-- // final null byte - - if n == 0 { - return "", true +// StringN stringifies a document upto N bytes +func (d Document) StringN(n int) string { + if len(d) < 5 || n <= 0 { + return "" } var buf strings.Builder + buf.WriteByte('{') - var truncated bool + length, rem, _ := ReadLength(d) + length -= 4 + var elem Element - var str string + var ok bool + first := true - for length > 0 && !truncated { - needStrLen := -1 - // Set needStrLen if n is positive, meaning we want to limit the string length. - if n > 0 { - // Stop stringifying if we reach the limit, that also ensures needStrLen is - // greater than 0 if we need to limit the length. - if buf.Len() >= n { - truncated = true - break - } - needStrLen = n - buf.Len() - } + truncated := false - // Append a comma if this is not the first element. - if !first { - buf.WriteByte(',') - // If we are truncating, we need to account for the comma in the length. - if needStrLen > 0 { - needStrLen-- - if needStrLen == 0 { - truncated = true - break - } + if n > 0 { + for length > 1 { + if !first { + buf.WriteByte(',') + } + elem, rem, ok = ReadElement(rem) + length -= int32(len(elem)) + if !ok { + return "" } - } - elem, rem, ok = ReadElement(rem) - length -= int32(len(elem)) - // Exit on malformed element. - if !ok || length < 0 { - return "", false - } + str := elem.StringN(n) + if buf.Len()+len(str) > n { + truncatedStr := bsoncoreutil.Truncate(str, n-buf.Len()) + buf.WriteString(truncatedStr) - // Delegate to StringN() on the element. - str, truncated = elem.StringN(needStrLen) - buf.WriteString(str) + truncated = true + break + } - first = false + buf.WriteString(str) + first = false + } } - if n <= 0 || (buf.Len() < n && !truncated) { + if !truncated { buf.WriteByte('}') - } else { - truncated = true } - return buf.String(), truncated + return buf.String() } // Elements returns this document as a slice of elements. The returned slice will contain valid diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go index 4214e5a7..dcb5e86e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go @@ -9,9 +9,7 @@ package bsoncore import ( "bytes" "fmt" - "strings" - - "go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil" + "math" ) // MalformedElementError represents a class of errors that RawElement methods return. @@ -117,80 +115,35 @@ func (e Element) ValueErr() (Value, error) { // String implements the fmt.String interface. The output will be in extended JSON format. func (e Element) String() string { - str, _ := e.StringN(-1) - return str + return e.StringN(math.MaxInt) } -// StringN will return values in extended JSON format that will stringify an element upto N bytes. -// If N is non-negative, it will truncate the string to N bytes. Otherwise, it will return the full -// string representation. The second return value indicates whether the string was truncated or not. -// If the element is not valid, this returns an empty string -func (e Element) StringN(n int) (string, bool) { +// StringN implements the fmt.String interface for upto N bytes. The output will be in extended JSON format. +func (e Element) StringN(n int) string { if len(e) == 0 { - return "", false - } - if n == 0 { - return "", true + return "" } - if n == 1 { - return `"`, true - } - t := Type(e[0]) idx := bytes.IndexByte(e[1:], 0x00) - if idx <= 0 { - return "", false - } - key := e[1 : idx+1] - - var buf strings.Builder - buf.WriteByte('"') - const suffix = `": ` - switch { - case n < 0 || idx <= n-buf.Len()-len(suffix): - buf.Write(key) - buf.WriteString(suffix) - case idx < n: - buf.Write(key) - buf.WriteString(suffix[:n-idx-1]) - return buf.String(), true - default: - buf.WriteString(bsoncoreutil.Truncate(string(key), n-1)) - return buf.String(), true - } - - needStrLen := -1 - // Set needStrLen if n is positive, meaning we want to limit the string length. - if n > 0 { - // Stop stringifying if we reach the limit, that also ensures needStrLen is - // greater than 0 if we need to limit the length. - if buf.Len() >= n { - return buf.String(), true - } - needStrLen = n - buf.Len() - } - - val, _, valid := ReadValue(e[idx+2:], t) + if idx == -1 { + return "" + } + key, valBytes := []byte(e[1:idx+1]), []byte(e[idx+2:]) + val, _, valid := ReadValue(valBytes, t) if !valid { - return "", false + return "" } var str string - var truncated bool if _, ok := val.StringValueOK(); ok { - str, truncated = val.StringN(needStrLen) + str = val.StringN(n) } else if arr, ok := val.ArrayOK(); ok { - str, truncated = arr.StringN(needStrLen) + str = arr.StringN(n) } else { str = val.String() - if needStrLen > 0 && len(str) > needStrLen { - truncated = true - str = bsoncoreutil.Truncate(str, needStrLen) - } } - buf.WriteString(str) - return buf.String(), truncated + return "\"" + string(key) + "\": " + str } // DebugString outputs a human readable version of RawElement. It will attempt to stringify the diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go index fec33029..b0fd9074 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go @@ -218,137 +218,138 @@ func idHex(id [12]byte) string { // String implements the fmt.String interface. This method will return values in extended JSON // format. If the value is not valid, this returns an empty string func (v Value) String() string { - str, _ := v.StringN(-1) - return str + return v.StringN(math.MaxInt) } -// StringN will return values in extended JSON format that will stringify a value upto N bytes. -// If N is non-negative, it will truncate the string to N bytes. Otherwise, it will return the full -// string representation. The second return value indicates whether the string was truncated or not. -// If the value is not valid, this returns an empty string -func (v Value) StringN(n int) (string, bool) { - var str string +// StringN implements the fmt.String interface. This method will return values in extended JSON +// format that will stringify a value upto N bytes. If the value is not valid, this returns an empty string +func (v Value) StringN(n int) string { + if n <= 0 { + return "" + } + switch v.Type { case TypeString: - s, ok := v.StringValueOK() + str, ok := v.StringValueOK() if !ok { - return "", false + return "" + } + str = escapeString(str) + if len(str) > n { + truncatedStr := bsoncoreutil.Truncate(str, n) + return truncatedStr } - str = escapeString(s) + return str case TypeEmbeddedDocument: doc, ok := v.DocumentOK() if !ok { - return "", false + return "" } return doc.StringN(n) case TypeArray: arr, ok := v.ArrayOK() if !ok { - return "", false + return "" } return arr.StringN(n) case TypeDouble: f64, ok := v.DoubleOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$numberDouble":"%s"}`, formatDouble(f64)) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberDouble":"%s"}`, formatDouble(f64)), n) case TypeBinary: subtype, data, ok := v.BinaryOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$binary":{"base64":"%s","subType":"%02x"}}`, base64.StdEncoding.EncodeToString(data), subtype) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$binary":{"base64":"%s","subType":"%02x"}}`, base64.StdEncoding.EncodeToString(data), subtype), n) case TypeUndefined: - str = `{"$undefined":true}` + return bsoncoreutil.Truncate(`{"$undefined":true}`, n) case TypeObjectID: oid, ok := v.ObjectIDOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$oid":"%s"}`, idHex(oid)) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$oid":"%s"}`, idHex(oid)), n) case TypeBoolean: b, ok := v.BooleanOK() if !ok { - return "", false + return "" } - str = strconv.FormatBool(b) + return bsoncoreutil.Truncate(strconv.FormatBool(b), n) case TypeDateTime: dt, ok := v.DateTimeOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$date":{"$numberLong":"%d"}}`, dt) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$date":{"$numberLong":"%d"}}`, dt), n) case TypeNull: - str = "null" + return bsoncoreutil.Truncate("null", n) case TypeRegex: pattern, options, ok := v.RegexOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf( + return bsoncoreutil.Truncate(fmt.Sprintf( `{"$regularExpression":{"pattern":%s,"options":"%s"}}`, escapeString(pattern), sortStringAlphebeticAscending(options), - ) + ), n) case TypeDBPointer: ns, pointer, ok := v.DBPointerOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$dbPointer":{"$ref":%s,"$id":{"$oid":"%s"}}}`, escapeString(ns), idHex(pointer)) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$dbPointer":{"$ref":%s,"$id":{"$oid":"%s"}}}`, escapeString(ns), idHex(pointer)), n) case TypeJavaScript: js, ok := v.JavaScriptOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$code":%s}`, escapeString(js)) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$code":%s}`, escapeString(js)), n) case TypeSymbol: symbol, ok := v.SymbolOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$symbol":%s}`, escapeString(symbol)) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$symbol":%s}`, escapeString(symbol)), n) case TypeCodeWithScope: code, scope, ok := v.CodeWithScopeOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$code":%s,"$scope":%s}`, code, scope) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$code":%s,"$scope":%s}`, code, scope), n) case TypeInt32: i32, ok := v.Int32OK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$numberInt":"%d"}`, i32) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberInt":"%d"}`, i32), n) case TypeTimestamp: t, i, ok := v.TimestampOK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$timestamp":{"t":%v,"i":%v}}`, t, i) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$timestamp":{"t":%v,"i":%v}}`, t, i), n) case TypeInt64: i64, ok := v.Int64OK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$numberLong":"%d"}`, i64) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberLong":"%d"}`, i64), n) case TypeDecimal128: h, l, ok := v.Decimal128OK() if !ok { - return "", false + return "" } - str = fmt.Sprintf(`{"$numberDecimal":"%s"}`, decimal128.String(h, l)) + return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberDecimal":"%s"}`, decimal128.String(h, l)), n) case TypeMinKey: - str = `{"$minKey":1}` + return bsoncoreutil.Truncate(`{"$minKey":1}`, n) case TypeMaxKey: - str = `{"$maxKey":1}` + return bsoncoreutil.Truncate(`{"$maxKey":1}`, n) default: - str = "" - } - if n >= 0 && len(str) > n { - return bsoncoreutil.Truncate(str, n), true + return "" } - return str, false } // DebugString outputs a human readable version of Document. It will attempt to stringify the diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go index bfc7bbdb..843715dc 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go @@ -11,7 +11,6 @@ import ( "errors" "fmt" "net/http" - "strings" "go.mongodb.org/mongo-driver/v2/mongo/address" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" @@ -32,6 +31,7 @@ func init() { RegisterAuthenticatorFactory("", newDefaultAuthenticator) RegisterAuthenticatorFactory(SCRAMSHA1, newScramSHA1Authenticator) RegisterAuthenticatorFactory(SCRAMSHA256, newScramSHA256Authenticator) + RegisterAuthenticatorFactory(MONGODBCR, newMongoDBCRAuthenticator) RegisterAuthenticatorFactory(PLAIN, newPlainAuthenticator) RegisterAuthenticatorFactory(GSSAPI, newGSSAPIAuthenticator) RegisterAuthenticatorFactory(MongoDBX509, newMongoDBX509Authenticator) @@ -41,12 +41,6 @@ func init() { // CreateAuthenticator creates an authenticator. func CreateAuthenticator(name string, cred *Cred, httpClient *http.Client) (Authenticator, error) { - // Return a custom error to indicate why auth mechanism "MONGODB-CR" is - // missing, even though it was previously available. - if strings.EqualFold(name, "MONGODB-CR") { - return nil, errors.New(`auth mechanism "MONGODB-CR" is no longer available in any supported version of MongoDB`) - } - if f, ok := authFactories[name]; ok { return f(cred, httpClient) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go index 0033379d..6982ccc0 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go @@ -32,8 +32,8 @@ func newDefaultAuthenticator(cred *Cred, httpClient *http.Client) (Authenticator }, nil } -// DefaultAuthenticator uses SCRAM-SHA-1 or SCRAM-SHA-256, depending on the -// server's SASL supported mechanisms. +// DefaultAuthenticator uses SCRAM-SHA-1 or MONGODB-CR depending +// on the server version. type DefaultAuthenticator struct { Cred *Cred @@ -53,20 +53,18 @@ func (a *DefaultAuthenticator) CreateSpeculativeConversation() (SpeculativeConve // Auth authenticates the connection. func (a *DefaultAuthenticator) Auth(ctx context.Context, cfg *driver.AuthConfig) error { - actual, err := func() (Authenticator, error) { - // If a server provides a list of supported mechanisms, we choose - // SCRAM-SHA-256 if it exists or else MUST use SCRAM-SHA-1. - // Otherwise, we decide based on what is supported. - if saslSupportedMechs := cfg.HandshakeInfo.SaslSupportedMechs; saslSupportedMechs != nil { - for _, v := range saslSupportedMechs { - if v == SCRAMSHA256 { - return newScramSHA256Authenticator(a.Cred, a.httpClient) - } - } - } + var actual Authenticator + var err error + + switch chooseAuthMechanism(cfg) { + case SCRAMSHA256: + actual, err = newScramSHA256Authenticator(a.Cred, a.httpClient) + case SCRAMSHA1: + actual, err = newScramSHA1Authenticator(a.Cred, a.httpClient) + default: + actual, err = newMongoDBCRAuthenticator(a.Cred, a.httpClient) + } - return newScramSHA1Authenticator(a.Cred, a.httpClient) - }() if err != nil { return newAuthError("error creating authenticator", err) } @@ -78,3 +76,18 @@ func (a *DefaultAuthenticator) Auth(ctx context.Context, cfg *driver.AuthConfig) func (a *DefaultAuthenticator) Reauth(_ context.Context, _ *driver.AuthConfig) error { return newAuthError("DefaultAuthenticator does not support reauthentication", nil) } + +// If a server provides a list of supported mechanisms, we choose +// SCRAM-SHA-256 if it exists or else MUST use SCRAM-SHA-1. +// Otherwise, we decide based on what is supported. +func chooseAuthMechanism(cfg *driver.AuthConfig) string { + if saslSupportedMechs := cfg.HandshakeInfo.SaslSupportedMechs; saslSupportedMechs != nil { + for _, v := range saslSupportedMechs { + if v == SCRAMSHA256 { + return v + } + } + } + + return SCRAMSHA1 +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go new file mode 100644 index 00000000..f8c1466d --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go @@ -0,0 +1,120 @@ +// 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 auth + +import ( + "context" + "fmt" + "io" + "net/http" + + // Ignore gosec warning "Blocklisted import crypto/md5: weak cryptographic primitive". We need + // to use MD5 here to implement the MONGODB-CR specification. + /* #nosec G501 */ + "crypto/md5" + + "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" + "go.mongodb.org/mongo-driver/v2/x/mongo/driver" + "go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation" +) + +// MONGODBCR is the mechanism name for MONGODB-CR. +// +// The MONGODB-CR authentication mechanism is deprecated in MongoDB 3.6 and removed in +// MongoDB 4.0. +const MONGODBCR = "MONGODB-CR" + +func newMongoDBCRAuthenticator(cred *Cred, _ *http.Client) (Authenticator, error) { + source := cred.Source + if source == "" { + source = "admin" + } + return &MongoDBCRAuthenticator{ + DB: source, + Username: cred.Username, + Password: cred.Password, + }, nil +} + +// MongoDBCRAuthenticator uses the MONGODB-CR algorithm to authenticate a connection. +// +// The MONGODB-CR authentication mechanism is deprecated in MongoDB 3.6 and removed in +// MongoDB 4.0. +type MongoDBCRAuthenticator struct { + DB string + Username string + Password string +} + +// Auth authenticates the connection. +// +// The MONGODB-CR authentication mechanism is deprecated in MongoDB 3.6 and removed in +// MongoDB 4.0. +func (a *MongoDBCRAuthenticator) Auth(ctx context.Context, cfg *driver.AuthConfig) error { + + db := a.DB + if db == "" { + db = defaultAuthDB + } + + doc := bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendInt32Element(nil, "getnonce", 1)) + cmd := operation.NewCommand(doc). + Database(db). + Deployment(driver.SingleConnectionDeployment{C: cfg.Connection}). + ClusterClock(cfg.ClusterClock). + ServerAPI(cfg.ServerAPI) + err := cmd.Execute(ctx) + if err != nil { + return newError(err, MONGODBCR) + } + rdr := cmd.Result() + + var getNonceResult struct { + Nonce string `bson:"nonce"` + } + + err = bson.Unmarshal(rdr, &getNonceResult) + if err != nil { + return newAuthError("unmarshal error", err) + } + + doc = bsoncore.BuildDocumentFromElements(nil, + bsoncore.AppendInt32Element(nil, "authenticate", 1), + bsoncore.AppendStringElement(nil, "user", a.Username), + bsoncore.AppendStringElement(nil, "nonce", getNonceResult.Nonce), + bsoncore.AppendStringElement(nil, "key", a.createKey(getNonceResult.Nonce)), + ) + cmd = operation.NewCommand(doc). + Database(db). + Deployment(driver.SingleConnectionDeployment{C: cfg.Connection}). + ClusterClock(cfg.ClusterClock). + ServerAPI(cfg.ServerAPI) + err = cmd.Execute(ctx) + if err != nil { + return newError(err, MONGODBCR) + } + + return nil +} + +// Reauth reauthenticates the connection. +func (a *MongoDBCRAuthenticator) Reauth(_ context.Context, _ *driver.AuthConfig) error { + return newAuthError("MONGODB-CR does not support reauthentication", nil) +} + +func (a *MongoDBCRAuthenticator) createKey(nonce string) string { + // Ignore gosec warning "Use of weak cryptographic primitive". We need to use MD5 here to + // implement the MONGODB-CR specification. + /* #nosec G401 */ + h := md5.New() + + _, _ = io.WriteString(h, nonce) + _, _ = io.WriteString(h, a.Username) + _, _ = io.WriteString(h, mongoPasswordDigest(a.Username, a.Password)) + return fmt.Sprintf("%x", h.Sum(nil)) +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go index 11d52621..c476ac86 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go @@ -13,7 +13,6 @@ import ( "io" "net/http" "net/url" - "os" "regexp" "strings" "sync" @@ -28,44 +27,33 @@ import ( // MongoDBOIDC is the string constant for the MONGODB-OIDC authentication mechanism. const MongoDBOIDC = "MONGODB-OIDC" -// Valid authMechanismProperties keys for MONGODB-OIDC. -const ( - // EnvironmentProp is the property key name that specifies the environment for the OIDC authenticator. - EnvironmentProp = "ENVIRONMENT" +// EnvironmentProp is the property key name that specifies the environment for the OIDC authenticator. +const EnvironmentProp = "ENVIRONMENT" - // ResourceProp is the property key name that specifies the token resource for GCP and AZURE OIDC auth. - ResourceProp = "TOKEN_RESOURCE" +// ResourceProp is the property key name that specifies the token resource for GCP and AZURE OIDC auth. +const ResourceProp = "TOKEN_RESOURCE" - // AllowedHostsProp is the property key name that specifies the allowed hosts for the OIDC authenticator. - AllowedHostsProp = "ALLOWED_HOSTS" -) - -// Valid ENVIRONMENT authMechismProperty values for MONGODB-OIDC. -const ( - // AzureEnvironmentValue is the value for the Azure environment. - AzureEnvironmentValue = "azure" +// AllowedHostsProp is the property key name that specifies the allowed hosts for the OIDC authenticator. +const AllowedHostsProp = "ALLOWED_HOSTS" - // GCPEnvironmentValue is the value for the GCP environment. - GCPEnvironmentValue = "gcp" +// AzureEnvironmentValue is the value for the Azure environment. +const AzureEnvironmentValue = "azure" - // K8SEnvironmentValue is the value for Kubernetes environments. - K8SEnvironmentValue = "k8s" +// GCPEnvironmentValue is the value for the GCP environment. +const GCPEnvironmentValue = "gcp" - // TestEnvironmentValue is the value for the test environment. - TestEnvironmentValue = "test" -) +// TestEnvironmentValue is the value for the test environment. +const TestEnvironmentValue = "test" -const ( - apiVersion = 1 - invalidateSleepTimeout = 100 * time.Millisecond +const apiVersion = 1 +const invalidateSleepTimeout = 100 * time.Millisecond - // The CSOT specification says to apply a 1-minute timeout if "CSOT is not applied". That's - // ambiguous for the v1.x Go Driver because it could mean either "no timeout provided" or "CSOT not - // enabled". Always use a maximum timeout duration of 1 minute, allowing us to ignore the ambiguity. - // Contexts with a shorter timeout are unaffected. - machineCallbackTimeout = time.Minute - humanCallbackTimeout = 5 * time.Minute -) +// The CSOT specification says to apply a 1-minute timeout if "CSOT is not applied". That's +// ambiguous for the v1.x Go Driver because it could mean either "no timeout provided" or "CSOT not +// enabled". Always use a maximum timeout duration of 1 minute, allowing us to ignore the ambiguity. +// Contexts with a shorter timeout are unaffected. +const machineCallbackTimeout = time.Minute +const humanCallbackTimeout = 5 * time.Minute var defaultAllowedHosts = []*regexp.Regexp{ regexp.MustCompile(`^.*[.]mongodb[.]net(:\d+)?$`), @@ -131,12 +119,14 @@ func newOIDCAuthenticator(cred *Cred, httpClient *http.Client) (Authenticator, e if cred.Props != nil { if env, ok := cred.Props[EnvironmentProp]; ok { switch strings.ToLower(env) { - case AzureEnvironmentValue, GCPEnvironmentValue: + case AzureEnvironmentValue: + fallthrough + case GCPEnvironmentValue: if _, ok := cred.Props[ResourceProp]; !ok { return nil, fmt.Errorf("%q must be specified for %q %q", ResourceProp, env, EnvironmentProp) } fallthrough - case K8SEnvironmentValue, TestEnvironmentValue: + case TestEnvironmentValue: if cred.OIDCMachineCallback != nil || cred.OIDCHumanCallback != nil { return nil, fmt.Errorf("OIDC callbacks are not allowed for %q %q", env, EnvironmentProp) } @@ -291,8 +281,6 @@ func (oa *OIDCAuthenticator) providerCallback() (OIDCCallback, error) { return nil, newAuthError(fmt.Sprintf("%q must be specified for GCP OIDC", ResourceProp), nil) } return getGCPOIDCCallback(resource, oa.httpClient), nil - case K8SEnvironmentValue: - return k8sOIDCCallback, nil } return nil, fmt.Errorf("%q %q not supported for MONGODB-OIDC", EnvironmentProp, env) @@ -372,29 +360,6 @@ func getGCPOIDCCallback(resource string, httpClient *http.Client) OIDCCallback { } } -// k8sOIDCCallbackfunc is the callback for the Kubernetes token provider. -func k8sOIDCCallback(context.Context, *OIDCArgs) (*OIDCCredential, error) { - // Check for the presence of the Azure and AWS token file path environment - // variables. If neither are set, use the GKE default token file path. - var path string - if p := os.Getenv("AZURE_FEDERATED_TOKEN_FILE"); p != "" { - path = p - } else if p := os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE"); p != "" { - path = p - } else { - path = "/var/run/secrets/kubernetes.io/serviceaccount/token" - } - - token, err := os.ReadFile(path) - if err != nil { - return nil, fmt.Errorf("error reading OIDC token from %q: %w", path, err) - } - - return &OIDCCredential{ - AccessToken: string(token), - }, nil -} - func (oa *OIDCAuthenticator) getAccessToken( ctx context.Context, conn *mnet.Connection, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go index 00674fbd..f4447396 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go @@ -34,7 +34,7 @@ var ErrNoCursor = errors.New("database response does not contain a cursor") type BatchCursor struct { clientSession *session.Client clock *session.ClusterClock - comment any + comment interface{} encoderFn codecutil.EncoderFn database string collection string @@ -381,40 +381,14 @@ func (bc *BatchCursor) getMore(ctx context.Context) { bc.err = Operation{ CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { - // If maxAwaitTime > remaining timeoutMS - minRoundTripTime, then use - // send remaining TimeoutMS - minRoundTripTime allowing the server an - // opportunity to respond with an empty batch. - var maxTimeMS int64 - if bc.maxAwaitTime != nil { - _, ctxDeadlineSet := ctx.Deadline() - - if ctxDeadlineSet { - rttMonitor := bc.Server().RTTMonitor() - - var ok bool - maxTimeMS, ok = driverutil.CalculateMaxTimeMS(ctx, rttMonitor.Min()) - if !ok && maxTimeMS <= 0 { - return nil, fmt.Errorf( - "calculated server-side timeout (%v ms) is less than or equal to 0 (%v): %w", - maxTimeMS, - rttMonitor.Stats(), - ErrDeadlineWouldBeExceeded) - } - } - - if !ctxDeadlineSet || bc.maxAwaitTime.Milliseconds() < maxTimeMS { - maxTimeMS = bc.maxAwaitTime.Milliseconds() - } - } - dst = bsoncore.AppendInt64Element(dst, "getMore", bc.id) dst = bsoncore.AppendStringElement(dst, "collection", bc.collection) if numToReturn > 0 { dst = bsoncore.AppendInt32Element(dst, "batchSize", numToReturn) } - if maxTimeMS > 0 { - dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", maxTimeMS) + if bc.maxAwaitTime != nil && *bc.maxAwaitTime > 0 { + dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", int64(*bc.maxAwaitTime)/int64(time.Millisecond)) } comment, err := codecutil.MarshalValue(bc.comment, bc.encoderFn) @@ -531,7 +505,7 @@ func (bc *BatchCursor) SetMaxAwaitTime(dur time.Duration) { } // SetComment sets the comment for future getMore operations. -func (bc *BatchCursor) SetComment(comment any) { +func (bc *BatchCursor) SetComment(comment interface{}) { bc.comment = comment } @@ -545,12 +519,6 @@ func (bc *BatchCursor) getOperationDeployment() Deployment { return SingleServerDeployment{bc.server} } -// MaxAwaitTime returns the maximum amount of time the server will allow -// the operations to execute. This is only valid for tailable awaitData cursors. -func (bc *BatchCursor) MaxAwaitTime() *time.Duration { - return bc.maxAwaitTime -} - // loadBalancedCursorDeployment is used as a Deployment for getMore and killCursors commands when pinning to a // connection in load balanced mode. This type also functions as an ErrorProcessor to ensure that SDAM errors are // handled for these commands in this mode. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go index ccf4534e..c9f9fd46 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go @@ -110,7 +110,7 @@ func (e *zlibEncoder) Encode(dst, src []byte) ([]byte, error) { } var zstdBufPool = sync.Pool{ - New: func() any { + New: func() interface{} { s := make([]byte, 0) return &s }, @@ -147,7 +147,7 @@ func CompressPayload(in []byte, opts CompressionOpts) ([]byte, error) { } var zstdReaderPool = sync.Pool{ - New: func() any { + New: func() interface{} { r, _ := zstd.NewReader(nil) return r }, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go index 8edad674..ece143a1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go @@ -297,6 +297,8 @@ func (u *ConnString) setDefaultAuthParams(dbName string) error { } else if u.AuthSource != "$external" { return fmt.Errorf("auth source must be $external") } + case "mongodb-cr": + fallthrough case "scram-sha-1": fallthrough case "scram-sha-256": @@ -694,6 +696,16 @@ func (u *ConnString) addOptions(connectionArgPairs []string) error { func (u *ConnString) validateAuth() error { switch strings.ToLower(u.AuthMechanism) { + case "mongodb-cr": + if u.Username == "" { + return fmt.Errorf("username required for MONGO-CR") + } + if u.Password == "" { + return fmt.Errorf("password required for MONGO-CR") + } + if u.AuthMechanismProperties != nil { + return fmt.Errorf("MONGO-CR cannot have mechanism properties") + } case "mongodb-x509": if u.Password != "" { return fmt.Errorf("password cannot be specified for MONGO-X509") diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go index 91b950c3..7f7c3e8f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go @@ -20,7 +20,6 @@ import ( "errors" "fmt" "net/http" - "time" "unsafe" "go.mongodb.org/mongo-driver/v2/bson" @@ -90,17 +89,6 @@ func NewMongoCrypt(opts *options.MongoCryptOptions) (*MongoCrypt, error) { C.mongocrypt_setopt_bypass_query_analysis(crypt.wrapped) } - var keyExpirationMs uint64 = 60_000 // 60,000 ms - if opts.KeyExpiration != nil { - if *opts.KeyExpiration <= 0 { - keyExpirationMs = 0 - } else { - // find the ceiling integer millisecond for the expiration - keyExpirationMs = uint64((*opts.KeyExpiration + time.Millisecond - 1) / time.Millisecond) - } - } - C.mongocrypt_setopt_key_expiration(crypt.wrapped, C.uint64_t(keyExpirationMs)) - // If loading the crypt_shared library isn't disabled, set the default library search path "$SYSTEM" // and set a library override path if one was provided. if !opts.CryptSharedLibDisabled { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go index 504065d4..c6474a4b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go @@ -8,7 +8,6 @@ package options import ( "net/http" - "time" "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" ) @@ -22,7 +21,6 @@ type MongoCryptOptions struct { CryptSharedLibDisabled bool CryptSharedLibOverridePath string HTTPClient *http.Client - KeyExpiration *time.Duration } // MongoCrypt creates a new MongoCryptOptions instance. @@ -72,10 +70,3 @@ func (mo *MongoCryptOptions) SetHTTPClient(httpClient *http.Client) *MongoCryptO mo.HTTPClient = httpClient return mo } - -// SetKeyExpiration sets the key expiration duration. 0 means "never expire". -// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up. -func (mo *MongoCryptOptions) SetKeyExpiration(expiration *time.Duration) *MongoCryptOptions { - mo.KeyExpiration = expiration - return mo -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go index 57ec762e..2597a5de 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go @@ -158,43 +158,13 @@ type ResponseInfo struct { } func redactStartedInformationCmd(info startedInformation) bson.Raw { - intLen := func(n int) int { - if n == 0 { - return 1 // Special case: 0 has one digit - } - count := 0 - for n > 0 { - n /= 10 - count++ - } - return count - } - var cmdCopy bson.Raw // Make a copy of the command. Redact if the command is security // sensitive and cannot be monitored. If there was a type 1 payload for // the current batch, convert it to a BSON array if !info.redacted { - cmdLen := len(info.cmd) - for _, seq := range info.documentSequences { - cmdLen += 7 // 2 (header) + 4 (array length) + 1 (array end) - cmdLen += len(seq.identifier) - data := seq.data - i := 0 - for { - doc, rest, ok := bsoncore.ReadDocument(data) - if !ok { - break - } - data = rest - cmdLen += len(doc) - cmdLen += intLen(i) - i++ - } - } - - cmdCopy = make([]byte, 0, cmdLen) + cmdCopy = make([]byte, 0, len(info.cmd)) cmdCopy = append(cmdCopy, info.cmd...) if len(info.documentSequences) > 0 { @@ -534,7 +504,7 @@ func (op Operation) Validate() error { } var memoryPool = sync.Pool{ - New: func() any { + New: func() interface{} { // Start with 1kb buffers. b := make([]byte, 1024) // Return a pointer as the static analysis tool suggests. @@ -1754,16 +1724,34 @@ func (op Operation) calculateMaxTimeMS(ctx context.Context, rttMin time.Duration return 0, nil } - // Calculate maxTimeMS value to potentially be appended to the wire message. - maxTimeMS, ok := driverutil.CalculateMaxTimeMS(ctx, rttMin) - if !ok && maxTimeMS <= 0 { + deadline, ok := ctx.Deadline() + if !ok { + return 0, nil + } + + remainingTimeout := time.Until(deadline) + + // Always round up to the next millisecond value so we never truncate the calculated + // maxTimeMS value (e.g. 400 microseconds evaluates to 1ms, not 0ms). + maxTimeMS := int64((remainingTimeout - rttMin + time.Millisecond - 1) / time.Millisecond) + if maxTimeMS <= 0 { return 0, fmt.Errorf( - "calculated server-side timeout (%v ms) is less than or equal to 0 (%v): %w", - maxTimeMS, + "remaining time %v until context deadline is less than or equal to min network round-trip time %v (%v): %w", + remainingTimeout, + rttMin, rttStats, ErrDeadlineWouldBeExceeded) } + // The server will return a "BadValue" error if maxTimeMS is greater + // than the maximum positive int32 value (about 24.9 days). If the + // user specified a timeout value greater than that, omit maxTimeMS + // and let the client-side timeout handle cancelling the op if the + // timeout is ever reached. + if maxTimeMS > math.MaxInt32 { + return 0, nil + } + return maxTimeMS, nil } @@ -1838,6 +1826,7 @@ func (op Operation) createReadPref(desc description.SelectedServer, isOpQuery bo // TODO if supplied readPreference was "overwritten" with primary in description.selectForReplicaSet. if desc.Server.Kind == description.ServerKindStandalone || (isOpQuery && desc.Server.Kind != description.ServerKindMongos) || + op.Type == Write || (op.IsOutputAggregate && desc.Server.WireVersion.Max < 13) { // Don't send read preference for: // 1. all standalones diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go index 380789ab..396a5693 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go @@ -50,7 +50,6 @@ type Aggregate struct { customOptions map[string]bsoncore.Value timeout *time.Duration omitMaxTimeMS bool - rawData *bool result driver.CursorResponse } @@ -160,10 +159,6 @@ func (a *Aggregate) command(dst []byte, desc description.SelectedServer) ([]byte if a.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", a.let) } - // Set rawData for 8.2+ servers. - if a.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *a.rawData) - } for optionName, optionValue := range a.customOptions { dst = bsoncore.AppendValueElement(dst, optionName, optionValue) } @@ -203,7 +198,7 @@ func (a *Aggregate) BypassDocumentValidation(bypassDocumentValidation bool) *Agg return a } -// Collation specifies a collation. +// Collation specifies a collation. This option is only valid for server versions 3.4 and above. func (a *Aggregate) Collation(collation bsoncore.Document) *Aggregate { if a == nil { a = new(Aggregate) @@ -436,13 +431,3 @@ func (a *Aggregate) OmitMaxTimeMS(omit bool) *Aggregate { a.omitMaxTimeMS = omit return a } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (a *Aggregate) RawData(rawData bool) *Aggregate { - if a == nil { - a = new(Aggregate) - } - - a.rawData = &rawData - return a -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go index d056702a..5ecaa3a9 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go @@ -41,7 +41,6 @@ type Count struct { result CountResult serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool } // CountResult represents a count result returned by the server. @@ -140,7 +139,7 @@ func (c *Count) Execute(ctx context.Context) error { return err } -func (c *Count) command(dst []byte, desc description.SelectedServer) ([]byte, error) { +func (c *Count) command(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "count", c.collection) if c.query != nil { dst = bsoncore.AppendDocumentElement(dst, "query", c.query) @@ -148,10 +147,6 @@ func (c *Count) command(dst []byte, desc description.SelectedServer) ([]byte, er if c.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", c.comment) } - // Set rawData for 8.2+ servers. - if c.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *c.rawData) - } return dst, nil } @@ -315,13 +310,3 @@ func (c *Count) Authenticator(authenticator driver.Authenticator) *Count { c.authenticator = authenticator return c } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (c *Count) RawData(rawData bool) *Count { - if c == nil { - c = new(Count) - } - - c.rawData = &rawData - return c -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go index f9a406db..840d0ba4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go @@ -151,7 +151,7 @@ func (c *Create) Capped(capped bool) *Create { return c } -// Collation specifies a collation. +// Collation specifies a collation. This option is only valid for server versions 3.4 and above. func (c *Create) Collation(collation bsoncore.Document) *Create { if c == nil { c = new(Create) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go index 17e88ba8..0380a55a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go @@ -38,7 +38,6 @@ type CreateIndexes struct { result CreateIndexesResult serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool } // CreateIndexesResult represents a createIndexes result returned by the server. @@ -134,10 +133,6 @@ func (ci *CreateIndexes) command(dst []byte, desc description.SelectedServer) ([ if ci.indexes != nil { dst = bsoncore.AppendArrayElement(dst, "indexes", ci.indexes) } - // Set rawData for 8.2+ servers. - if ci.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *ci.rawData) - } return dst, nil } @@ -282,13 +277,3 @@ func (ci *CreateIndexes) Authenticator(authenticator driver.Authenticator) *Crea ci.authenticator = authenticator return ci } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (ci *CreateIndexes) RawData(rawData bool) *CreateIndexes { - if ci == nil { - ci = new(CreateIndexes) - } - - ci.rawData = &rawData - return ci -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go index e4510fb8..39420efc 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go @@ -43,7 +43,6 @@ type Delete struct { serverAPI *driver.ServerAPIOptions let bsoncore.Document timeout *time.Duration - rawData *bool logger *logger.Logger } @@ -140,10 +139,6 @@ func (d *Delete) command(dst []byte, desc description.SelectedServer) ([]byte, e if d.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", d.let) } - // Set rawData for 8.2+ servers. - if d.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *d.rawData) - } return dst, nil } @@ -282,7 +277,8 @@ func (d *Delete) Retry(retry driver.RetryMode) *Delete { } // Hint is a flag to indicate that the update document contains a hint. Hint is only supported by -// servers >= 4.4. Older servers will report an error for using the hint option. +// servers >= 4.4. Older servers >= 3.4 will report an error for using the hint option. For servers < +// 3.4, the driver will return an error if the hint option is used. func (d *Delete) Hint(hint bool) *Delete { if d == nil { d = new(Delete) @@ -342,13 +338,3 @@ func (d *Delete) Authenticator(authenticator driver.Authenticator) *Delete { d.authenticator = authenticator return d } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (d *Delete) RawData(rawData bool) *Delete { - if d == nil { - d = new(Delete) - } - - d.rawData = &rawData - return d -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go index ef235e24..89d412de 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go @@ -43,7 +43,6 @@ type Distinct struct { result DistinctResult serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool } // DistinctResult represents a distinct result returned by the server. @@ -131,10 +130,6 @@ func (d *Distinct) command(dst []byte, desc description.SelectedServer) ([]byte, if d.query != nil { dst = bsoncore.AppendDocumentElement(dst, "query", d.query) } - // Set rawData for 8.2+ servers. - if d.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *d.rawData) - } return dst, nil } @@ -328,13 +323,3 @@ func (d *Distinct) Authenticator(authenticator driver.Authenticator) *Distinct { d.authenticator = authenticator return d } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (d *Distinct) RawData(rawData bool) *Distinct { - if d == nil { - d = new(Distinct) - } - - d.rawData = &rawData - return d -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go index 14ecbdc1..e57cff72 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go @@ -37,7 +37,6 @@ type DropIndexes struct { result DropIndexesResult serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool } // DropIndexesResult represents a dropIndexes result returned by the server. @@ -105,7 +104,7 @@ func (di *DropIndexes) Execute(ctx context.Context) error { } -func (di *DropIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) { +func (di *DropIndexes) command(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "dropIndexes", di.collection) switch t := di.index.(type) { @@ -116,10 +115,6 @@ func (di *DropIndexes) command(dst []byte, desc description.SelectedServer) ([]b dst = bsoncore.AppendDocumentElement(dst, "index", t) } } - // Set rawData for 8.2+ servers. - if di.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *di.rawData) - } return dst, nil } @@ -253,13 +248,3 @@ func (di *DropIndexes) Authenticator(authenticator driver.Authenticator) *DropIn di.authenticator = authenticator return di } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (di *DropIndexes) RawData(rawData bool) *DropIndexes { - if di == nil { - di = new(DropIndexes) - } - - di.rawData = &rawData - return di -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go index 615e2408..b607cb14 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go @@ -61,7 +61,6 @@ type Find struct { result driver.CursorResponse serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool logger *logger.Logger omitMaxTimeMS bool } @@ -192,10 +191,6 @@ func (f *Find) command(dst []byte, desc description.SelectedServer) ([]byte, err if f.tailable != nil { dst = bsoncore.AppendBooleanElement(dst, "tailable", *f.tailable) } - // Set rawData for 8.2+ servers. - if f.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *f.rawData) - } return dst, nil } @@ -570,16 +565,6 @@ func (f *Find) Authenticator(authenticator driver.Authenticator) *Find { return f } -// RawData sets the rawData to access timeseries data in the compressed format. -func (f *Find) RawData(rawData bool) *Find { - if f == nil { - f = new(Find) - } - - f.rawData = &rawData - return f -} - // OmitMaxTimeMS omits the automatically-calculated "maxTimeMS" from the // command. func (f *Find) OmitMaxTimeMS(omit bool) *Find { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go index 09205681..505c56b0 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go @@ -50,7 +50,6 @@ type FindAndModify struct { serverAPI *driver.ServerAPIOptions let bsoncore.Document timeout *time.Duration - rawData *bool result FindAndModifyResult } @@ -60,7 +59,7 @@ type LastErrorObject struct { // True if an update modified an existing document UpdatedExisting bool // Object ID of the upserted document. - Upserted any + Upserted interface{} } // FindAndModifyResult represents a findAndModify result returned by the server. @@ -212,10 +211,6 @@ func (fam *FindAndModify) command(dst []byte, desc description.SelectedServer) ( if fam.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", fam.let) } - // Set rawData for 8.2+ servers. - if fam.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *fam.rawData) - } return dst, nil } @@ -481,13 +476,3 @@ func (fam *FindAndModify) Authenticator(authenticator driver.Authenticator) *Fin fam.authenticator = authenticator return fam } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (fam *FindAndModify) RawData(rawData bool) *FindAndModify { - if fam == nil { - fam = new(FindAndModify) - } - - fam.rawData = &rawData - return fam -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go index 57d461ae..b48e2c85 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go @@ -42,7 +42,6 @@ type Insert struct { result InsertResult serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool logger *logger.Logger } @@ -133,10 +132,6 @@ func (i *Insert) command(dst []byte, desc description.SelectedServer) ([]byte, e if i.ordered != nil { dst = bsoncore.AppendBooleanElement(dst, "ordered", *i.ordered) } - // Set rawData for 8.2+ servers. - if i.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *i.rawData) - } return dst, nil } @@ -323,13 +318,3 @@ func (i *Insert) Authenticator(authenticator driver.Authenticator) *Insert { i.authenticator = authenticator return i } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (i *Insert) RawData(rawData bool) *Insert { - if i == nil { - i = new(Insert) - } - - i.rawData = &rawData - return i -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go index 672404cb..3f9b55a6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go @@ -39,7 +39,6 @@ type ListCollections struct { batchSize *int32 serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool } // NewListCollections constructs and returns a new ListCollections. @@ -93,7 +92,7 @@ func (lc *ListCollections) Execute(ctx context.Context) error { } -func (lc *ListCollections) command(dst []byte, desc description.SelectedServer) ([]byte, error) { +func (lc *ListCollections) command(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendInt32Element(dst, "listCollections", 1) if lc.filter != nil { dst = bsoncore.AppendDocumentElement(dst, "filter", lc.filter) @@ -111,11 +110,6 @@ func (lc *ListCollections) command(dst []byte, desc description.SelectedServer) } dst = bsoncore.AppendDocumentElement(dst, "cursor", cursorDoc.Build()) - // Set rawData for 8.2+ servers. - if lc.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *lc.rawData) - } - return dst, nil } @@ -280,13 +274,3 @@ func (lc *ListCollections) Authenticator(authenticator driver.Authenticator) *Li lc.authenticator = authenticator return lc } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (lc *ListCollections) RawData(rawData bool) *ListCollections { - if lc == nil { - lc = new(ListCollections) - } - - lc.rawData = &rawData - return lc -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go index 21b138a4..d7642a19 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go @@ -34,7 +34,6 @@ type ListIndexes struct { crypt driver.Crypt serverAPI *driver.ServerAPIOptions timeout *time.Duration - rawData *bool result driver.CursorResponse } @@ -92,19 +91,16 @@ func (li *ListIndexes) Execute(ctx context.Context) error { } -func (li *ListIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) { +func (li *ListIndexes) command(dst []byte, _ description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "listIndexes", li.collection) cursorIdx, cursorDoc := bsoncore.AppendDocumentStart(nil) if li.batchSize != nil { + cursorDoc = bsoncore.AppendInt32Element(cursorDoc, "batchSize", *li.batchSize) } cursorDoc, _ = bsoncore.AppendDocumentEnd(cursorDoc, cursorIdx) dst = bsoncore.AppendDocumentElement(dst, "cursor", cursorDoc) - // Set rawData for 8.2+ servers. - if li.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *li.rawData) - } return dst, nil } @@ -239,13 +235,3 @@ func (li *ListIndexes) Authenticator(authenticator driver.Authenticator) *ListIn li.authenticator = authenticator return li } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (li *ListIndexes) RawData(rawData bool) *ListIndexes { - if li == nil { - li = new(ListIndexes) - } - - li.rawData = &rawData - return li -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go index 00e193ef..186f9463 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go @@ -46,14 +46,13 @@ type Update struct { serverAPI *driver.ServerAPIOptions let bsoncore.Document timeout *time.Duration - rawData *bool logger *logger.Logger } // Upsert contains the information for an upsert in an Update operation. type Upsert struct { Index int64 - ID any `bson:"_id"` + ID interface{} `bson:"_id"` } // UpdateResult contains information for the result of an Update operation. @@ -204,15 +203,12 @@ func (u *Update) command(dst []byte, desc description.SelectedServer) ([]byte, e if u.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", u.let) } - // Set rawData for 8.2+ servers. - if u.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { - dst = bsoncore.AppendBooleanElement(dst, "rawData", *u.rawData) - } return dst, nil } -// BypassDocumentValidation allows the operation to opt-out of document level validation. +// BypassDocumentValidation allows the operation to opt-out of document level validation. Valid +// for server versions >= 3.2. For servers < 3.2, this setting is ignored. func (u *Update) BypassDocumentValidation(bypassDocumentValidation bool) *Update { if u == nil { u = new(Update) @@ -223,7 +219,8 @@ func (u *Update) BypassDocumentValidation(bypassDocumentValidation bool) *Update } // Hint is a flag to indicate that the update document contains a hint. Hint is only supported by -// servers >= 4.2. Older servers will report an error for using the hint option. +// servers >= 4.2. Older servers >= 3.4 will report an error for using the hint option. For servers < +// 3.4, the driver will return an error if the hint option is used. func (u *Update) Hint(hint bool) *Update { if u == nil { u = new(Update) @@ -233,7 +230,8 @@ func (u *Update) Hint(hint bool) *Update { return u } -// ArrayFilters is a flag to indicate that the update document contains an arrayFilters field. +// ArrayFilters is a flag to indicate that the update document contains an arrayFilters field. This option is only +// supported on server versions 3.6 and higher. For servers < 3.6, the driver will return an error. func (u *Update) ArrayFilters(arrayFilters bool) *Update { if u == nil { u = new(Update) @@ -427,13 +425,3 @@ func (u *Update) Authenticator(authenticator driver.Authenticator) *Update { u.authenticator = authenticator return u } - -// RawData sets the rawData to access timeseries data in the compressed format. -func (u *Update) RawData(rawData bool) *Update { - if u == nil { - u = new(Update) - } - - u.rawData = &rawData - return u -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go index b1bf1d13..24ad6a3a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go @@ -14,6 +14,7 @@ import ( "fmt" "io" "net" + "os" "strings" "sync" "sync/atomic" @@ -211,7 +212,7 @@ func (c *connection) connect(ctx context.Context) (err error) { // Assign the result of DialContext to a temporary net.Conn to ensure that c.nc is not set in an error case. tempNc, err := c.config.dialer.DialContext(ctx, c.addr.Network(), c.addr.String()) if err != nil { - return ConnectionError{Wrapped: err, init: true, message: fmt.Sprintf("failed to connect to %s", c.addr)} + return ConnectionError{Wrapped: err, init: true} } c.nc = tempNc @@ -228,7 +229,7 @@ func (c *connection) connect(ctx context.Context) (err error) { tlsNc, err := configureTLS(ctx, c.config.tlsConnectionSource, c.nc, c.addr, tlsConfig, ocspOpts) if err != nil { - return ConnectionError{Wrapped: err, init: true, message: fmt.Sprintf("failed to configure TLS for %s", c.addr)} + return ConnectionError{Wrapped: err, init: true} } c.nc = tlsNc } @@ -340,10 +341,7 @@ func transformNetworkError(ctx context.Context, originalError error, contextDead return originalError } if netErr, ok := originalError.(net.Error); ok && netErr.Timeout() { - return fmt.Errorf("%w: %s: %s", - context.DeadlineExceeded, - "client timed out waiting for server response", - originalError.Error()) + return fmt.Errorf("%w: %s", context.DeadlineExceeded, originalError.Error()) } return originalError @@ -415,6 +413,9 @@ func (c *connection) readWireMessage(ctx context.Context) ([]byte, error) { c.close() } message := errMsg + if errors.Is(err, io.EOF) { + message = "socket was unexpectedly closed" + } return nil, ConnectionError{ ConnectionID: c.id, Wrapped: transformNetworkError(ctx, err, contextDeadlineUsed), @@ -525,6 +526,48 @@ func (c *connection) closed() bool { return atomic.LoadInt64(&c.state) == connDisconnected } +// isAlive returns true if the connection is alive and ready to be used for an +// operation. +// +// Note that the liveness check can be slow (at least 1ms), so isAlive only +// checks the liveness of the connection if it's been idle for at least 10 +// seconds. For frequently in-use connections, a network error during an +// operation will be the first indication of a dead connection. +func (c *connection) isAlive() bool { + if c.nc == nil { + return false + } + + // If the connection has been idle for less than 10 seconds, skip the + // liveness check. + // + // The 10-seconds idle bypass is based on the liveness check implementation + // in the Python Driver. That implementation uses 1 second as the idle + // threshold, but we chose to be more conservative in the Go Driver because + // this is new behavior with unknown side-effects. See + // https://github.com/mongodb/mongo-python-driver/blob/e6b95f65953e01e435004af069a6976473eaf841/pymongo/synchronous/pool.py#L983-L985 + idleStart, ok := c.idleStart.Load().(time.Time) + if !ok || idleStart.Add(10*time.Second).After(time.Now()) { + return true + } + + // Set a 1ms read deadline and attempt to read 1 byte from the connection. + // Expect it to block for 1ms then return a deadline exceeded error. If it + // returns any other error, the connection is not usable, so return false. + // If it doesn't return an error and actually reads data, the connection is + // also not usable, so return false. + // + // Note that we don't need to un-set the read deadline because the "read" + // and "write" methods always reset the deadlines. + err := c.nc.SetReadDeadline(time.Now().Add(1 * time.Millisecond)) + if err != nil { + return false + } + var b [1]byte + _, err = c.nc.Read(b[:]) + return errors.Is(err, os.ErrDeadlineExceeded) +} + func (c *connection) idleTimeoutExpired() bool { if c.idleTimeout == 0 { return false diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go index dee19415..79f11f7f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go @@ -10,17 +10,11 @@ import ( "context" "errors" "fmt" - "io" - "net" - "os" - "strings" "time" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" ) -var _ error = ConnectionError{} - // ConnectionError represents a connection error. type ConnectionError struct { ConnectionID string @@ -34,28 +28,21 @@ type ConnectionError struct { // Error implements the error interface. func (e ConnectionError) Error() string { - var messages []string + message := e.message if e.init { - messages = append(messages, "error occurred during connection handshake") + fullMsg := "error occurred during connection handshake" + if message != "" { + fullMsg = fmt.Sprintf("%s: %s", fullMsg, message) + } + message = fullMsg } - if e.message != "" { - messages = append(messages, e.message) + if e.Wrapped != nil && message != "" { + return fmt.Sprintf("connection(%s) %s: %s", e.ConnectionID, message, e.Wrapped.Error()) } if e.Wrapped != nil { - if errors.Is(e.Wrapped, io.EOF) { - messages = append(messages, "connection closed unexpectedly by the other side") - } - if errors.Is(e.Wrapped, os.ErrDeadlineExceeded) { - messages = append(messages, "client timed out waiting for server response") - } else if err, ok := e.Wrapped.(net.Error); ok && err.Timeout() { - messages = append(messages, "client timed out waiting for server response") - } - messages = append(messages, e.Wrapped.Error()) - } - if len(messages) > 0 { - return fmt.Sprintf("connection(%s) %s", e.ConnectionID, strings.Join(messages, ": ")) + return fmt.Sprintf("connection(%s) %s", e.ConnectionID, e.Wrapped.Error()) } - return fmt.Sprintf("connection(%s)", e.ConnectionID) + return fmt.Sprintf("connection(%s) %s", e.ConnectionID, message) } // Unwrap returns the underlying error. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go index 530b2169..3cc06656 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go @@ -20,7 +20,7 @@ import ( var ( // MinSupportedMongoDBVersion is the version string for the lowest MongoDB version supported by the driver. - MinSupportedMongoDBVersion = "4.0" + MinSupportedMongoDBVersion = "3.6" // SupportedWireVersions is the range of wire versions supported by the driver. SupportedWireVersions = driverutil.NewVersionRange(driverutil.MinWireVersion, driverutil.MaxWireVersion) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go index 23656864..d6568e84 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go @@ -143,7 +143,7 @@ func mustLogPoolMessage(pool *pool) bool { logger.LevelDebug, logger.ComponentConnection) } -func logPoolMessage(pool *pool, msg string, keysAndValues ...any) { +func logPoolMessage(pool *pool, msg string, keysAndValues ...interface{}) { host, port, err := net.SplitHostPort(pool.address.String()) if err != nil { host = pool.address.String() @@ -169,9 +169,11 @@ type reason struct { // connectionPerished checks if a given connection is perished and should be removed from the pool. func connectionPerished(conn *connection) (reason, bool) { switch { - case conn.closed(): + case conn.closed() || !conn.isAlive(): // A connection would only be closed if it encountered a network error - // during an operation and closed itself. + // during an operation and closed itself. If a connection is not alive + // (e.g. the connection was closed by the server-side), it's also + // considered a network error. return reason{ loggerConn: logger.ReasonConnClosedError, event: event.ReasonError, @@ -503,19 +505,7 @@ func (p *pool) checkOut(ctx context.Context) (conn *connection, err error) { } return nil, ErrPoolClosed case poolPaused: - // Wrap poolCleared in a driver.Error so we can add the - // "TransientTransactionError" label. This will add - // "TransientTransactionError" to all poolClearedError instances, not - // just those that happened during transactions. While that behavior is - // different than other places we add "TransientTransactionError", it is - // consistent with the Transactions specification and simplifies the - // code. - pcErr := poolClearedError{err: p.lastClearErr, address: p.address} - err := driver.Error{ - Message: pcErr.Error(), - Labels: []string{driver.TransientTransactionError}, - Wrapped: pcErr, - } + err := poolClearedError{err: p.lastClearErr, address: p.address} p.stateMu.RUnlock() duration := time.Since(start) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go index 90cee89e..7fab1136 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go @@ -228,7 +228,7 @@ func mustLogServerMessage(srv *Server) bool { logger.LevelDebug, logger.ComponentTopology) } -func logServerMessage(srv *Server, msg string, keysAndValues ...any) { +func logServerMessage(srv *Server, msg string, keysAndValues ...interface{}) { serverHost, serverPort, err := net.SplitHostPort(srv.address.String()) if err != nil { serverHost = srv.address.String() diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go index 5343934c..5c1e1342 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go @@ -167,7 +167,7 @@ func mustLogTopologyMessage(topo *Topology, level logger.Level) bool { level, logger.ComponentTopology) } -func logTopologyMessage(topo *Topology, level logger.Level, msg string, keysAndValues ...any) { +func logTopologyMessage(topo *Topology, level logger.Level, msg string, keysAndValues ...interface{}) { topo.cfg.logger.Print(level, logger.ComponentTopology, msg, @@ -218,7 +218,7 @@ func logServerSelection( level logger.Level, msg string, srvSelector description.ServerSelector, - keysAndValues ...any, + keysAndValues ...interface{}, ) { var srvSelectorString string @@ -405,10 +405,7 @@ func (t *Topology) Disconnect(ctx context.Context) error { t.pollingwg.Wait() } - oldDesc := t.fsm.Topology - t.fsm = newFSM() - t.desc.Store(t.fsm.Topology) - t.publishTopologyDescriptionChangedEvent(oldDesc, t.fsm.Topology) + t.desc.Store(description.Topology{}) atomic.StoreInt64(&t.state, topologyDisconnected) t.publishTopologyClosedEvent() @@ -694,6 +691,7 @@ func (t *Topology) selectServerFromSubscription( case <-ctx.Done(): return nil, ServerSelectionError{Wrapped: ctx.Err(), Desc: current} case current = <-subscriptionCh: + default: } suitable, err := t.selectServerFromDescription(current, srvSelector) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go index 2ddc7434..aefa74c5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go @@ -15,11 +15,9 @@ import ( "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/logger" - "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" - "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/ocsp" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/session" @@ -272,14 +270,6 @@ func NewConfigFromOptionsWithAuthenticator(opts *options.ClientOptions, clock *s // Required for SASL mechanism negotiation during handshake handshakeOpts.DBUser = opts.Auth.AuthSource + "." + opts.Auth.Username } - if a := optionsutil.Value(opts.Custom, "authenticateToAnything"); a != nil { - if v, ok := a.(bool); ok && v { - // Authenticate arbiters - handshakeOpts.PerformAuthentication = func(_ description.Server) bool { - return true - } - } - } handshaker = func(driver.Handshaker) driver.Handshaker { return auth.Handshaker(nil, handshakeOpts) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go index f0b1b5e5..dd16cb7b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go @@ -406,7 +406,7 @@ func ReadMsgSectionDocumentSequence(src []byte) (identifier string, docs []bsonc // sequence data. func ReadMsgSectionRawDocumentSequence(src []byte) (identifier string, data []byte, rem []byte, ok bool) { length, rem, ok := readi32(src) - if !ok || int(length) > len(src) || length < 4 { + if !ok || int(length) > len(src) || length-4 < 0 { return "", nil, src, false } diff --git a/vendor/modules.txt b/vendor/modules.txt index 10f4b1d0..e9af4278 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -240,8 +240,8 @@ github.com/xdg-go/stringprep # github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 ## explicit; go 1.17 github.com/youmark/pkcs8 -# go.mongodb.org/mongo-driver/v2 v2.3.1 -## explicit; go 1.19 +# go.mongodb.org/mongo-driver/v2 v2.1.0 +## explicit; go 1.18 go.mongodb.org/mongo-driver/v2/bson go.mongodb.org/mongo-driver/v2/event go.mongodb.org/mongo-driver/v2/internal/aws @@ -260,7 +260,6 @@ go.mongodb.org/mongo-driver/v2/internal/handshake go.mongodb.org/mongo-driver/v2/internal/httputil go.mongodb.org/mongo-driver/v2/internal/logger go.mongodb.org/mongo-driver/v2/internal/mongoutil -go.mongodb.org/mongo-driver/v2/internal/optionsutil go.mongodb.org/mongo-driver/v2/internal/ptrutil go.mongodb.org/mongo-driver/v2/internal/rand go.mongodb.org/mongo-driver/v2/internal/randutil From 3040aadcd23d2c7f016cd0b68f7cbf2a7c21fbbe Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:51:38 -0500 Subject: [PATCH 11/21] =?UTF-8?q?update=20version-supported=20=E2=80=A6=20?= =?UTF-8?q?why=20did=20this=20work=20before=3F=3F=3F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/verifier/uri.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/verifier/uri.go b/internal/verifier/uri.go index c5ed2cb8..2c99948b 100644 --- a/internal/verifier/uri.go +++ b/internal/verifier/uri.go @@ -79,14 +79,14 @@ func (verifier *Verifier) maybeSuggestHashedComparisonOptimization() { } func isVersionSupported(version []int) bool { - if version[0] >= 5 { + if version[0] >= 4 { return true } - if version[0] < 4 { + if version[0] < 3 { return false } - return version[1] >= 2 + return version[1] >= 6 } func (verifier *Verifier) SetDstURI(ctx context.Context, uri string) error { From 1b7bc28bdde647586d90107d1ffd0588c6e6beb0 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 09:52:40 -0500 Subject: [PATCH 12/21] pare back --- .github/workflows/all.yml | 50 +++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index a36bf1b1..e73ce518 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -45,36 +45,36 @@ jobs: # versions are: source, destination mongodb_versions: - [ '4.2', '4.2' ] - - [ '4.2', '4.4' ] - - [ '4.2', '5.0' ] - - [ '4.2', '6.0' ] - - [ '4.2', '8.0' ] - - - [ '4.4', '4.4' ] - - [ '4.4', '5.0' ] - - [ '4.4', '6.0' ] - - [ '4.4', '8.0' ] - - - [ '5.0', '5.0' ] - - [ '5.0', '6.0' ] - - [ '5.0', '7.0' ] - - [ '5.0', '8.0' ] - - - [ '6.0', '6.0' ] - - [ '6.0', '7.0' ] - - [ '6.0', '8.0' ] - - - [ '7.0', '7.0' ] - - [ '7.0', '8.0' ] - - - [ '8.0', '8.0' ] +# - [ '4.2', '4.4' ] +# - [ '4.2', '5.0' ] +# - [ '4.2', '6.0' ] +# - [ '4.2', '8.0' ] +# +# - [ '4.4', '4.4' ] +# - [ '4.4', '5.0' ] +# - [ '4.4', '6.0' ] +# - [ '4.4', '8.0' ] +# +# - [ '5.0', '5.0' ] +# - [ '5.0', '6.0' ] +# - [ '5.0', '7.0' ] +# - [ '5.0', '8.0' ] +# +# - [ '6.0', '6.0' ] +# - [ '6.0', '7.0' ] +# - [ '6.0', '8.0' ] +# +# - [ '7.0', '7.0' ] +# - [ '7.0', '8.0' ] +# +# - [ '8.0', '8.0' ] toHashedIndexKey: [true, false] topology: - replset - - replset-to-sharded - - sharded +# - replset-to-sharded +# - sharded # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. From 1c088eee1f3a0be51308afdf6a8d71e61fc1f5e2 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 10:01:28 -0500 Subject: [PATCH 13/21] =?UTF-8?q?4.0=20can=E2=80=99t=20idleCursors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/testutil/testutil.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 6b57dbd3..16e5f720 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -95,6 +95,15 @@ func KillApplicationChangeStreams( client *mongo.Client, appName string, ) error { + currentOpArg := bson.D{} + + if false { + currentOpArg = append( + currentOpArg, + bson.E{"idleCursors", true}, + ) + } + // Kill verifier’s change stream. cursor, err := client.Database( "admin", @@ -103,9 +112,7 @@ func KillApplicationChangeStreams( ctx, mongo.Pipeline{ { - {"$currentOp", bson.D{ - {"idleCursors", true}, - }}, + {"$currentOp", currentOpArg}, }, { {"$match", bson.D{ From fd68b3d7f0dd633d5ea1f214683990805dee8cc2 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 10:09:56 -0500 Subject: [PATCH 14/21] resumeAfter --- internal/verifier/change_stream.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/verifier/change_stream.go b/internal/verifier/change_stream.go index 4a91a3c3..ab2f169d 100644 --- a/internal/verifier/change_stream.go +++ b/internal/verifier/change_stream.go @@ -374,7 +374,8 @@ func (csr *ChangeStreamReader) createChangeStream( logEvent.Msg("Starting change stream from persisted resume token.") - opts = opts.SetStartAfter(token) + //opts = opts.SetStartAfter(token) + opts = opts.SetResumeAfter(token) } else { csStartLogEvent.Msgf("Starting change stream from current %s cluster time.", csr.readerType) } From 25682d87631d4c2e14cb8662bed36316c009d988 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 10:25:24 -0500 Subject: [PATCH 15/21] replaceRoot --- internal/verifier/compare.go | 24 +++++++++++++----------- internal/verifier/dockey_agg_test.go | 2 +- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/internal/verifier/compare.go b/internal/verifier/compare.go index 85fbfca0..4b90db14 100644 --- a/internal/verifier/compare.go +++ b/internal/verifier/compare.go @@ -700,20 +700,22 @@ func transformPipelineForToHashedIndexKey( ) mongo.Pipeline { return append( slices.Clone(in), - bson.D{{"$replaceWith", bson.D{ - // Single-letter field names minimize the document size. - {docKeyInHashedCompare, dockey.ExtractTrueDocKeyAgg( - task.QueryFilter.GetDocKeyFields(), - "$$ROOT", - )}, - {"h", bson.D{ - {"$toHashedIndexKey", bson.D{ - {"$_internalKeyStringValue", bson.D{ - {"input", "$$ROOT"}, + bson.D{{"$replaceRoot", bson.D{ + {"newRoot", bson.D{ + // Single-letter field names minimize the document size. + {docKeyInHashedCompare, dockey.ExtractTrueDocKeyAgg( + task.QueryFilter.GetDocKeyFields(), + "$$ROOT", + )}, + {"h", bson.D{ + {"$toHashedIndexKey", bson.D{ + {"$_internalKeyStringValue", bson.D{ + {"input", "$$ROOT"}, + }}, }}, }}, + {"s", bson.D{{"$bsonSize", "$$ROOT"}}}, }}, - {"s", bson.D{{"$bsonSize", "$$ROOT"}}}, }}}, ) } diff --git a/internal/verifier/dockey_agg_test.go b/internal/verifier/dockey_agg_test.go index 94417b08..9141920e 100644 --- a/internal/verifier/dockey_agg_test.go +++ b/internal/verifier/dockey_agg_test.go @@ -66,7 +66,7 @@ func (suite *IntegrationTestSuite) testExtractTrueDocKeyAgg(reverseYN bool) { cursor, err := coll.Aggregate( ctx, mongo.Pipeline{ - {{"$replaceWith", computedDocKeyAgg}}, + {{"$replaceRoot", bson.D{{"newRoot", computedDocKeyAgg}}}}, }, ) require.NoError(err, "should open cursor to agg") From d9289cb658a87f18ac595f8ad0fad0e83cc6253a Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 10:54:30 -0500 Subject: [PATCH 16/21] 4.0 only --- .github/workflows/all.yml | 3 --- internal/testutil/testutil.go | 4 +++- internal/util/clusterinfo.go | 12 ++++++++++++ internal/verifier/change_stream.go | 9 ++++++--- internal/verifier/change_stream_test.go | 2 ++ internal/verifier/uri.go | 9 +-------- 6 files changed, 24 insertions(+), 15 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index e73ce518..449dccb0 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -19,9 +19,6 @@ jobs: fail-fast: false matrix: include: - - mongodb_versions: [ '3.6', '8.0' ] - topology: replset - - mongodb_versions: [ '4.0', '8.0' ] topology: replset diff --git a/internal/testutil/testutil.go b/internal/testutil/testutil.go index 16e5f720..e0a680df 100644 --- a/internal/testutil/testutil.go +++ b/internal/testutil/testutil.go @@ -7,6 +7,7 @@ import ( "log" "testing" + "github.com/10gen/migration-verifier/internal/util" "github.com/pkg/errors" "github.com/samber/lo" "go.mongodb.org/mongo-driver/v2/bson" @@ -93,11 +94,12 @@ func KillApplicationChangeStreams( ctx context.Context, t *testing.T, client *mongo.Client, + versionArray []int, appName string, ) error { currentOpArg := bson.D{} - if false { + if util.ClusterHasCurrentOpIdleCursors([2]int(versionArray)) { currentOpArg = append( currentOpArg, bson.E{"idleCursors", true}, diff --git a/internal/util/clusterinfo.go b/internal/util/clusterinfo.go index b2354e96..f08608ac 100644 --- a/internal/util/clusterinfo.go +++ b/internal/util/clusterinfo.go @@ -31,6 +31,18 @@ func ClusterHasBSONSize(va [2]int) bool { return major > 4 } +func ClusterHasCurrentOpIdleCursors(va [2]int) bool { + major := va[0] + + if major == 4 { + return va[1] >= 2 + } + + return major > 4 +} + +var ClusterHasChangeStreamStartAfter = ClusterHasCurrentOpIdleCursors + const ( TopologySharded ClusterTopology = "sharded" TopologyReplset ClusterTopology = "replset" diff --git a/internal/verifier/change_stream.go b/internal/verifier/change_stream.go index ab2f169d..76529256 100644 --- a/internal/verifier/change_stream.go +++ b/internal/verifier/change_stream.go @@ -374,8 +374,11 @@ func (csr *ChangeStreamReader) createChangeStream( logEvent.Msg("Starting change stream from persisted resume token.") - //opts = opts.SetStartAfter(token) - opts = opts.SetResumeAfter(token) + if util.ClusterHasChangeStreamStartAfter([2]int(csr.clusterInfo.VersionArray)) { + opts = opts.SetStartAfter(token) + } else { + opts = opts.SetResumeAfter(token) + } } else { csStartLogEvent.Msgf("Starting change stream from current %s cluster time.", csr.readerType) } @@ -387,7 +390,7 @@ func (csr *ChangeStreamReader) createChangeStream( sctx := mongo.NewSessionContext(ctx, sess) changeStream, err := csr.watcherClient.Watch(sctx, pipeline, opts) if err != nil { - return nil, nil, bson.Timestamp{}, errors.Wrap(err, "failed to open change stream") + return nil, nil, bson.Timestamp{}, errors.Wrap(err, "opening change stream") } err = csr.persistResumeToken(ctx, changeStream.ResumeToken()) diff --git a/internal/verifier/change_stream_test.go b/internal/verifier/change_stream_test.go index 5f746f14..5f8e8395 100644 --- a/internal/verifier/change_stream_test.go +++ b/internal/verifier/change_stream_test.go @@ -803,6 +803,7 @@ func (suite *IntegrationTestSuite) TestWritesOffCursorKilledResilience() { suite.Context(), suite.T(), suite.srcMongoClient, + verifier.srcClusterInfo.VersionArray, clientAppName, ), ) @@ -831,6 +832,7 @@ func (suite *IntegrationTestSuite) TestCursorKilledResilience() { suite.Context(), suite.T(), suite.srcMongoClient, + verifier.srcClusterInfo.VersionArray, clientAppName, ), ) diff --git a/internal/verifier/uri.go b/internal/verifier/uri.go index 2c99948b..f1c9ebe0 100644 --- a/internal/verifier/uri.go +++ b/internal/verifier/uri.go @@ -79,14 +79,7 @@ func (verifier *Verifier) maybeSuggestHashedComparisonOptimization() { } func isVersionSupported(version []int) bool { - if version[0] >= 4 { - return true - } - if version[0] < 3 { - return false - } - - return version[1] >= 6 + return version[0] >= 4 } func (verifier *Verifier) SetDstURI(ctx context.Context, uri string) error { From 71aed941e0f4e914fd7959993e6b0ef44d63f2d2 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 10:56:17 -0500 Subject: [PATCH 17/21] full test suite --- .github/workflows/all.yml | 51 ++++++++++++++++++++------------------- 1 file changed, 26 insertions(+), 25 deletions(-) diff --git a/.github/workflows/all.yml b/.github/workflows/all.yml index 449dccb0..d5bd8701 100644 --- a/.github/workflows/all.yml +++ b/.github/workflows/all.yml @@ -19,6 +19,7 @@ jobs: fail-fast: false matrix: include: + # NB: This is the only setup we’re supporting with 4.0. - mongodb_versions: [ '4.0', '8.0' ] topology: replset @@ -42,36 +43,36 @@ jobs: # versions are: source, destination mongodb_versions: - [ '4.2', '4.2' ] -# - [ '4.2', '4.4' ] -# - [ '4.2', '5.0' ] -# - [ '4.2', '6.0' ] -# - [ '4.2', '8.0' ] -# -# - [ '4.4', '4.4' ] -# - [ '4.4', '5.0' ] -# - [ '4.4', '6.0' ] -# - [ '4.4', '8.0' ] -# -# - [ '5.0', '5.0' ] -# - [ '5.0', '6.0' ] -# - [ '5.0', '7.0' ] -# - [ '5.0', '8.0' ] -# -# - [ '6.0', '6.0' ] -# - [ '6.0', '7.0' ] -# - [ '6.0', '8.0' ] -# -# - [ '7.0', '7.0' ] -# - [ '7.0', '8.0' ] -# -# - [ '8.0', '8.0' ] + - [ '4.2', '4.4' ] + - [ '4.2', '5.0' ] + - [ '4.2', '6.0' ] + - [ '4.2', '8.0' ] + + - [ '4.4', '4.4' ] + - [ '4.4', '5.0' ] + - [ '4.4', '6.0' ] + - [ '4.4', '8.0' ] + + - [ '5.0', '5.0' ] + - [ '5.0', '6.0' ] + - [ '5.0', '7.0' ] + - [ '5.0', '8.0' ] + + - [ '6.0', '6.0' ] + - [ '6.0', '7.0' ] + - [ '6.0', '8.0' ] + + - [ '7.0', '7.0' ] + - [ '7.0', '8.0' ] + + - [ '8.0', '8.0' ] toHashedIndexKey: [true, false] topology: - replset -# - replset-to-sharded -# - sharded + - replset-to-sharded + - sharded # Ubuntu 24 lacks OpenSSL 1.1.1’s libcrypto, which pre-v6 MongoDB # versions need. From 2a681ba34fcd20ba44333a462092dc757d4ba144 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 11:38:12 -0500 Subject: [PATCH 18/21] mod tidy --- go.mod | 6 +- go.sum | 4 - .../mongo-driver/v2/bson/bsoncodec.go | 6 +- .../mongo-driver/v2/bson/buffered_byte_src.go | 128 +++++ .../mongo-driver/v2/bson/codec_cache.go | 4 +- .../mongo-driver/v2/bson/copier.go | 8 +- .../mongo-driver/v2/bson/decimal.go | 4 +- .../mongo-driver/v2/bson/decoder.go | 6 +- .../v2/bson/default_value_decoders.go | 31 +- .../v2/bson/default_value_encoders.go | 4 +- .../mongo-driver/v2/bson/doc.go | 78 ++- .../v2/bson/empty_interface_codec.go | 6 +- .../mongo-driver/v2/bson/encoder.go | 13 +- .../mongo-driver/v2/bson/extjson_parser.go | 2 +- .../mongo-driver/v2/bson/extjson_writer.go | 7 +- .../mongo-driver/v2/bson/json_scanner.go | 2 +- .../mongo-driver/v2/bson/marshal.go | 17 +- .../mongo-driver/v2/bson/mgoregistry.go | 4 +- .../mongo-driver/v2/bson/primitive.go | 14 +- .../mongo-driver/v2/bson/raw_value.go | 10 +- .../mongo-driver/v2/bson/registry.go | 4 +- .../v2/bson/streaming_byte_src.go | 104 ++++ .../mongo-driver/v2/bson/struct_codec.go | 4 + .../mongo-driver/v2/bson/types.go | 2 +- .../mongo-driver/v2/bson/unmarshal.go | 14 +- .../mongo-driver/v2/bson/value_reader.go | 524 +++++++++++------- .../mongo-driver/v2/bson/value_writer.go | 25 +- .../v2/internal/bsoncoreutil/bsoncoreutil.go | 2 +- .../v2/internal/bsonutil/bsonutil.go | 6 +- .../v2/internal/codecutil/encoding.go | 8 +- .../v2/internal/driverutil/description.go | 2 +- .../v2/internal/driverutil/operation.go | 37 ++ .../v2/internal/httputil/httputil.go | 14 +- .../v2/internal/logger/component.go | 16 +- .../v2/internal/logger/io_sink.go | 6 +- .../mongo-driver/v2/internal/logger/logger.go | 13 +- .../v2/internal/mongoutil/mongoutil.go | 16 + .../v2/internal/optionsutil/options.go | 45 ++ .../v2/mongo/background_context.go | 2 +- .../mongo-driver/v2/mongo/batch_cursor.go | 7 +- .../mongo-driver/v2/mongo/bulk_write.go | 35 +- .../v2/mongo/bulk_write_models.go | 137 ++--- .../mongo-driver/v2/mongo/change_stream.go | 83 ++- .../mongo-driver/v2/mongo/client.go | 35 +- .../v2/mongo/client_bulk_write.go | 51 +- .../v2/mongo/client_bulk_write_models.go | 72 +-- .../v2/mongo/client_encryption.go | 9 +- .../mongo-driver/v2/mongo/collection.go | 195 +++++-- .../mongo-driver/v2/mongo/cursor.go | 116 +++- .../mongo-driver/v2/mongo/database.go | 100 ++-- .../mongo-driver/v2/mongo/doc.go | 4 +- .../mongo-driver/v2/mongo/errors.go | 174 +++++- .../mongo-driver/v2/mongo/gridfs_bucket.go | 20 +- .../v2/mongo/gridfs_download_stream.go | 33 +- .../v2/mongo/gridfs_upload_stream.go | 6 +- .../mongo-driver/v2/mongo/index_view.go | 60 +- .../mongo-driver/v2/mongo/mongo.go | 31 +- .../mongo-driver/v2/mongo/mongocryptd.go | 2 +- .../v2/mongo/options/aggregateoptions.go | 28 +- .../v2/mongo/options/autoencryptionoptions.go | 26 +- .../v2/mongo/options/bulkwriteoptions.go | 17 +- .../v2/mongo/options/changestreamoptions.go | 19 +- .../mongo/options/clientbulkwriteoptions.go | 13 +- .../mongo/options/clientencryptionoptions.go | 20 +- .../v2/mongo/options/clientoptions.go | 66 ++- .../v2/mongo/options/countoptions.go | 21 +- .../mongo/options/createcollectionoptions.go | 47 +- .../v2/mongo/options/datakeyoptions.go | 4 +- .../v2/mongo/options/deleteoptions.go | 80 +-- .../v2/mongo/options/distinctoptions.go | 22 +- .../v2/mongo/options/dropcollectionoptions.go | 4 +- .../v2/mongo/options/estimatedcountoptions.go | 10 +- .../v2/mongo/options/findoptions.go | 207 +++---- .../v2/mongo/options/gridfsoptions.go | 8 +- .../v2/mongo/options/indexoptions.go | 43 +- .../v2/mongo/options/insertoptions.go | 24 +- .../mongo/options/listcollectionsoptions.go | 6 + .../v2/mongo/options/loggeroptions.go | 4 +- .../v2/mongo/options/replaceoptions.go | 46 +- .../v2/mongo/options/rewrapdatakeyoptions.go | 4 +- .../v2/mongo/options/updateoptions.go | 108 ++-- .../mongo-driver/v2/mongo/readpref/options.go | 13 +- .../v2/mongo/readpref/readpref.go | 8 +- .../mongo-driver/v2/mongo/results.go | 27 +- .../v2/mongo/search_index_view.go | 8 +- .../mongo-driver/v2/mongo/session.go | 11 +- .../mongo-driver/v2/mongo/single_result.go | 6 +- .../v2/mongo/writeconcern/writeconcern.go | 2 +- .../mongo-driver/v2/version/version.go | 2 +- .../mongo-driver/v2/x/bsonx/bsoncore/array.go | 87 +-- .../v2/x/bsonx/bsoncore/document.go | 90 +-- .../v2/x/bsonx/bsoncore/element.go | 75 ++- .../mongo-driver/v2/x/bsonx/bsoncore/value.go | 103 ++-- .../v2/x/mongo/driver/auth/auth.go | 8 +- .../v2/x/mongo/driver/auth/default.go | 43 +- .../v2/x/mongo/driver/auth/mongodbcr.go | 120 ---- .../v2/x/mongo/driver/auth/oidc.go | 83 ++- .../v2/x/mongo/driver/batch_cursor.go | 40 +- .../v2/x/mongo/driver/compression.go | 4 +- .../x/mongo/driver/connstring/connstring.go | 12 - .../x/mongo/driver/mongocrypt/mongocrypt.go | 12 + .../mongocrypt/options/mongocrypt_options.go | 9 + .../v2/x/mongo/driver/operation.go | 63 ++- .../v2/x/mongo/driver/operation/aggregate.go | 17 +- .../v2/x/mongo/driver/operation/count.go | 17 +- .../v2/x/mongo/driver/operation/create.go | 2 +- .../mongo/driver/operation/create_indexes.go | 15 + .../v2/x/mongo/driver/operation/delete.go | 18 +- .../v2/x/mongo/driver/operation/distinct.go | 15 + .../x/mongo/driver/operation/drop_indexes.go | 17 +- .../v2/x/mongo/driver/operation/find.go | 15 + .../mongo/driver/operation/find_and_modify.go | 17 +- .../v2/x/mongo/driver/operation/insert.go | 15 + .../driver/operation/list_collections.go | 18 +- .../x/mongo/driver/operation/list_indexes.go | 18 +- .../v2/x/mongo/driver/operation/update.go | 26 +- .../v2/x/mongo/driver/topology/connection.go | 55 +- .../v2/x/mongo/driver/topology/errors.go | 33 +- .../v2/x/mongo/driver/topology/fsm.go | 2 +- .../v2/x/mongo/driver/topology/pool.go | 22 +- .../v2/x/mongo/driver/topology/server.go | 2 +- .../v2/x/mongo/driver/topology/topology.go | 10 +- .../mongo/driver/topology/topology_options.go | 10 + .../x/mongo/driver/wiremessage/wiremessage.go | 2 +- vendor/modules.txt | 5 +- 125 files changed, 2802 insertions(+), 1570 deletions(-) create mode 100644 vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go create mode 100644 vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go create mode 100644 vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go delete mode 100644 vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go diff --git a/go.mod b/go.mod index 1f15ff50..618f88cc 100644 --- a/go.mod +++ b/go.mod @@ -8,8 +8,10 @@ require ( github.com/dustin/go-humanize v1.0.1 github.com/gin-contrib/pprof v1.5.3 github.com/gin-gonic/gin v1.10.0 + github.com/goaux/timer v1.1.0 github.com/google/uuid v1.3.0 github.com/huandu/go-clone/generic v1.7.2 + github.com/libp2p/go-buffer-pool v0.1.0 github.com/olekukonko/tablewriter v0.0.5 github.com/pkg/errors v0.9.1 github.com/quasilyte/go-ruleguard/dsl v0.3.22 @@ -18,7 +20,7 @@ require ( github.com/samber/mo v1.13.0 github.com/stretchr/testify v1.10.0 github.com/urfave/cli v1.22.9 - go.mongodb.org/mongo-driver/v2 v2.1.0 + go.mongodb.org/mongo-driver/v2 v2.3.1 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 golang.org/x/sync v0.13.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 @@ -36,7 +38,6 @@ require ( github.com/go-playground/locales v0.14.1 // indirect github.com/go-playground/universal-translator v0.18.1 // indirect github.com/go-playground/validator/v10 v10.26.0 // indirect - github.com/goaux/timer v1.1.0 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/golang/snappy v1.0.0 // indirect github.com/huandu/go-clone v1.6.0 // indirect @@ -44,7 +45,6 @@ require ( github.com/klauspost/compress v1.16.7 // indirect github.com/klauspost/cpuid/v2 v2.2.10 // indirect github.com/leodido/go-urn v1.4.0 // indirect - github.com/libp2p/go-buffer-pool v0.1.0 // indirect github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.9 // indirect diff --git a/go.sum b/go.sum index 32d9b3f4..e4cfaa08 100644 --- a/go.sum +++ b/go.sum @@ -129,12 +129,8 @@ github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gi github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= -go.mongodb.org/mongo-driver/v2 v2.1.0 h1:/ELnVNjmfUKDsoBisXxuJL0noR9CfeUIrP7Yt3R+egg= -go.mongodb.org/mongo-driver/v2 v2.1.0/go.mod h1:AWiLRShSrk5RHQS3AEn3RL19rqOzVq49MCpWQ3x/huI= go.mongodb.org/mongo-driver/v2 v2.3.1 h1:WrCgSzO7dh1/FrePud9dK5fKNZOE97q5EQimGkos7Wo= go.mongodb.org/mongo-driver/v2 v2.3.1/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI= -go.mongodb.org/mongo-driver/v2 v2.4.0 h1:Oq6BmUAAFTzMeh6AonuDlgZMuAuEiUxoAD1koK5MuFo= -go.mongodb.org/mongo-driver/v2 v2.4.0/go.mod h1:jHeEDJHJq7tm6ZF45Issun9dbogjfnPySb1vXA7EeAI= golang.org/x/arch v0.16.0 h1:foMtLTdyOmIniqWCHjY6+JxuC54XP1fDwx4N0ASyW+U= golang.org/x/arch v0.16.0/go.mod h1:JmwW7aLIoRUKgaTzhkiEFxvcEiQGyOg9BMonBJUS7EE= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go index bacc99fb..78b861a3 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/bsoncodec.go @@ -69,6 +69,9 @@ func (vde ValueDecoderError) Error() string { if vde.Received.IsValid() { received = vde.Received.Type().String() } + if !vde.Received.CanSet() { + received = "unsettable " + received + } return fmt.Sprintf("%s can only decode valid and settable %s, but got %s", vde.Name, strings.Join(typeKinds, ", "), received) } @@ -88,6 +91,7 @@ type EncodeContext struct { nilSliceAsEmpty bool nilByteSliceAsEmpty bool omitZeroStruct bool + omitEmpty bool useJSONStructTags bool } @@ -103,7 +107,7 @@ type DecodeContext struct { truncate bool // defaultDocumentType specifies the Go type to decode top-level and nested BSON documents into. In particular, the - // usage for this field is restricted to data typed as "interface{}" or "map[string]interface{}". If DocumentType is + // usage for this field is restricted to data typed as "any" or "map[string]any". If DocumentType is // set to a type that a BSON document cannot be unmarshaled into (e.g. "string"), unmarshalling will result in an // error. defaultDocumentType reflect.Type diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go new file mode 100644 index 00000000..eb19e3cb --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/buffered_byte_src.go @@ -0,0 +1,128 @@ +// Copyright (C) MongoDB, Inc. 2025-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 ( + "bytes" + "io" +) + +// bufferedByteSrc implements the low-level byteSrc interface by reading +// directly from an in-memory byte slice. It provides efficient, zero-copy +// access for parsing BSON when the entire document is buffered in memory. +type bufferedByteSrc struct { + buf []byte // entire BSON document + offset int64 // Current read index into buf +} + +var _ byteSrc = (*bufferedByteSrc)(nil) + +// Read reads up to len(p) bytes from the in-memory buffer, advancing the offset +// by the number of bytes read. +func (b *bufferedByteSrc) readExact(p []byte) (int, error) { + if b.offset >= int64(len(b.buf)) { + return 0, io.EOF + } + n := copy(p, b.buf[b.offset:]) + b.offset += int64(n) + return n, nil +} + +// ReadByte returns the single byte at buf[offset] and advances offset by 1. +func (b *bufferedByteSrc) ReadByte() (byte, error) { + if b.offset >= int64(len(b.buf)) { + return 0, io.EOF + } + b.offset++ + return b.buf[b.offset-1], nil +} + +// peek returns buf[offset:offset+n] without advancing offset. +func (b *bufferedByteSrc) peek(n int) ([]byte, error) { + // Ensure we don't read past the end of the buffer. + if int64(n)+b.offset > int64(len(b.buf)) { + return b.buf[b.offset:], io.EOF + } + + // Return the next n bytes without advancing the offset + return b.buf[b.offset : b.offset+int64(n)], nil +} + +// discard advances offset by n bytes, returning the number of bytes discarded. +func (b *bufferedByteSrc) discard(n int) (int, error) { + // Ensure we don't read past the end of the buffer. + if int64(n)+b.offset > int64(len(b.buf)) { + // If we have exceeded the buffer length, discard only up to the end. + left := len(b.buf) - int(b.offset) + b.offset = int64(len(b.buf)) + + return left, io.EOF + } + + // Advance the read position + b.offset += int64(n) + return n, nil +} + +// readSlice scans buf[offset:] for the first occurrence of delim, returns +// buf[offset:idx+1], and advances offset past it; errors if delim not found. +func (b *bufferedByteSrc) readSlice(delim byte) ([]byte, error) { + // Ensure we don't read past the end of the buffer. + if b.offset >= int64(len(b.buf)) { + return nil, io.EOF + } + + // Look for the delimiter in the remaining bytes + rem := b.buf[b.offset:] + idx := bytes.IndexByte(rem, delim) + if idx < 0 { + return nil, io.EOF + } + + // Build the result slice up through the delimiter. + result := rem[:idx+1] + + // Advance the offset past the delimiter. + b.offset += int64(idx + 1) + + return result, nil +} + +// pos returns the current read position in the buffer. +func (b *bufferedByteSrc) pos() int64 { + return b.offset +} + +// regexLength will return the total byte length of a BSON regex value. +func (b *bufferedByteSrc) regexLength() (int32, error) { + rem := b.buf[b.offset:] + + // Find end of the first C-string (pattern). + i := bytes.IndexByte(rem, 0x00) + if i < 0 { + return 0, io.EOF + } + + // Find end of second C-string (options). + j := bytes.IndexByte(rem[i+1:], 0x00) + if j < 0 { + return 0, io.EOF + } + + // Total length = first C-string length (pattern) + second C-string length + // (options) + 2 null terminators + return int32(i + j + 2), nil +} + +func (*bufferedByteSrc) streamable() bool { + return false +} + +func (b *bufferedByteSrc) reset() { + b.buf = nil + b.offset = 0 +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go index b4042822..de97441e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/codec_cache.go @@ -49,7 +49,7 @@ func (c *typeEncoderCache) LoadOrStore(rt reflect.Type, enc ValueEncoder) ValueE func (c *typeEncoderCache) Clone() *typeEncoderCache { cc := new(typeEncoderCache) - c.cache.Range(func(k, v interface{}) bool { + c.cache.Range(func(k, v any) bool { if k != nil && v != nil { cc.cache.Store(k, v) } @@ -82,7 +82,7 @@ func (c *typeDecoderCache) LoadOrStore(rt reflect.Type, dec ValueDecoder) ValueD func (c *typeDecoderCache) Clone() *typeDecoderCache { cc := new(typeDecoderCache) - c.cache.Range(func(k, v interface{}) bool { + c.cache.Range(func(k, v any) bool { if k != nil && v != nil { cc.cache.Store(k, v) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go index 6279f072..c9a37c75 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/copier.go @@ -7,7 +7,6 @@ package bson import ( - "bytes" "errors" "fmt" "io" @@ -180,8 +179,11 @@ func copyValueFromBytes(dst ValueWriter, t Type, src []byte) error { return wvb.writeValueBytes(t, src) } - vr := newDocumentReader(bytes.NewReader(src)) - vr.pushElement(t) + vr := newBufferedDocumentReader(src) + vr.advanceFrame() + + vr.stack[vr.frame].mode = mElement + vr.stack[vr.frame].vType = t return copyValue(dst, vr) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go index 85c506ef..6241733a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/decimal.go @@ -145,7 +145,7 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { return nil } - var res interface{} + var res any err := json.Unmarshal(b, &res) if err != nil { return err @@ -154,7 +154,7 @@ func (d *Decimal128) UnmarshalJSON(b []byte) error { // Extended JSON if !ok { - m, ok := res.(map[string]interface{}) + m, ok := res.(map[string]any) if !ok { return errors.New("not an extended JSON Decimal128: expected document") } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go index 2fa9e6f1..4c24dc66 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/decoder.go @@ -20,7 +20,7 @@ var ErrDecodeToNil = errors.New("cannot Decode to nil value") // methods and is not consumable from outside of this package. The Decoders retrieved from this pool // must have both Reset and SetRegistry called on them. var decPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(Decoder) }, } @@ -44,7 +44,7 @@ func NewDecoder(vr ValueReader) *Decoder { // value pointed to by val. // // See [Unmarshal] for details about BSON unmarshaling behavior. -func (d *Decoder) Decode(val interface{}) error { +func (d *Decoder) Decode(val any) error { if unmarshaler, ok := val.(Unmarshaler); ok { // TODO(skriptble): Reuse a []byte here and use the AppendDocumentBytes method. buf, err := copyDocumentToBytes(d.vr) @@ -88,7 +88,7 @@ func (d *Decoder) SetRegistry(r *Registry) { } // DefaultDocumentM causes the Decoder to always unmarshal documents into the bson.M type. This -// behavior is restricted to data typed as "interface{}" or "map[string]interface{}". +// behavior is restricted to data typed as "any" or "map[string]any". func (d *Decoder) DefaultDocumentM() { d.dc.defaultDocumentType = reflect.TypeOf(M{}) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go index 42ea2e58..8ce5954d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_decoders.go @@ -32,8 +32,8 @@ func (d decodeBinaryError) Error() string { // registerDefaultDecoders will register the decoder methods attached to DefaultValueDecoders with // the provided RegistryBuilder. // -// There is no support for decoding map[string]interface{} because there is no decoder for -// interface{}, so users must either register this decoder themselves or use the +// There is no support for decoding map[string]any because there is no decoder for +// any, so users must either register this decoder themselves or use the // EmptyInterfaceDecoder available in the bson package. func registerDefaultDecoders(reg *Registry) { intDecoder := decodeAdapter{intDecodeValue, intDecodeType} @@ -150,7 +150,7 @@ func dDecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { return err } - var v interface{} + var v any err = decoder.DecodeValue(dc, elemVr, reflect.ValueOf(&v).Elem()) if err != nil { return err @@ -1332,8 +1332,12 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle eType := val.Type().Elem() + isInterfaceSlice := eType.Kind() == reflect.Interface && val.Len() > 0 + + // If this is not an interface slice with pre-populated elements, we can look up + // the decoder for eType once. var vDecoder ValueDecoder - if !(eType.Kind() == reflect.Interface && val.Len() > 0) { + if !isInterfaceSlice { vDecoder, err = dc.LookupDecoder(eType) if err != nil { return nil, err @@ -1351,7 +1355,9 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle } var elem reflect.Value - if vDecoder == nil { + if isInterfaceSlice && idx < val.Len() { + // Decode into an existing any slot. + elem = val.Index(idx).Elem() switch { case elem.Kind() != reflect.Ptr || elem.IsNil(): @@ -1359,6 +1365,12 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle if err != nil { return nil, err } + + // If an element is allocated and unsettable, it must be overwritten. + if !elem.CanSet() { + elem = reflect.New(elem.Type()).Elem() + } + err = valueDecoder.DecodeValue(dc, vr, elem) if err != nil { return nil, newDecodeError(strconv.Itoa(idx), err) @@ -1380,6 +1392,15 @@ func decodeDefault(dc DecodeContext, vr ValueReader, val reflect.Value) ([]refle } } } else { + // For non-interface slices, or if we've exhausted the pre-populated + // slots, we create a fresh value. + + if vDecoder == nil { + vDecoder, err = dc.LookupDecoder(eType) + if err != nil { + return nil, err + } + } elem, err = decodeTypeOrValueWithInfo(vDecoder, dc, vr, eType) if err != nil { return nil, newDecodeError(strconv.Itoa(idx), err) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go index bd5a20f2..67d464cb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/default_value_encoders.go @@ -18,7 +18,7 @@ import ( ) var bvwPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(valueWriter) }, } @@ -26,7 +26,7 @@ var bvwPool = sync.Pool{ var errInvalidValue = errors.New("cannot encode invalid element") var sliceWriterPool = sync.Pool{ - New: func() interface{} { + New: func() any { sw := make(sliceWriter, 0) return &sw }, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go index 81aceef2..b346f71f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/doc.go @@ -4,30 +4,14 @@ // not use this 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 is a library for reading, writing, and manipulating BSON. BSON is a binary serialization format used to -// store documents and make remote procedure calls in MongoDB. The BSON specification is located at https://bsonspec.org. -// The BSON library handles marshaling and unmarshaling of values through a configurable codec system. For a description -// of the codec system and examples of registering custom codecs, see the bsoncodec package. For additional information -// and usage examples, check out the [Work with BSON] page in the Go Driver docs site. -// -// # Raw BSON -// -// The Raw family of types is used to validate and retrieve elements from a slice of bytes. This -// type is most useful when you want do lookups on BSON bytes without unmarshaling it into another -// type. -// -// Example: -// -// var raw bson.Raw = ... // bytes from somewhere -// err := raw.Validate() -// if err != nil { return err } -// val := raw.Lookup("foo") -// i32, ok := val.Int32OK() -// // do something with i32... +// Package bson is a library for reading, writing, and manipulating BSON. BSON is a binary serialization +// format used to store documents and make remote procedure calls in MongoDB. For more information about +// the Go BSON library, including usage examples, check out the [Work with BSON] page in the Go Driver +// docs site. For more information about BSON, see https://bsonspec.org. // // # Native Go Types // -// The D and M types defined in this package can be used to build representations of BSON using native Go types. D is a +// The [D] and [M] types defined in this package can be used to build representations of BSON using native Go types. D is a // slice and M is a map. For more information about the use cases for these types, see the documentation on the type // definitions. // @@ -90,29 +74,19 @@ // 4. A pointer field is marshaled as the underlying type if the pointer is non-nil. If the pointer is nil, it is // marshaled as a BSON null value. // -// 5. When unmarshaling, a field of type interface{} will follow the D/M type mappings listed above. BSON documents -// unmarshaled into an interface{} field will be unmarshaled as a D. -// -// The encoding of each struct field can be customized by the "bson" struct tag. -// -// This tag behavior is configurable, and different struct tag behavior can be configured by initializing a new -// bsoncodec.StructCodec with the desired tag parser and registering that StructCodec onto the Registry. By default, JSON -// tags are not honored, but that can be enabled by creating a StructCodec with JSONFallbackStructTagParser, like below: +// 5. When unmarshaling, a field of type any will follow the D/M type mappings listed above. BSON documents +// unmarshaled into an any field will be unmarshaled as a D. // -// Example: -// -// structcodec, _ := bsoncodec.NewStructCodec(bsoncodec.JSONFallbackStructTagParser) -// -// The bson tag gives the name of the field, possibly followed by a comma-separated list of options. -// The name may be empty in order to specify options without overriding the default field name. The following options can -// be used to configure behavior: +// The encoding of each struct field can be customized by the "bson" struct tag. The "bson" tag gives the name of the +// field, followed by a comma-separated list of options. The name may be omitted in order to specify options without +// overriding the default field name. The following options can be used to configure behavior: // // 1. omitempty: If the "omitempty" struct tag is specified on a field, the field will not be marshaled if it is set to // an "empty" value. Numbers, booleans, and strings are considered empty if their value is equal to the zero value for // the type (i.e. 0 for numbers, false for booleans, and "" for strings). Slices, maps, and arrays are considered // empty if they are of length zero. Interfaces and pointers are considered empty if their value is nil. By default, -// structs are only considered empty if the struct type implements [bsoncodec.Zeroer] and the IsZero -// method returns true. Struct types that do not implement [bsoncodec.Zeroer] are never considered empty and will be +// structs are only considered empty if the struct type implements [Zeroer] and the "IsZero" +// method returns true. Struct types that do not implement [Zeroer] are never considered empty and will be // marshaled as embedded documents. NOTE: It is recommended that this tag be used for all slice and map fields. // // 2. minsize: If the minsize struct tag is specified on a field of type int64, uint, uint32, or uint64 and the value of @@ -127,23 +101,33 @@ // 4. inline: If the inline struct tag is specified for a struct or map field, the field will be "flattened" when // marshaling and "un-flattened" when unmarshaling. This means that all of the fields in that struct/map will be // pulled up one level and will become top-level fields rather than being fields in a nested document. For example, -// if a map field named "Map" with value map[string]interface{}{"foo": "bar"} is inlined, the resulting document will +// if a map field named "Map" with value map[string]any{"foo": "bar"} is inlined, the resulting document will // be {"foo": "bar"} instead of {"map": {"foo": "bar"}}. There can only be one inlined map field in a struct. If // there are duplicated fields in the resulting document when an inlined struct is marshaled, the inlined field will // be overwritten. If there are duplicated fields in the resulting document when an inlined map is marshaled, an // error will be returned. This tag can be used with fields that are pointers to structs. If an inlined pointer field // is nil, it will not be marshaled. For fields that are not maps or structs, this tag is ignored. // -// # Marshaling and Unmarshaling +// # Raw BSON // -// Manually marshaling and unmarshaling can be done with the Marshal and Unmarshal family of functions. +// The Raw family of types is used to validate and retrieve elements from a slice of bytes. This +// type is most useful when you want do lookups on BSON bytes without unmarshaling it into another +// type. // -// bsoncodec code 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. +// Example: // -// The codec system is composed of two parts: +// var raw bson.Raw = ... // bytes from somewhere +// err := raw.Validate() +// if err != nil { return err } +// val := raw.Lookup("foo") +// i32, ok := val.Int32OK() +// // do something with i32... +// +// # Custom Registry +// +// The Go BSON library uses a [Registry] to define encoding and decoding behavior for different data types. +// The default encoding and decoding behavior can be customized or extended by using a modified Registry. +// The custom registry system is composed of two parts: // // 1) [ValueEncoder] and [ValueDecoder] that handle encoding and decoding Go values to and from BSON // representations. @@ -151,5 +135,7 @@ // 2) A [Registry] that holds these ValueEncoders and ValueDecoders and provides methods for // retrieving them. // +// To use a custom Registry, use [Encoder.SetRegistry] or [Decoder.SetRegistry]. +// // [Work with BSON]: https://www.mongodb.com/docs/drivers/go/current/fundamentals/bson/ package bson diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go index 80d44d8c..ae1db53f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/empty_interface_codec.go @@ -10,7 +10,7 @@ import ( "reflect" ) -// emptyInterfaceCodec is the Codec used for interface{} values. +// emptyInterfaceCodec is the Codec used for any values. type emptyInterfaceCodec struct { // decodeBinaryAsSlice causes DecodeValue to unmarshal BSON binary field values that are the // "Generic" or "Old" BSON binary subtype as a Go byte slice instead of a Binary. @@ -22,7 +22,7 @@ type emptyInterfaceCodec struct { // collection. var _ typeDecoder = &emptyInterfaceCodec{} -// EncodeValue is the ValueEncoderFunc for interface{}. +// EncodeValue is the ValueEncoderFunc for any. func (eic *emptyInterfaceCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect.Value) error { if !val.IsValid() || val.Type() != tEmpty { return ValueEncoderError{Name: "EmptyInterfaceEncodeValue", Types: []reflect.Type{tEmpty}, Received: val} @@ -111,7 +111,7 @@ func (eic *emptyInterfaceCodec) decodeType(dc DecodeContext, vr ValueReader, t r return elem, nil } -// DecodeValue is the ValueDecoderFunc for interface{}. +// DecodeValue is the ValueDecoderFunc for any. func (eic *emptyInterfaceCodec) DecodeValue(dc DecodeContext, vr ValueReader, val reflect.Value) error { if !val.CanSet() || val.Type() != tEmpty { return ValueDecoderError{Name: "EmptyInterfaceDecodeValue", Types: []reflect.Type{tEmpty}, Received: val} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go index 0ad2432d..d27bb7b5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/encoder.go @@ -15,7 +15,7 @@ import ( // methods and is not consumable from outside of this package. The Encoders retrieved from this pool // must have both Reset and SetRegistry called on them. var encPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(Encoder) }, } @@ -38,7 +38,7 @@ func NewEncoder(vw ValueWriter) *Encoder { // Encode writes the BSON encoding of val to the stream. // // See [Marshal] for details about BSON marshaling behavior. -func (e *Encoder) Encode(val interface{}) error { +func (e *Encoder) Encode(val any) error { if marshaler, ok := val.(Marshaler); ok { // TODO(skriptble): Should we have a MarshalAppender interface so that we can have []byte reuse? buf, err := marshaler.MarshalBSON() @@ -108,7 +108,8 @@ func (e *Encoder) NilByteSliceAsEmpty() { // TODO struct fields once the logic is updated to also inspect private struct fields. // OmitZeroStruct causes the Encoder to consider the zero value for a struct (e.g. MyStruct{}) -// as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set. +// as empty and omit it from the marshaled BSON when the "omitempty" struct tag option is set +// or the OmitEmpty() method is called. // // Note that the Encoder only examines exported struct fields when determining if a struct is the // zero value. It considers pointers to a zero struct value (e.g. &MyStruct{}) not empty. @@ -116,6 +117,12 @@ func (e *Encoder) OmitZeroStruct() { e.ec.omitZeroStruct = true } +// OmitEmpty causes the Encoder to omit empty values from the marshaled BSON as the "omitempty" +// struct tag option is set. +func (e *Encoder) OmitEmpty() { + e.ec.omitEmpty = true +} + // UseJSONStructTags causes the Encoder to fall back to using the "json" struct tag if a "bson" // struct tag is not specified. func (e *Encoder) UseJSONStructTags() { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go index a63f23a2..eb536a67 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_parser.go @@ -46,7 +46,7 @@ const ( type extJSONValue struct { t Type - v interface{} + v any } type extJSONObject struct { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go index 5f231ba1..2d43943f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/extjson_writer.go @@ -407,12 +407,13 @@ func (ejvw *extJSONValueWriter) WriteRegex(pattern string, options string) error return err } + options = sortStringAlphebeticAscending(options) var buf bytes.Buffer buf.WriteString(`{"$regularExpression":{"pattern":`) writeStringWithEscapes(pattern, &buf, ejvw.escapeHTML) - buf.WriteString(`,"options":"`) - buf.WriteString(sortStringAlphebeticAscending(options)) - buf.WriteString(`"}},`) + buf.WriteString(`,"options":`) + writeStringWithEscapes(options, &buf, ejvw.escapeHTML) + buf.WriteString(`}},`) ejvw.buf = append(ejvw.buf, buf.Bytes()...) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go index b6eba79e..bc03915d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/json_scanner.go @@ -37,7 +37,7 @@ const ( type jsonToken struct { t jsonTokenType - v interface{} + v any p int } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go index 21631d81..71a28dab 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/marshal.go @@ -15,7 +15,7 @@ import ( const defaultDstCap = 256 var extjPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(extJSONValueWriter) }, } @@ -43,7 +43,7 @@ type ValueMarshaler interface { // Pool of buffers for marshalling BSON. var bufPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(bytes.Buffer) }, } @@ -54,7 +54,7 @@ var bufPool = sync.Pool{ // Marshal will use the default registry created by NewRegistry to recursively // marshal val into a []byte. Marshal will inspect struct tags and alter the // marshaling process accordingly. -func Marshal(val interface{}) ([]byte, error) { +func Marshal(val any) ([]byte, error) { sw := bufPool.Get().(*bytes.Buffer) defer func() { // Proper usage of a sync.Pool requires each entry to have approximately @@ -74,7 +74,10 @@ func Marshal(val interface{}) ([]byte, error) { } }() sw.Reset() - vw := NewDocumentWriter(sw) + + vw := getDocumentWriter(sw) + defer putDocumentWriter(vw) + enc := encPool.Get().(*Encoder) defer encPool.Put(enc) enc.Reset(vw) @@ -91,7 +94,7 @@ func Marshal(val interface{}) ([]byte, error) { // // MarshalValue will use bson.NewRegistry() to transform val into a BSON value. If val is a struct, this function will // inspect struct tags and alter the marshalling process accordingly. -func MarshalValue(val interface{}) (Type, []byte, error) { +func MarshalValue(val any) (Type, []byte, error) { sw := bufPool.Get().(*bytes.Buffer) defer func() { // Proper usage of a sync.Pool requires each entry to have approximately @@ -140,7 +143,7 @@ func MarshalValue(val interface{}) (Type, []byte, error) { } // MarshalExtJSON returns the extended JSON encoding of val. -func MarshalExtJSON(val interface{}, canonical, escapeHTML bool) ([]byte, error) { +func MarshalExtJSON(val any, canonical, escapeHTML bool) ([]byte, error) { sw := sliceWriter(make([]byte, 0, defaultDstCap)) ejvw := extjPool.Get().(*extJSONValueWriter) ejvw.reset(sw, canonical, escapeHTML) @@ -172,7 +175,7 @@ func IndentExtJSON(dst *bytes.Buffer, src []byte, prefix, indent string) error { // MarshalExtJSONIndent returns the extended JSON encoding of val with each line with prefixed // and indented. -func MarshalExtJSONIndent(val interface{}, canonical, escapeHTML bool, prefix, indent string) ([]byte, error) { +func MarshalExtJSONIndent(val any, canonical, escapeHTML bool, prefix, indent string) ([]byte, error) { marshaled, err := MarshalExtJSON(val, canonical, escapeHTML) if err != nil { return nil, err diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go index f42935e5..6aa74f29 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/mgoregistry.go @@ -17,7 +17,7 @@ var ( tInt = reflect.TypeOf(int(0)) tM = reflect.TypeOf(M{}) - tInterfaceSlice = reflect.TypeOf([]interface{}{}) + tInterfaceSlice = reflect.TypeOf([]any{}) tGetter = reflect.TypeOf((*getter)(nil)).Elem() tSetter = reflect.TypeOf((*setter)(nil)).Elem() ) @@ -131,7 +131,7 @@ type setter interface { // If GetBSON returns return a non-nil error, the marshalling procedure // will stop and error out with the provided value. type getter interface { - GetBSON() (interface{}, error) + GetBSON() (any, error) } // setterDecodeValue is the ValueDecoderFunc for Setter types. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go index 162bfa71..55d57446 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/primitive.go @@ -137,7 +137,7 @@ type Symbol string // CodeWithScope represents a BSON JavaScript code with scope value. type CodeWithScope struct { Code JavaScript - Scope interface{} + Scope any } func (cws CodeWithScope) String() string { @@ -257,17 +257,17 @@ func (d *D) UnmarshalJSON(b []byte) error { // E represents a BSON element for a D. It is usually used inside a D. type E struct { Key string - Value interface{} + Value any } // M is an unordered representation of a BSON document. This type should be used when the order of the elements does not -// matter. This type is handled as a regular map[string]interface{} when encoding and decoding. Elements will be +// matter. This type is handled as a regular map[string]any when encoding and decoding. Elements will be // serialized in an undefined, random order. If the order of the elements matters, a D should be used instead. // // Example usage: // // bson.M{"foo": "bar", "hello": "world", "pi": 3.14159} -type M map[string]interface{} +type M map[string]any func (m M) String() string { b, err := MarshalExtJSON(m, true, false) @@ -282,7 +282,7 @@ func (m M) String() string { // Example usage: // // bson.A{"bar", "world", 3.14159, bson.D{{"qux", 12345}}} -type A []interface{} +type A []any func jsonDecodeD(dec *json.Decoder) (D, error) { res := D{} @@ -326,8 +326,8 @@ func jsonDecodeD(dec *json.Decoder) (D, error) { return res, nil } -func jsonDecodeSlice(dec *json.Decoder) ([]interface{}, error) { - var res []interface{} +func jsonDecodeSlice(dec *json.Decoder) ([]any, error) { + var res []any done := false for !done { t, err := dec.Token() diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go index 53f053f0..24283a24 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/raw_value.go @@ -43,7 +43,7 @@ func (rv RawValue) IsZero() bool { // error is returned. This method will use the registry used to create the RawValue, if the RawValue // was created from partial BSON processing, or it will use the default registry. Users wishing to // specify the registry to use should use UnmarshalWithRegistry. -func (rv RawValue) Unmarshal(val interface{}) error { +func (rv RawValue) Unmarshal(val any) error { reg := rv.r if reg == nil { reg = defaultRegistry @@ -66,12 +66,12 @@ func (rv RawValue) Equal(rv2 RawValue) bool { // UnmarshalWithRegistry performs the same unmarshalling as Unmarshal but uses the provided registry // instead of the one attached or the default registry. -func (rv RawValue) UnmarshalWithRegistry(r *Registry, val interface{}) error { +func (rv RawValue) UnmarshalWithRegistry(r *Registry, val any) error { if r == nil { return ErrNilRegistry } - vr := newValueReader(rv.Type, bytes.NewReader(rv.Value)) + vr := newBufferedValueReader(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) @@ -86,12 +86,12 @@ func (rv RawValue) UnmarshalWithRegistry(r *Registry, val interface{}) error { // 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 *DecodeContext, val interface{}) error { +func (rv RawValue) UnmarshalWithContext(dc *DecodeContext, val any) error { if dc == nil { return ErrNilContext } - vr := newValueReader(rv.Type, bytes.NewReader(rv.Value)) + vr := newBufferedValueReader(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) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go index d8f65ddc..21057da4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/registry.go @@ -65,7 +65,7 @@ func (entme errNoTypeMapEntry) Error() string { // for any value whose type implements bson.Marshaler, regardless of the value's concrete type. // // 3. Type map entries - This can be used to associate a BSON type with a Go type. These type -// associations are used when decoding into a bson.D/bson.M or a struct field of type interface{}. +// associations are used when decoding into a bson.D/bson.M or a struct field of type any. // For example, by default, BSON int32 and int64 values decode as Go int32 and int64 instances, // respectively, when decoding into a bson.D. The following code would change the behavior so these // values decode as Go int instances instead: @@ -214,7 +214,7 @@ func (r *Registry) RegisterInterfaceDecoder(iface reflect.Type, dec ValueDecoder // mapping is decoding situations where an empty interface is used and a default type needs to be // created and decoded into. // -// By default, BSON documents will decode into interface{} values as bson.D. To change the default type for BSON +// By default, BSON documents will decode into any values as bson.D. To change the default type for BSON // documents, a type map entry for TypeEmbeddedDocument should be registered. For example, to force BSON documents // to decode to bson.Raw, use the following code: // diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go new file mode 100644 index 00000000..c9366e9f --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/streaming_byte_src.go @@ -0,0 +1,104 @@ +// Copyright (C) MongoDB, Inc. 2025-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 ( + "bufio" + "io" +) + +// streamingByteSrc reads from an ioReader wrapped in a bufio.Reader. It +// first reads the BSON length header, then ensures it only ever reads exactly +// that many bytes. +// +// Note: this approach trades memory usage for extra buffering and reader calls, +// so it is less performanted than the in-memory bufferedValueReader. +type streamingByteSrc struct { + br *bufio.Reader + offset int64 // offset is the current read position in the buffer +} + +var _ byteSrc = (*streamingByteSrc)(nil) + +// Read reads up to len(p) bytes from the underlying bufio.Reader, advancing +// the offset by the number of bytes read. +func (s *streamingByteSrc) readExact(p []byte) (int, error) { + n, err := io.ReadFull(s.br, p) + if err == nil { + s.offset += int64(n) + } + + return n, err +} + +// ReadByte returns the single byte at buf[offset] and advances offset by 1. +func (s *streamingByteSrc) ReadByte() (byte, error) { + c, err := s.br.ReadByte() + if err == nil { + s.offset++ + } + return c, err +} + +// peek returns buf[offset:offset+n] without advancing offset. +func (s *streamingByteSrc) peek(n int) ([]byte, error) { + return s.br.Peek(n) +} + +// discard advances offset by n bytes, returning the number of bytes discarded. +func (s *streamingByteSrc) discard(n int) (int, error) { + m, err := s.br.Discard(n) + s.offset += int64(m) + return m, err +} + +// readSlice scans buf[offset:] for the first occurrence of delim, returns +// buf[offset:idx+1], and advances offset past it; errors if delim not found. +func (s *streamingByteSrc) readSlice(delim byte) ([]byte, error) { + data, err := s.br.ReadSlice(delim) + if err != nil { + return nil, err + } + s.offset += int64(len(data)) + return data, nil +} + +// pos returns the current read position in the buffer. +func (s *streamingByteSrc) pos() int64 { + return s.offset +} + +// regexLength will return the total byte length of a BSON regex value. +func (s *streamingByteSrc) regexLength() (int32, error) { + var ( + count int32 + nulCount int + ) + + for nulCount < 2 { + buf, err := s.br.Peek(int(count) + 1) + if err != nil { + return 0, err + } + + b := buf[count] + count++ + if b == 0x00 { + nulCount++ + } + } + + return count, nil +} + +func (*streamingByteSrc) streamable() bool { + return true +} + +func (s *streamingByteSrc) reset() { + s.offset = 0 +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go index b3f160c8..83b63f5f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/struct_codec.go @@ -118,6 +118,10 @@ func (sc *structCodec) EncodeValue(ec EncodeContext, vw ValueWriter, val reflect } } + if ec.omitEmpty { + desc.omitEmpty = true + } + desc.encoder, rv, err = lookupElementEncoder(ec, desc.encoder, rv) if err != nil && !errors.Is(err, errInvalidValue) { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go index c2883aa4..d11cb2aa 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/types.go @@ -83,7 +83,7 @@ var tInt64 = reflect.TypeOf(int64(0)) var tString = reflect.TypeOf("") var tTime = reflect.TypeOf(time.Time{}) -var tEmpty = reflect.TypeOf((*interface{})(nil)).Elem() +var tEmpty = reflect.TypeOf((*any)(nil)).Elem() var tByteSlice = reflect.TypeOf([]byte(nil)) var tByte = reflect.TypeOf(byte(0x00)) var tURL = reflect.TypeOf(url.URL{}) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go index 72870c10..4377c4e4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/unmarshal.go @@ -41,8 +41,10 @@ type ValueUnmarshaler interface { // // When unmarshaling BSON, if the BSON value is null and the Go value is a // pointer, the pointer is set to nil without calling UnmarshalBSONValue. -func Unmarshal(data []byte, val interface{}) error { - vr := newDocumentReader(bytes.NewReader(data)) +func Unmarshal(data []byte, val any) error { + vr := getBufferedDocumentReader(data) + defer putBufferedDocumentReader(vr) + if l, err := vr.peekLength(); err != nil { return err } else if int(l) != len(data) { @@ -54,8 +56,8 @@ func Unmarshal(data []byte, val interface{}) error { // UnmarshalValue parses the BSON value of type t with bson.NewRegistry() and // stores the result in the value pointed to by val. If val is nil or not a pointer, // UnmarshalValue returns an error. -func UnmarshalValue(t Type, data []byte, val interface{}) error { - vr := newValueReader(t, bytes.NewReader(data)) +func UnmarshalValue(t Type, data []byte, val any) error { + vr := newBufferedValueReader(t, data) return unmarshalFromReader(DecodeContext{Registry: defaultRegistry}, vr, val) } @@ -68,7 +70,7 @@ func UnmarshalValue(t Type, data []byte, val interface{}) error { // // For more information about Extended JSON, see // https://www.mongodb.com/docs/manual/reference/mongodb-extended-json/ -func UnmarshalExtJSON(data []byte, canonicalOnly bool, val interface{}) error { +func UnmarshalExtJSON(data []byte, canonicalOnly bool, val any) error { ejvr, err := NewExtJSONValueReader(bytes.NewReader(data), canonicalOnly) if err != nil { return err @@ -77,7 +79,7 @@ func UnmarshalExtJSON(data []byte, canonicalOnly bool, val interface{}) error { return unmarshalFromReader(DecodeContext{Registry: defaultRegistry}, ejvr, val) } -func unmarshalFromReader(dc DecodeContext, vr ValueReader, val interface{}) error { +func unmarshalFromReader(dc DecodeContext, vr ValueReader, val any) error { dec := decPool.Get().(*Decoder) defer decPool.Put(dec) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go index 678c47b1..e5bcc198 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_reader.go @@ -13,8 +13,41 @@ import ( "fmt" "io" "math" + "sync" ) +type byteSrc interface { + io.ByteReader + + readExact(p []byte) (int, error) + + // Peek returns the next n bytes without advancing the cursor. It must return + // exactly n bytes or n error if fewer are available. + peek(n int) ([]byte, error) + + // discard advanced the cursor by n bytes, returning the actual number + // discarded or an error if fewer were available. + discard(n int) (int, error) + + // readSlice reads until (and including) the first occurrence of delim, + // returning the entire slice [start...delimiter] and advancing the cursor. + // past it. Returns an error if delim is not found. + readSlice(delim byte) ([]byte, error) + + // pos returns the number of bytes consumed so far. + pos() int64 + + // regexLength returns the total byte length of a BSON regex value (two + // C-strings including their terminating NULs) in buffered mode. + regexLength() (int32, error) + + // streamable returns true if this source can be used in a streaming context. + streamable() bool + + // reset resets the source to its initial state. + reset() +} + var _ ValueReader = &valueReader{} // ErrEOA is the error returned when the end of a BSON array has been reached. @@ -29,44 +62,92 @@ type vrState struct { end int64 } +var vrPool = sync.Pool{ + New: func() any { + return &valueReader{ + stack: make([]vrState, 1, 5), + } + }, +} + // valueReader is for reading BSON values. type valueReader struct { - r *bufio.Reader + src byteSrc offset int64 stack []vrState frame int64 } -// NewDocumentReader returns a ValueReader using b for the underlying BSON -// representation. -func NewDocumentReader(r io.Reader) ValueReader { - return newDocumentReader(r) +func getBufferedDocumentReader(b []byte) *valueReader { + return newBufferedDocumentReader(b) } -// newValueReader returns a ValueReader that starts in the Value mode instead of in top -// level document mode. This enables the creation of a ValueReader for a single BSON value. -func newValueReader(t Type, r io.Reader) ValueReader { - vr := newDocumentReader(r) - if len(vr.stack) == 0 { - vr.stack = make([]vrState, 1, 5) +func putBufferedDocumentReader(vr *valueReader) { + if vr == nil { + return } - vr.stack[0].mode = mValue - vr.stack[0].vType = t - return vr + + vr.src.reset() + + // Reset src and stack to avoid holding onto memory. + vr.src = nil + vr.frame = 0 + vr.stack = vr.stack[:0] + + vrPool.Put(vr) } -func newDocumentReader(r io.Reader) *valueReader { +// NewDocumentReader returns a ValueReader using b for the underlying BSON +// representation. +func NewDocumentReader(r io.Reader) ValueReader { stack := make([]vrState, 1, 5) stack[0] = vrState{ mode: mTopLevel, } + return &valueReader{ - r: bufio.NewReader(r), + src: &streamingByteSrc{br: bufio.NewReader(r), offset: 0}, stack: stack, } } +// newBufferedValueReader returns a ValueReader that starts in the Value mode +// instead of in top level document mode. This enables the creation of a +// ValueReader for a single BSON value. +func newBufferedValueReader(t Type, b []byte) ValueReader { + bVR := newBufferedDocumentReader(b) + + bVR.stack[0].vType = t + bVR.stack[0].mode = mValue + + return bVR +} + +func newBufferedDocumentReader(b []byte) *valueReader { + vr := vrPool.Get().(*valueReader) + + vr.src = &bufferedByteSrc{ + buf: b, + offset: 0, + } + + // Reset parse state. + vr.frame = 0 + if cap(vr.stack) < 1 { + vr.stack = make([]vrState, 1, 5) + } else { + vr.stack = vr.stack[:1] + } + + vr.stack[0] = vrState{ + mode: mTopLevel, + end: int64(len(b)), + } + + return vr +} + func (vr *valueReader) advanceFrame() { if vr.frame+1 >= int64(len(vr.stack)) { // We need to grow the stack length := len(vr.stack) @@ -86,62 +167,6 @@ func (vr *valueReader) advanceFrame() { vr.stack[vr.frame].end = 0 } -func (vr *valueReader) pushDocument() error { - vr.advanceFrame() - - vr.stack[vr.frame].mode = mDocument - - length, err := vr.readLength() - if err != nil { - return err - } - vr.stack[vr.frame].end = int64(length) + vr.offset - 4 - - return nil -} - -func (vr *valueReader) pushArray() error { - vr.advanceFrame() - - vr.stack[vr.frame].mode = mArray - - length, err := vr.readLength() - if err != nil { - return err - } - vr.stack[vr.frame].end = int64(length) + vr.offset - 4 - - return nil -} - -func (vr *valueReader) pushElement(t Type) { - vr.advanceFrame() - - vr.stack[vr.frame].mode = mElement - vr.stack[vr.frame].vType = t -} - -func (vr *valueReader) pushValue(t Type) { - vr.advanceFrame() - - vr.stack[vr.frame].mode = mValue - vr.stack[vr.frame].vType = t -} - -func (vr *valueReader) pushCodeWithScope() (int64, error) { - vr.advanceFrame() - - vr.stack[vr.frame].mode = mCodeWithScope - - length, err := vr.readLength() - if err != nil { - return 0, err - } - vr.stack[vr.frame].end = int64(length) + vr.offset - 4 - - return int64(length), nil -} - func (vr *valueReader) pop() error { var cnt int switch vr.stack[vr.frame].mode { @@ -151,22 +176,27 @@ func (vr *valueReader) pop() error { cnt = 2 // we pop twice to jump over the vrElement: vrDocument -> vrElement -> vrDocument/TopLevel/etc... } for i := 0; i < cnt && vr.frame > 0; i++ { - if vr.offset < vr.stack[vr.frame].end { - _, err := vr.r.Discard(int(vr.stack[vr.frame].end - vr.offset)) + if vr.src.pos() < vr.stack[vr.frame].end { + _, err := vr.src.discard(int(vr.stack[vr.frame].end - vr.src.pos())) if err != nil { return err } } vr.frame-- } - if vr.frame == 0 { - if vr.stack[0].end > vr.offset { - vr.stack[0].end -= vr.offset - } else { - vr.stack[0].end = 0 + + if vr.src.streamable() { + if vr.frame == 0 { + if vr.stack[0].end > vr.src.pos() { + vr.stack[0].end -= vr.src.pos() + } else { + vr.stack[0].end = 0 + } + + vr.src.reset() } - vr.offset = 0 } + return nil } @@ -209,7 +239,9 @@ func (vr *valueReader) Type() Type { return vr.stack[vr.frame].vType } -func (vr *valueReader) appendNextElement(dst []byte) ([]byte, error) { +// peekNextValueSize returns the length of the next value in the stream without +// offsetting the reader position. +func peekNextValueSize(vr *valueReader) (int32, error) { var length int32 var err error switch vr.stack[vr.frame].vType { @@ -237,58 +269,73 @@ func (vr *valueReader) appendNextElement(dst []byte) ([]byte, error) { case TypeObjectID: length = 12 case TypeRegex: - for n := 0; n < 2; n++ { // Read two C strings. - str, err := vr.r.ReadBytes(0x00) - if err != nil { - return nil, err - } - dst = append(dst, str...) - vr.offset += int64(len(str)) - } - return dst, nil + length, err = vr.src.regexLength() default: - return nil, fmt.Errorf("attempted to read bytes of unknown BSON type %v", vr.stack[vr.frame].vType) + return 0, fmt.Errorf("attempted to read bytes of unknown BSON type %v", vr.stack[vr.frame].vType) } - if err != nil { - return nil, err + + return length, err +} + +// readBytes tries to grab the next n bytes zero-allocation using peek+discard. +// If peek fails (e.g. bufio buffer full), it falls back to io.ReadFull. +func readBytes(src byteSrc, n int) ([]byte, error) { + if src.streamable() { + data := make([]byte, n) + if _, err := src.readExact(data); err != nil { + return nil, err + } + + return data, nil } - buf := make([]byte, length) - _, err = io.ReadFull(vr.r, buf) + // Zero-allocation path. + buf, err := src.peek(n) if err != nil { return nil, err } - dst = append(dst, buf...) - vr.offset += int64(len(buf)) - return dst, err + + _, _ = src.discard(n) // Discard the bytes from the source. + return buf, nil +} + +// readBytesValueReader returns a subslice [offset, offset+length) or EOF. +func (vr *valueReader) readBytes(n int32) ([]byte, error) { + if n < 0 { + return nil, fmt.Errorf("invalid length: %d", n) + } + + return readBytes(vr.src, int(n)) } +//nolint:unparam func (vr *valueReader) readValueBytes(dst []byte) (Type, []byte, error) { switch vr.stack[vr.frame].mode { case mTopLevel: length, err := vr.peekLength() if err != nil { - return Type(0), nil, err - } - dst, err = vr.appendBytes(dst, length) - if err != nil { - return Type(0), nil, err + return 0, nil, err } - return Type(0), dst, nil + b, err := vr.readBytes(length) + return Type(0), append(dst, b...), err case mElement, mValue: - dst, err := vr.appendNextElement(dst) + t := vr.stack[vr.frame].vType + + length, err := peekNextValueSize(vr) if err != nil { - return Type(0), dst, err + return t, dst, err } - t := vr.stack[vr.frame].vType - err = vr.pop() - if err != nil { + b, err := vr.readBytes(length) + + if err := vr.pop(); err != nil { return Type(0), nil, err } - return t, dst, nil + + return t, append(dst, b...), err + default: - return Type(0), nil, vr.invalidTransitionErr(0, "ReadValueBytes", []mode{mElement, mValue}) + return Type(0), nil, vr.invalidTransitionErr(0, "readValueBytes", []mode{mElement, mValue}) } } @@ -299,7 +346,12 @@ func (vr *valueReader) Skip() error { return vr.invalidTransitionErr(0, "Skip", []mode{mElement, mValue}) } - _, err := vr.appendNextElement(nil) + length, err := peekNextValueSize(vr) + if err != nil { + return err + } + + _, err = vr.src.discard(int(length)) if err != nil { return err } @@ -307,20 +359,33 @@ func (vr *valueReader) Skip() error { return vr.pop() } +// ReadArray returns an ArrayReader for the next BSON array in the valueReader +// source, advancing the reader position to the end of the array. func (vr *valueReader) ReadArray() (ArrayReader, error) { if err := vr.ensureElementValue(TypeArray, mArray, "ReadArray"); err != nil { return nil, err } - err := vr.pushArray() + // Push a new frame for the array. + vr.advanceFrame() + + // Read the 4-byte length. + size, err := vr.readLength() if err != nil { return nil, err } + // Compute the end position: current position + total size - length. + vr.stack[vr.frame].mode = mArray + vr.stack[vr.frame].end = vr.src.pos() + int64(size) - 4 + return vr, nil } -func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { +// ReadBinary reads a BSON binary value, returning the byte slice and the +// type of the binary data (0x02 for old binary, 0x00 for new binary, etc.), +// advancing the reader position to the end of the binary value. +func (vr *valueReader) ReadBinary() ([]byte, byte, error) { if err := vr.ensureElementValue(TypeBinary, 0, "ReadBinary"); err != nil { return nil, 0, err } @@ -330,7 +395,7 @@ func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { return nil, 0, err } - btype, err = vr.readByte() + btype, err := vr.readByte() if err != nil { return nil, 0, err } @@ -343,18 +408,24 @@ func (vr *valueReader) ReadBinary() (b []byte, btype byte, err error) { } } - b = make([]byte, length) - err = vr.read(b) + b, err := vr.readBytes(length) if err != nil { return nil, 0, err } + // copy so user doesn’t share underlying buffer + cp := make([]byte, len(b)) + copy(cp, b) + if err := vr.pop(); err != nil { return nil, 0, err } - return b, btype, nil + + return cp, btype, nil } +// ReadBoolean reads a BSON boolean value, returning true or false, advancing +// the reader position to the end of the boolean value. func (vr *valueReader) ReadBoolean() (bool, error) { if err := vr.ensureElementValue(TypeBoolean, 0, "ReadBoolean"); err != nil { return false, err @@ -375,6 +446,8 @@ func (vr *valueReader) ReadBoolean() (bool, error) { return b == 1, nil } +// ReadDocument reads a BSON embedded document, returning a DocumentReader, +// advancing the reader position to the end of the document. func (vr *valueReader) ReadDocument() (DocumentReader, error) { switch vr.stack[vr.frame].mode { case mTopLevel: @@ -386,7 +459,7 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { return nil, fmt.Errorf("invalid string length: %d", length) } - vr.stack[vr.frame].end = int64(length) + vr.offset - 4 + vr.stack[vr.frame].end = int64(length) + vr.src.pos() - 4 return vr, nil case mElement, mValue: if vr.stack[vr.frame].vType != TypeEmbeddedDocument { @@ -396,15 +469,22 @@ func (vr *valueReader) ReadDocument() (DocumentReader, error) { return nil, vr.invalidTransitionErr(mDocument, "ReadDocument", []mode{mTopLevel, mElement, mValue}) } - err := vr.pushDocument() + vr.advanceFrame() + + size, err := vr.readLength() if err != nil { return nil, err } + vr.stack[vr.frame].mode = mDocument + vr.stack[vr.frame].end = int64(size) + vr.src.pos() - 4 + return vr, nil } -func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err error) { +// ReadCodeWithScope reads a BSON CodeWithScope value, returning the code as a +// string, advancing the reader position to the end of the CodeWithScope value. +func (vr *valueReader) ReadCodeWithScope() (string, DocumentReader, error) { if err := vr.ensureElementValue(TypeCodeWithScope, 0, "ReadCodeWithScope"); err != nil { return "", nil, err } @@ -420,21 +500,26 @@ func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err if strLength <= 0 { return "", nil, fmt.Errorf("invalid string length: %d", strLength) } - strBytes := make([]byte, strLength) - err = vr.read(strBytes) + buf, err := vr.readBytes(strLength) if err != nil { return "", nil, err } - code = string(strBytes[:len(strBytes)-1]) - size, err := vr.pushCodeWithScope() + code := string(buf[:len(buf)-1]) + vr.advanceFrame() + + // Use readLength to ensure that we are not out of bounds. + size, err := vr.readLength() if err != nil { return "", nil, err } + vr.stack[vr.frame].mode = mCodeWithScope + vr.stack[vr.frame].end = vr.src.pos() + int64(size) - 4 + // The total length should equal: // 4 (total length) + strLength + 4 (the length of str itself) + (document length) - componentsLength := int64(4+strLength+4) + size + componentsLength := int64(4+strLength+4) + int64(size) if int64(totalLength) != componentsLength { return "", nil, fmt.Errorf( "length of CodeWithScope does not match lengths of components; total: %d; components: %d", @@ -444,27 +529,34 @@ func (vr *valueReader) ReadCodeWithScope() (code string, dr DocumentReader, err return code, vr, nil } -func (vr *valueReader) ReadDBPointer() (ns string, oid ObjectID, err error) { +// ReadDBPointer reads a BSON DBPointer value, returning the namespace, the +// object ID, and an error if any, advancing the reader position to the end of +// the DBPointer value. +func (vr *valueReader) ReadDBPointer() (string, ObjectID, error) { if err := vr.ensureElementValue(TypeDBPointer, 0, "ReadDBPointer"); err != nil { - return "", oid, err + return "", ObjectID{}, err } - - ns, err = vr.readString() + ns, err := vr.readString() if err != nil { - return "", oid, err + return "", ObjectID{}, err } - err = vr.read(oid[:]) + oidBytes, err := vr.readBytes(12) if err != nil { return "", ObjectID{}, err } + var oid ObjectID + copy(oid[:], oidBytes) + if err := vr.pop(); err != nil { return "", ObjectID{}, err } return ns, oid, nil } +// ReadDateTime reads a BSON DateTime value, advancing the reader position to +// the end of the DateTime value. func (vr *valueReader) ReadDateTime() (int64, error) { if err := vr.ensureElementValue(TypeDateTime, 0, "ReadDateTime"); err != nil { return 0, err @@ -481,17 +573,16 @@ func (vr *valueReader) ReadDateTime() (int64, error) { return i, nil } +// ReadDecimal128 reads a BSON Decimal128 value, advancing the reader +// to the end of the Decimal128 value. func (vr *valueReader) ReadDecimal128() (Decimal128, error) { if err := vr.ensureElementValue(TypeDecimal128, 0, "ReadDecimal128"); err != nil { return Decimal128{}, err } - - var b [16]byte - err := vr.read(b[:]) + b, err := vr.readBytes(16) if err != nil { return Decimal128{}, err } - l := binary.LittleEndian.Uint64(b[0:8]) h := binary.LittleEndian.Uint64(b[8:16]) @@ -501,6 +592,8 @@ func (vr *valueReader) ReadDecimal128() (Decimal128, error) { return NewDecimal128(h, l), nil } +// ReadDouble reads a BSON double value, advancing the reader position to +// to the end of the double value. func (vr *valueReader) ReadDouble() (float64, error) { if err := vr.ensureElementValue(TypeDouble, 0, "ReadDouble"); err != nil { return 0, err @@ -517,39 +610,59 @@ func (vr *valueReader) ReadDouble() (float64, error) { return math.Float64frombits(u), nil } +// ReadInt32 reads a BSON int32 value, advancing the reader position to the end +// of the int32 value. func (vr *valueReader) ReadInt32() (int32, error) { if err := vr.ensureElementValue(TypeInt32, 0, "ReadInt32"); err != nil { return 0, err } + i, err := vr.readi32() + if err != nil { + return 0, err + } if err := vr.pop(); err != nil { return 0, err } - return vr.readi32() + return i, nil } +// ReadInt64 reads a BSON int64 value, advancing the reader position to the end +// of the int64 value. func (vr *valueReader) ReadInt64() (int64, error) { if err := vr.ensureElementValue(TypeInt64, 0, "ReadInt64"); err != nil { return 0, err } + i, err := vr.readi64() + if err != nil { + return 0, err + } if err := vr.pop(); err != nil { return 0, err } - return vr.readi64() + return i, nil } +// ReadJavascript reads a BSON JavaScript value, advancing the reader +// to the end of the JavaScript value. func (vr *valueReader) ReadJavascript() (string, error) { if err := vr.ensureElementValue(TypeJavaScript, 0, "ReadJavascript"); err != nil { return "", err } + s, err := vr.readString() + if err != nil { + return "", err + } if err := vr.pop(); err != nil { return "", err } - return vr.readString() + return s, nil } +// ReadMaxKey reads a BSON MaxKey value, advancing the reader position to the +// end of the MaxKey value. func (vr *valueReader) ReadMaxKey() error { if err := vr.ensureElementValue(TypeMaxKey, 0, "ReadMaxKey"); err != nil { return err @@ -558,6 +671,8 @@ func (vr *valueReader) ReadMaxKey() error { return vr.pop() } +// ReadMinKey reads a BSON MinKey value, advancing the reader position to the +// end of the MinKey value. func (vr *valueReader) ReadMinKey() error { if err := vr.ensureElementValue(TypeMinKey, 0, "ReadMinKey"); err != nil { return err @@ -566,6 +681,8 @@ func (vr *valueReader) ReadMinKey() error { return vr.pop() } +// REadNull reads a BSON Null value, advancing the reader position to the +// end of the Null value. func (vr *valueReader) ReadNull() error { if err := vr.ensureElementValue(TypeNull, 0, "ReadNull"); err != nil { return err @@ -574,23 +691,29 @@ func (vr *valueReader) ReadNull() error { return vr.pop() } +// ReadObjectID reads a BSON ObjectID value, advancing the reader to the end of +// the ObjectID value. func (vr *valueReader) ReadObjectID() (ObjectID, error) { if err := vr.ensureElementValue(TypeObjectID, 0, "ReadObjectID"); err != nil { return ObjectID{}, err } - var oid ObjectID - err := vr.read(oid[:]) + oidBytes, err := vr.readBytes(12) if err != nil { return ObjectID{}, err } + var oid ObjectID + copy(oid[:], oidBytes) + if err := vr.pop(); err != nil { return ObjectID{}, err } return oid, nil } +// ReadRegex reads a BSON Regex value, advancing the reader position to the +// regex value. func (vr *valueReader) ReadRegex() (string, string, error) { if err := vr.ensureElementValue(TypeRegex, 0, "ReadRegex"); err != nil { return "", "", err @@ -612,39 +735,52 @@ func (vr *valueReader) ReadRegex() (string, string, error) { return pattern, options, nil } +// ReadString reads a BSON String value, advancing the reader position to the +// end of the String value. func (vr *valueReader) ReadString() (string, error) { if err := vr.ensureElementValue(TypeString, 0, "ReadString"); err != nil { return "", err } + s, err := vr.readString() + if err != nil { + return "", err + } if err := vr.pop(); err != nil { return "", err } - return vr.readString() + return s, nil } +// ReadSymbol reads a BSON Symbol value, advancing the reader position to the +// end of the Symbol value. func (vr *valueReader) ReadSymbol() (string, error) { if err := vr.ensureElementValue(TypeSymbol, 0, "ReadSymbol"); err != nil { return "", err } - + s, err := vr.readString() + if err != nil { + return "", err + } if err := vr.pop(); err != nil { return "", err } - return vr.readString() + return s, nil } -func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { +// ReadTimestamp reads a BSON Timestamp value, advancing the reader to the end +// of the Timestamp value. +func (vr *valueReader) ReadTimestamp() (uint32, uint32, error) { if err := vr.ensureElementValue(TypeTimestamp, 0, "ReadTimestamp"); err != nil { return 0, 0, err } - i, err = vr.readu32() + i, err := vr.readu32() if err != nil { return 0, 0, err } - t, err = vr.readu32() + t, err := vr.readu32() if err != nil { return 0, 0, err } @@ -655,6 +791,8 @@ func (vr *valueReader) ReadTimestamp() (t uint32, i uint32, err error) { return t, i, nil } +// ReadUndefined reads a BSON Undefined value, advancing the reader position +// to the end of the Undefined value. func (vr *valueReader) ReadUndefined() error { if err := vr.ensureElementValue(TypeUndefined, 0, "ReadUndefined"); err != nil { return err @@ -663,6 +801,8 @@ func (vr *valueReader) ReadUndefined() error { return vr.pop() } +// ReadElement reads the next element in the BSON document, advancing the +// reader position to the end of the element. func (vr *valueReader) ReadElement() (string, ValueReader, error) { switch vr.stack[vr.frame].mode { case mTopLevel, mDocument, mCodeWithScope: @@ -676,7 +816,7 @@ func (vr *valueReader) ReadElement() (string, ValueReader, error) { } if t == 0 { - if vr.offset != vr.stack[vr.frame].end { + if vr.src.pos() != vr.stack[vr.frame].end { return "", nil, vr.invalidDocumentLengthError() } @@ -689,10 +829,15 @@ func (vr *valueReader) ReadElement() (string, ValueReader, error) { return "", nil, err } - vr.pushElement(Type(t)) + vr.advanceFrame() + + vr.stack[vr.frame].mode = mElement + vr.stack[vr.frame].vType = Type(t) return name, vr, nil } +// ReadValue reads the next value in the BSON array, advancing the to the end of +// the value. func (vr *valueReader) ReadValue() (ValueReader, error) { switch vr.stack[vr.frame].mode { case mArray: @@ -706,7 +851,7 @@ func (vr *valueReader) ReadValue() (ValueReader, error) { } if t == 0 { - if vr.offset != vr.stack[vr.frame].end { + if vr.src.pos() != vr.stack[vr.frame].end { return nil, vr.invalidDocumentLengthError() } @@ -714,49 +859,32 @@ func (vr *valueReader) ReadValue() (ValueReader, error) { return nil, ErrEOA } - if _, err := vr.readCString(); err != nil { + _, err = vr.src.readSlice(0x00) + if err != nil { return nil, err } - vr.pushValue(Type(t)) - return vr, nil -} - -func (vr *valueReader) read(p []byte) error { - n, err := io.ReadFull(vr.r, p) - if err != nil { - return err - } - vr.offset += int64(n) - return nil -} + vr.advanceFrame() -func (vr *valueReader) appendBytes(dst []byte, length int32) ([]byte, error) { - buf := make([]byte, length) - err := vr.read(buf) - if err != nil { - return nil, err - } - return append(dst, buf...), nil + vr.stack[vr.frame].mode = mValue + vr.stack[vr.frame].vType = Type(t) + return vr, nil } func (vr *valueReader) readByte() (byte, error) { - b, err := vr.r.ReadByte() + b, err := vr.src.ReadByte() if err != nil { return 0x0, err } - vr.offset++ return b, nil } func (vr *valueReader) readCString() (string, error) { - str, err := vr.r.ReadString(0x00) + data, err := vr.src.readSlice(0x00) if err != nil { return "", err } - l := len(str) - vr.offset += int64(l) - return str[:l-1], nil + return string(data[:len(data)-1]), nil } func (vr *valueReader) readString() (string, error) { @@ -764,79 +892,69 @@ func (vr *valueReader) readString() (string, error) { if err != nil { return "", err } + if length <= 0 { return "", fmt.Errorf("invalid string length: %d", length) } - buf := make([]byte, length) - err = vr.read(buf) + raw, err := readBytes(vr.src, int(length)) if err != nil { return "", err } - if buf[length-1] != 0x00 { - return "", fmt.Errorf("string does not end with null byte, but with %v", buf[length-1]) + // Check that the last byte is the NUL terminator. + if raw[len(raw)-1] != 0x00 { + return "", fmt.Errorf("string does not end with null byte, but with %v", raw[len(raw)-1]) } - return string(buf[:length-1]), nil + // Convert and strip the trailing NUL. + return string(raw[:len(raw)-1]), nil } func (vr *valueReader) peekLength() (int32, error) { - buf, err := vr.r.Peek(4) + buf, err := vr.src.peek(4) if err != nil { return 0, err } - return int32(binary.LittleEndian.Uint32(buf)), nil } func (vr *valueReader) readLength() (int32, error) { - l, err := vr.readi32() - if err != nil { - return 0, err - } - if l < 0 { - return 0, fmt.Errorf("invalid negative length: %d", l) - } - return l, nil + return vr.readi32() } func (vr *valueReader) readi32() (int32, error) { - var buf [4]byte - err := vr.read(buf[:]) + raw, err := readBytes(vr.src, 4) if err != nil { return 0, err } - return int32(binary.LittleEndian.Uint32(buf[:])), nil + return int32(binary.LittleEndian.Uint32(raw)), nil } func (vr *valueReader) readu32() (uint32, error) { - var buf [4]byte - err := vr.read(buf[:]) + raw, err := readBytes(vr.src, 4) if err != nil { return 0, err } - return binary.LittleEndian.Uint32(buf[:]), nil + return binary.LittleEndian.Uint32(raw), nil } func (vr *valueReader) readi64() (int64, error) { - var buf [8]byte - err := vr.read(buf[:]) + raw, err := readBytes(vr.src, 8) if err != nil { return 0, err } - return int64(binary.LittleEndian.Uint64(buf[:])), nil + return int64(binary.LittleEndian.Uint64(raw)), nil } func (vr *valueReader) readu64() (uint64, error) { - var buf [8]byte - err := vr.read(buf[:]) + raw, err := readBytes(vr.src, 8) if err != nil { return 0, err } - return binary.LittleEndian.Uint64(buf[:]), nil + return binary.LittleEndian.Uint64(raw), nil } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go index 57334a92..9dd8912d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/bson/value_writer.go @@ -21,7 +21,7 @@ import ( var _ ValueWriter = &valueWriter{} var vwPool = sync.Pool{ - New: func() interface{} { + New: func() any { return new(valueWriter) }, } @@ -33,6 +33,29 @@ func putValueWriter(vw *valueWriter) { } } +var documentWriterPool = sync.Pool{ + New: func() any { + return newDocumentWriter(nil) + }, +} + +func getDocumentWriter(w io.Writer) *valueWriter { + vw := documentWriterPool.Get().(*valueWriter) + + vw.reset(vw.buf) + vw.buf = vw.buf[:0] + vw.w = w + + return vw +} + +func putDocumentWriter(vw *valueWriter) { + if vw != nil { + vw.w = nil // don't leak the writer + documentWriterPool.Put(vw) + } +} + // This is here so that during testing we can change it and not require // allocating a 4GB slice. var maxSize = math.MaxInt32 diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go index ff0f6493..7acdb2f1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil/bsoncoreutil.go @@ -8,7 +8,7 @@ package bsoncoreutil // Truncate truncates a given string for a certain width func Truncate(str string, width int) string { - if width == 0 { + if width <= 0 { return "" } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go index 1eba9c24..4af8284e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/bsonutil/bsonutil.go @@ -52,9 +52,9 @@ func RawArrayToDocuments(arr bson.RawArray) []bson.Raw { return out } -// RawToInterfaces takes one or many bson.Raw documents and returns them as a []interface{}. -func RawToInterfaces(docs ...bson.Raw) []interface{} { - out := make([]interface{}, len(docs)) +// RawToInterfaces takes one or many bson.Raw documents and returns them as a []any. +func RawToInterfaces(docs ...bson.Raw) []any { + out := make([]any, len(docs)) for i := range docs { out[i] = docs[i] } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go index aafb1e99..11a74312 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/codecutil/encoding.go @@ -22,22 +22,24 @@ var ErrNilValue = errors.New("value is nil") // MarshalError is returned when attempting to transform a value into a document // results in an error. type MarshalError struct { - Value interface{} + Value any Err error } // Error implements the error interface. func (e MarshalError) Error() string { - return fmt.Sprintf("cannot transform type %s to a BSON Document: %v", + return fmt.Sprintf("cannot marshal type %q to a BSON Document: %v", reflect.TypeOf(e.Value), e.Err) } +func (e MarshalError) Unwrap() error { return e.Err } + // EncoderFn is used to functionally construct an encoder for marshaling values. type EncoderFn func(io.Writer) *bson.Encoder // MarshalValue will attempt to encode the value with the encoder returned by // the encoder function. -func MarshalValue(val interface{}, encFn EncoderFn) (bsoncore.Value, error) { +func MarshalValue(val any, encFn EncoderFn) (bsoncore.Value, error) { // If the val is already a bsoncore.Value, then do nothing. if bval, ok := val.(bsoncore.Value); ok { return bval, nil diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go index df3adc36..89963799 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/description.go @@ -21,7 +21,7 @@ import ( ) const ( - MinWireVersion = 6 + MinWireVersion = 7 MaxWireVersion = 25 ) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go index e37cba59..74142a56 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/driverutil/operation.go @@ -6,6 +6,12 @@ package driverutil +import ( + "context" + "math" + "time" +) + // Operation Names should be sourced from the command reference documentation: // https://www.mongodb.com/docs/manual/reference/command/ const ( @@ -30,3 +36,34 @@ const ( UpdateOp = "update" // UpdateOp is the name for updating BulkWriteOp = "bulkWrite" // BulkWriteOp is the name for client-level bulk write ) + +// CalculateMaxTimeMS calculates the maxTimeMS value to send to the server +// based on the context deadline and the minimum round trip time. If the +// calculated maxTimeMS is likely to cause a socket timeout, then this function +// will return 0 and false. +func CalculateMaxTimeMS(ctx context.Context, rttMin time.Duration) (int64, bool) { + deadline, ok := ctx.Deadline() + if !ok { + return 0, true + } + + remainingTimeout := time.Until(deadline) + + // Always round up to the next millisecond value so we never truncate the calculated + // maxTimeMS value (e.g. 400 microseconds evaluates to 1ms, not 0ms). + maxTimeMS := int64((remainingTimeout - rttMin + time.Millisecond - 1) / time.Millisecond) + if maxTimeMS <= 0 { + return 0, false + } + + // The server will return a "BadValue" error if maxTimeMS is greater + // than the maximum positive int32 value (about 24.9 days). If the + // user specified a timeout value greater than that, omit maxTimeMS + // and let the client-side timeout handle cancelling the op if the + // timeout is ever reached. + if maxTimeMS > math.MaxInt32 { + return 0, true + } + + return maxTimeMS, true +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go index db0dd5f1..761ad14d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/httputil/httputil.go @@ -10,9 +10,17 @@ import ( "net/http" ) -// DefaultHTTPClient is the default HTTP client used across the driver. -var DefaultHTTPClient = &http.Client{ - Transport: http.DefaultTransport.(*http.Transport).Clone(), +var DefaultHTTPClient = &http.Client{} + +// NewHTTPClient will return the globally-defined DefaultHTTPClient, updating +// the transport if it differs from the http package DefaultTransport. +func NewHTTPClient() *http.Client { + client := DefaultHTTPClient + if _, ok := http.DefaultTransport.(*http.Transport); !ok { + client.Transport = http.DefaultTransport + } + + return client } // CloseIdleHTTPConnections closes any connections which were previously diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go index a601707c..ef6649ec 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/component.go @@ -75,10 +75,10 @@ const ( ) // KeyValues is a list of key-value pairs. -type KeyValues []interface{} +type KeyValues []any // Add adds a key-value pair to an instance of a KeyValues list. -func (kvs *KeyValues) Add(key string, value interface{}) { +func (kvs *KeyValues) Add(key string, value any) { *kvs = append(*kvs, key, value) } @@ -157,9 +157,9 @@ type Command struct { } // SerializeCommand takes a command and a variable number of key-value pairs and -// returns a slice of interface{} that can be passed to the logger for +// returns a slice of any that can be passed to the logger for // structured logging. -func SerializeCommand(cmd Command, extraKeysAndValues ...interface{}) KeyValues { +func SerializeCommand(cmd Command, extraKeysAndValues ...any) KeyValues { // Initialize the boilerplate keys and values. keysAndValues := KeyValues{ KeyCommandName, cmd.Name, @@ -203,7 +203,7 @@ type Connection struct { // SerializeConnection serializes a Connection message into a slice of keys and // values that can be passed to a logger. -func SerializeConnection(conn Connection, extraKeysAndValues ...interface{}) KeyValues { +func SerializeConnection(conn Connection, extraKeysAndValues ...any) KeyValues { // Initialize the boilerplate keys and values. keysAndValues := KeyValues{ KeyMessage, conn.Message, @@ -235,7 +235,7 @@ type Server struct { // SerializeServer serializes a Server message into a slice of keys and // values that can be passed to a logger. -func SerializeServer(srv Server, extraKV ...interface{}) KeyValues { +func SerializeServer(srv Server, extraKV ...any) KeyValues { // Initialize the boilerplate keys and values. keysAndValues := KeyValues{ KeyDriverConnectionID, srv.DriverConnectionID, @@ -272,7 +272,7 @@ type ServerSelection struct { // SerializeServerSelection serializes a Topology message into a slice of keys // and values that can be passed to a logger. -func SerializeServerSelection(srvSelection ServerSelection, extraKV ...interface{}) KeyValues { +func SerializeServerSelection(srvSelection ServerSelection, extraKV ...any) KeyValues { keysAndValues := KeyValues{ KeySelector, srvSelection.Selector, KeyOperation, srvSelection.Operation, @@ -299,7 +299,7 @@ type Topology struct { // SerializeTopology serializes a Topology message into a slice of keys and // values that can be passed to a logger. -func SerializeTopology(topo Topology, extraKV ...interface{}) KeyValues { +func SerializeTopology(topo Topology, extraKV ...any) KeyValues { keysAndValues := KeyValues{ KeyTopologyID, topo.ID.Hex(), } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go index 0a6c1bdc..3edceb61 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/io_sink.go @@ -36,12 +36,12 @@ func NewIOSink(out io.Writer) *IOSink { } // Info will write a JSON-encoded message to the io.Writer. -func (sink *IOSink) Info(_ int, msg string, keysAndValues ...interface{}) { +func (sink *IOSink) Info(_ int, msg string, keysAndValues ...any) { mapSize := len(keysAndValues) / 2 if math.MaxInt-mapSize >= 2 { mapSize += 2 } - kvMap := make(map[string]interface{}, mapSize) + kvMap := make(map[string]any, mapSize) kvMap[KeyTimestamp] = time.Now().UnixNano() kvMap[KeyMessage] = msg @@ -57,7 +57,7 @@ func (sink *IOSink) Info(_ int, msg string, keysAndValues ...interface{}) { } // Error will write a JSON-encoded error message to the io.Writer. -func (sink *IOSink) Error(err error, msg string, kv ...interface{}) { +func (sink *IOSink) Error(err error, msg string, kv ...any) { kv = append(kv, KeyError, err.Error()) sink.Info(0, msg, kv...) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go index c43e37c2..c9b700b2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/logger/logger.go @@ -36,10 +36,10 @@ const maxDocumentLengthEnvVar = "MONGODB_LOG_MAX_DOCUMENT_LENGTH" type LogSink interface { // Info logs a non-error message with the given key/value pairs. The // level argument is provided for optional logging. - Info(level int, msg string, keysAndValues ...interface{}) + Info(level int, msg string, keysAndValues ...any) // Error logs an error, with the given message and key/value pairs. - Error(err error, msg string, keysAndValues ...interface{}) + Error(err error, msg string, keysAndValues ...any) } // Logger represents the configuration for the internal logger. @@ -112,7 +112,7 @@ func (logger *Logger) LevelComponentEnabled(level Level, component Component) bo // this function is implemented based on the go-logr/logr LogSink interface, // which is why "Print" has a message parameter. Any duplication in code is // intentional to adhere to the logr pattern. -func (logger *Logger) Print(level Level, component Component, msg string, keysAndValues ...interface{}) { +func (logger *Logger) Print(level Level, component Component, msg string, keysAndValues ...any) { // If the level is not enabled for the component, then // skip the message. if !logger.LevelComponentEnabled(level, component) { @@ -130,7 +130,7 @@ func (logger *Logger) Print(level Level, component Component, msg string, keysAn // Error logs an error, with the given message and key/value pairs. // It functions similarly to Print, but may have unique behavior, and should be // preferred for logging errors. -func (logger *Logger) Error(err error, msg string, keysAndValues ...interface{}) { +func (logger *Logger) Error(err error, msg string, keysAndValues ...any) { if logger.Sink == nil { return } @@ -241,10 +241,9 @@ func FormatDocument(msg bson.Raw, width uint) string { return "{}" } - str := bsoncore.Document(msg).StringN(int(width)) + str, truncated := bsoncore.Document(msg).StringN(int(width)) - // If the last byte is not a closing bracket, then the document was truncated - if len(str) > 0 && str[len(str)-1] != '}' { + if truncated { str += TruncationSuffix } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go index 0345b96e..be58d38b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/mongoutil/mongoutil.go @@ -7,7 +7,9 @@ package mongoutil import ( + "context" "reflect" + "time" "go.mongodb.org/mongo-driver/v2/mongo/options" ) @@ -83,3 +85,17 @@ func HostsFromURI(uri string) ([]string, error) { return opts.Hosts, nil } + +// TimeoutWithinContext will return true if the provided timeout is nil or if +// it is less than the context deadline. If the context does not have a +// deadline, it will return true. +func TimeoutWithinContext(ctx context.Context, timeout time.Duration) bool { + deadline, ok := ctx.Deadline() + if !ok { + return true + } + + ctxTimeout := time.Until(deadline) + + return ctxTimeout <= 0 || timeout < ctxTimeout +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go b/vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go new file mode 100644 index 00000000..5e7527c9 --- /dev/null +++ b/vendor/go.mongodb.org/mongo-driver/v2/internal/optionsutil/options.go @@ -0,0 +1,45 @@ +// Copyright (C) MongoDB, Inc. 2025-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 optionsutil + +// Options stores internal options. +type Options struct { + values map[string]any +} + +// WithValue sets an option value with the associated key. +func WithValue(opts Options, key string, option any) Options { + if opts.values == nil { + opts.values = make(map[string]any) + } + opts.values[key] = option + return opts +} + +// Value returns the value associated with the options for key. +func Value(opts Options, key string) any { + if opts.values == nil { + return nil + } + if val, ok := opts.values[key]; ok { + return val + } + return nil +} + +// Equal compares two Options instances for equality. +func Equal(opts1, opts2 Options) bool { + if len(opts1.values) != len(opts2.values) { + return false + } + for key, val1 := range opts1.values { + if val2, ok := opts2.values[key]; !ok || val1 != val2 { + return false + } + } + return true +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go index e4146e8b..0fac0868 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/background_context.go @@ -29,6 +29,6 @@ func newBackgroundContext(ctx context.Context) context.Context { } } -func (b *backgroundContext) Value(key interface{}) interface{} { +func (b *backgroundContext) Value(key any) any { return b.childValuesCtx.Value(key) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go index 148a6275..fc6f7604 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/batch_cursor.go @@ -50,7 +50,12 @@ type batchCursor interface { // SetComment will set a user-configurable comment that can be used to // identify the operation in server logs. - SetComment(interface{}) + SetComment(any) + + // MaxAwaitTime returns the maximum amount of time the server will allow + // the operations to execute. This is only valid for tailable awaitData + // cursors. + MaxAwaitTime() *time.Duration } // changeStreamCursor is the interface implemented by batch cursors that also provide the functionality for retrieving diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go index 415a90ae..036e3bad 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write.go @@ -29,7 +29,7 @@ type bulkWriteBatch struct { // bulkWrite performs a bulkwrite operation type bulkWrite struct { - comment interface{} + comment any ordered *bool bypassDocumentValidation *bool models []WriteModel @@ -38,7 +38,8 @@ type bulkWrite struct { selector description.ServerSelector writeConcern *writeconcern.WriteConcern result BulkWriteResult - let interface{} + let any + rawData *bool } func (bw *bulkWrite) execute(ctx context.Context) error { @@ -49,7 +50,7 @@ func (bw *bulkWrite) execute(ctx context.Context) error { batches := createBatches(bw.models, ordered) bw.result = BulkWriteResult{ - UpsertedIDs: make(map[int64]interface{}), + UpsertedIDs: make(map[int64]any), } bwErr := BulkWriteException{ @@ -104,7 +105,7 @@ func (bw *bulkWrite) execute(ctx context.Context) error { func (bw *bulkWrite) runBatch(ctx context.Context, batch bulkWriteBatch) (BulkWriteResult, BulkWriteException, error) { batchRes := BulkWriteResult{ - UpsertedIDs: make(map[int64]interface{}), + UpsertedIDs: make(map[int64]any), } batchErr := BulkWriteException{} @@ -209,6 +210,10 @@ func (bw *bulkWrite) runInsert(ctx context.Context, batch bulkWriteBatch) (opera } op = op.Retry(retry) + if bw.rawData != nil { + op.RawData(*bw.rawData) + } + err := op.Execute(ctx) return op.Result(), err @@ -282,15 +287,19 @@ func (bw *bulkWrite) runDelete(ctx context.Context, batch bulkWriteBatch) (opera } op = op.Retry(retry) + if bw.rawData != nil { + op.RawData(*bw.rawData) + } + err := op.Execute(ctx) return op.Result(), err } func createDeleteDoc( - filter interface{}, + filter any, collation *options.Collation, - hint interface{}, + hint any, deleteOne bool, bsonOpts *options.BSONOptions, registry *bson.Registry, @@ -415,17 +424,21 @@ func (bw *bulkWrite) runUpdate(ctx context.Context, batch bulkWriteBatch) (opera } op = op.Retry(retry) + if bw.rawData != nil { + op.RawData(*bw.rawData) + } + err := op.Execute(ctx) return op.Result(), err } type updateDoc struct { - filter interface{} - update interface{} - hint interface{} - sort interface{} - arrayFilters []interface{} + filter any + update any + hint any + sort any + arrayFilters []any collation *options.Collation upsert *bool multi bool diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go index ddc3043a..f28af163 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/bulk_write_models.go @@ -23,7 +23,7 @@ type WriteModel interface { // // See corresponding setter methods for documentation. type InsertOneModel struct { - Document interface{} + Document any } // NewInsertOneModel creates a new InsertOneModel. @@ -34,7 +34,7 @@ func NewInsertOneModel() *InsertOneModel { // SetDocument specifies the document to be inserted. The document cannot be nil. If it does not have an _id field when // transformed into BSON, one will be added automatically to the marshalled document. The original document will not be // modified. -func (iom *InsertOneModel) SetDocument(doc interface{}) *InsertOneModel { +func (iom *InsertOneModel) SetDocument(doc any) *InsertOneModel { iom.Document = doc return iom } @@ -45,9 +45,9 @@ func (*InsertOneModel) writeModel() {} // // See corresponding setter methods for documentation. type DeleteOneModel struct { - Filter interface{} + Filter any Collation *options.Collation - Hint interface{} + Hint any } // NewDeleteOneModel creates a new DeleteOneModel. @@ -58,7 +58,7 @@ func NewDeleteOneModel() *DeleteOneModel { // SetFilter specifies a filter to use to select the document to delete. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (dom *DeleteOneModel) SetFilter(filter interface{}) *DeleteOneModel { +func (dom *DeleteOneModel) SetFilter(filter any) *DeleteOneModel { dom.Filter = filter return dom } @@ -70,13 +70,14 @@ func (dom *DeleteOneModel) SetCollation(collation *options.Collation) *DeleteOne return dom } -// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will -// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if -// this option is specified. The driver will return an error if this option is specified during an unacknowledged write -// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which -// means that no hint will be sent. -func (dom *DeleteOneModel) SetHint(hint interface{}) *DeleteOneModel { +// SetHint specifies the index to use for the operation. This should either be +// the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.4. Server versions < 4.4 will +// return an error if this option is specified. The driver will return an error +// if this option is specified during an unacknowledged write operation. The +// driver will return an error if the hint parameter is a multi-key map. The +// default value is nil, which means that no hint will be sent. +func (dom *DeleteOneModel) SetHint(hint any) *DeleteOneModel { dom.Hint = hint return dom } @@ -87,9 +88,9 @@ func (*DeleteOneModel) writeModel() {} // // See corresponding setter methods for documentation. type DeleteManyModel struct { - Filter interface{} + Filter any Collation *options.Collation - Hint interface{} + Hint any } // NewDeleteManyModel creates a new DeleteManyModel. @@ -99,7 +100,7 @@ func NewDeleteManyModel() *DeleteManyModel { // SetFilter specifies a filter to use to select documents to delete. The filter must be a document containing query // operators. It cannot be nil. -func (dmm *DeleteManyModel) SetFilter(filter interface{}) *DeleteManyModel { +func (dmm *DeleteManyModel) SetFilter(filter any) *DeleteManyModel { dmm.Filter = filter return dmm } @@ -111,13 +112,14 @@ func (dmm *DeleteManyModel) SetCollation(collation *options.Collation) *DeleteMa return dmm } -// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will -// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if -// this option is specified. The driver will return an error if this option is specified during an unacknowledged write -// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which -// means that no hint will be sent. -func (dmm *DeleteManyModel) SetHint(hint interface{}) *DeleteManyModel { +// SetHint specifies the index to use for the operation. This should either be +// the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.4. Server versions < 4.4 will +// return an error if this option is specified. The driver will return an error +// if this option is specified during an unacknowledged write operation. The +// driver will return an error if the hint parameter is a multi-key map. The +// default value is nil, which means that no hint will be sent. +func (dmm *DeleteManyModel) SetHint(hint any) *DeleteManyModel { dmm.Hint = hint return dmm } @@ -130,10 +132,10 @@ func (*DeleteManyModel) writeModel() {} type ReplaceOneModel struct { Collation *options.Collation Upsert *bool - Filter interface{} - Replacement interface{} - Hint interface{} - Sort interface{} + Filter any + Replacement any + Hint any + Sort any } // NewReplaceOneModel creates a new ReplaceOneModel. @@ -141,13 +143,14 @@ func NewReplaceOneModel() *ReplaceOneModel { return &ReplaceOneModel{} } -// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will -// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if -// this option is specified. The driver will return an error if this option is specified during an unacknowledged write -// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which -// means that no hint will be sent. -func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel { +// SetHint specifies the index to use for the operation. This should either be +// the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.2. Server versions < 4.2 will +// return an error if this option is specified. The driver will return an error +// if this option is specified during an unacknowledged write operation. The +// driver will return an error if the hint parameter is a multi-key map. The +// default value is nil, which means that no hint will be sent. +func (rom *ReplaceOneModel) SetHint(hint any) *ReplaceOneModel { rom.Hint = hint return rom } @@ -155,14 +158,14 @@ func (rom *ReplaceOneModel) SetHint(hint interface{}) *ReplaceOneModel { // SetFilter specifies a filter to use to select the document to replace. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (rom *ReplaceOneModel) SetFilter(filter interface{}) *ReplaceOneModel { +func (rom *ReplaceOneModel) SetFilter(filter any) *ReplaceOneModel { rom.Filter = filter return rom } // SetReplacement specifies a document that will be used to replace the selected document. It cannot be nil and cannot // contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). -func (rom *ReplaceOneModel) SetReplacement(rep interface{}) *ReplaceOneModel { +func (rom *ReplaceOneModel) SetReplacement(rep any) *ReplaceOneModel { rom.Replacement = rep return rom } @@ -186,7 +189,7 @@ func (rom *ReplaceOneModel) SetUpsert(upsert bool) *ReplaceOneModel { // matched by the sort order will be replaced. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (rom *ReplaceOneModel) SetSort(sort interface{}) *ReplaceOneModel { +func (rom *ReplaceOneModel) SetSort(sort any) *ReplaceOneModel { rom.Sort = sort return rom } @@ -199,11 +202,11 @@ func (*ReplaceOneModel) writeModel() {} type UpdateOneModel struct { Collation *options.Collation Upsert *bool - Filter interface{} - Update interface{} - ArrayFilters []interface{} - Hint interface{} - Sort interface{} + Filter any + Update any + ArrayFilters []any + Hint any + Sort any } // NewUpdateOneModel creates a new UpdateOneModel. @@ -211,13 +214,14 @@ func NewUpdateOneModel() *UpdateOneModel { return &UpdateOneModel{} } -// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will -// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if -// this option is specified. The driver will return an error if this option is specified during an unacknowledged write -// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which -// means that no hint will be sent. -func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel { +// SetHint specifies the index to use for the operation. This should either be +// the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.2. Server versions < 4.2 will +// return an error if this option is specified. The driver will return an error +// if this option is specified during an unacknowledged write operation. The +// driver will return an error if the hint parameter is a multi-key map. The +// default value is nil, which means that no hint will be sent. +func (uom *UpdateOneModel) SetHint(hint any) *UpdateOneModel { uom.Hint = hint return uom } @@ -225,21 +229,21 @@ func (uom *UpdateOneModel) SetHint(hint interface{}) *UpdateOneModel { // SetFilter specifies a filter to use to select the document to update. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (uom *UpdateOneModel) SetFilter(filter interface{}) *UpdateOneModel { +func (uom *UpdateOneModel) SetFilter(filter any) *UpdateOneModel { uom.Filter = filter return uom } // SetUpdate specifies the modifications to be made to the selected document. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (uom *UpdateOneModel) SetUpdate(update interface{}) *UpdateOneModel { +func (uom *UpdateOneModel) SetUpdate(update any) *UpdateOneModel { uom.Update = update return uom } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (uom *UpdateOneModel) SetArrayFilters(filters []interface{}) *UpdateOneModel { +func (uom *UpdateOneModel) SetArrayFilters(filters []any) *UpdateOneModel { uom.ArrayFilters = filters return uom } @@ -263,7 +267,7 @@ func (uom *UpdateOneModel) SetUpsert(upsert bool) *UpdateOneModel { // matched by the sort order will be updated. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (uom *UpdateOneModel) SetSort(sort interface{}) *UpdateOneModel { +func (uom *UpdateOneModel) SetSort(sort any) *UpdateOneModel { uom.Sort = sort return uom } @@ -276,10 +280,10 @@ func (*UpdateOneModel) writeModel() {} type UpdateManyModel struct { Collation *options.Collation Upsert *bool - Filter interface{} - Update interface{} - ArrayFilters []interface{} - Hint interface{} + Filter any + Update any + ArrayFilters []any + Hint any } // NewUpdateManyModel creates a new UpdateManyModel. @@ -287,34 +291,35 @@ func NewUpdateManyModel() *UpdateManyModel { return &UpdateManyModel{} } -// SetHint specifies the index to use for the operation. This should either be the index name as a string or the index -// specification as a document. This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will -// return an error if this option is specified. For server versions < 3.4, the driver will return a client-side error if -// this option is specified. The driver will return an error if this option is specified during an unacknowledged write -// operation. The driver will return an error if the hint parameter is a multi-key map. The default value is nil, which -// means that no hint will be sent. -func (umm *UpdateManyModel) SetHint(hint interface{}) *UpdateManyModel { +// SetHint specifies the index to use for the operation. This should either be +// the index name as a string or the index specification as a document. This +// option is only valid for MongoDB versions >= 4.2. Server versions < 4.2 will +// return an error if this option is specified. The driver will return an error +// if this option is specified during an unacknowledged write operation. The +// driver will return an error if the hint parameter is a multi-key map. The +// default value is nil, which means that no hint will be sent. +func (umm *UpdateManyModel) SetHint(hint any) *UpdateManyModel { umm.Hint = hint return umm } // SetFilter specifies a filter to use to select documents to update. The filter must be a document containing query // operators. It cannot be nil. -func (umm *UpdateManyModel) SetFilter(filter interface{}) *UpdateManyModel { +func (umm *UpdateManyModel) SetFilter(filter any) *UpdateManyModel { umm.Filter = filter return umm } // SetUpdate specifies the modifications to be made to the selected documents. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (umm *UpdateManyModel) SetUpdate(update interface{}) *UpdateManyModel { +func (umm *UpdateManyModel) SetUpdate(update any) *UpdateManyModel { umm.Update = update return umm } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (umm *UpdateManyModel) SetArrayFilters(filters []interface{}) *UpdateManyModel { +func (umm *UpdateManyModel) SetArrayFilters(filters []any) *UpdateManyModel { umm.ArrayFilters = filters return umm } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go index bde1ebc8..d5ad8058 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/change_stream.go @@ -12,7 +12,6 @@ import ( "fmt" "reflect" "strconv" - "time" "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/internal/csot" @@ -103,34 +102,7 @@ type changeStreamConfig struct { crypt driver.Crypt } -// validChangeStreamTimeouts will return "false" if maxAwaitTimeMS is set, -// timeoutMS is set to a non-zero value, and maxAwaitTimeMS is greater than or -// equal to timeoutMS. Otherwise, the timeouts are valid. -func validChangeStreamTimeouts(ctx context.Context, cs *ChangeStream) bool { - if cs.options == nil || cs.client == nil { - return true - } - - maxAwaitTime := cs.options.MaxAwaitTime - timeout := cs.client.timeout - - if maxAwaitTime == nil { - return true - } - - if deadline, ok := ctx.Deadline(); ok { - ctxTimeout := time.Until(deadline) - timeout = &ctxTimeout - } - - if timeout == nil { - return true - } - - return *timeout <= 0 || *maxAwaitTime < *timeout -} - -func newChangeStream(ctx context.Context, config changeStreamConfig, pipeline interface{}, +func newChangeStream(ctx context.Context, config changeStreamConfig, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { if ctx == nil { ctx = context.Background() @@ -339,8 +311,8 @@ AggregateExecuteLoop: break AggregateExecuteLoop } - switch tt := err.(type) { - case driver.Error: + var tt driver.Error + if errors.As(err, &tt) { // If error is not retryable, do not retry. if !tt.RetryableRead() { break AggregateExecuteLoop @@ -370,13 +342,13 @@ AggregateExecuteLoop: // Reset deployment. cs.aggregate.Deployment(cs.createOperationDeployment(server, conn)) - default: + } else { // Do not retry if error is not a driver error. break AggregateExecuteLoop } } if err != nil { - cs.err = replaceErrors(err) + cs.err = wrapErrors(err) return cs.err } @@ -384,7 +356,7 @@ AggregateExecuteLoop: cr.Server = server cs.cursor, cs.err = driver.NewBatchCursor(cr, cs.sess, cs.client.clock, cs.cursorOptions) - if cs.err = replaceErrors(cs.err); cs.err != nil { + if cs.err = wrapErrors(cs.err); cs.err != nil { return cs.Err() } @@ -429,7 +401,7 @@ func (cs *ChangeStream) storeResumeToken() error { return nil } -func (cs *ChangeStream) buildPipelineSlice(pipeline interface{}) error { +func (cs *ChangeStream) buildPipelineSlice(pipeline any) error { val := reflect.ValueOf(pipeline) if !val.IsValid() || !(val.Kind() == reflect.Slice) { cs.err = errors.New("can only marshal slices and arrays into aggregation pipelines, but got invalid") @@ -585,7 +557,7 @@ func (cs *ChangeStream) SetBatchSize(size int32) { // Decode will unmarshal the current event document into val and return any errors from the unmarshalling process // without any modification. If val is nil or is a typed nil, an error will be returned. -func (cs *ChangeStream) Decode(val interface{}) error { +func (cs *ChangeStream) Decode(val any) error { if cs.cursor == nil { return ErrNilCursor } @@ -597,13 +569,13 @@ func (cs *ChangeStream) Decode(val interface{}) error { // Err returns the last error seen by the change stream, or nil if no errors has occurred. func (cs *ChangeStream) Err() error { if cs.err != nil { - return replaceErrors(cs.err) + return wrapErrors(cs.err) } if cs.cursor == nil { return nil } - return replaceErrors(cs.cursor.Err()) + return wrapErrors(cs.cursor.Err()) } // Close closes this change stream and the underlying cursor. Next and TryNext must not be called after Close has been @@ -619,7 +591,7 @@ func (cs *ChangeStream) Close(ctx context.Context) error { return nil // cursor is already closed } - cs.err = replaceErrors(cs.cursor.Close(ctx)) + cs.err = wrapErrors(cs.cursor.Close(ctx)) cs.cursor = nil return cs.Err() } @@ -678,7 +650,7 @@ func (cs *ChangeStream) next(ctx context.Context, nonBlocking bool) bool { if len(cs.batch) == 0 { cs.loopNext(ctx, nonBlocking) if cs.err != nil { - cs.err = replaceErrors(cs.err) + cs.err = wrapErrors(cs.err) return false } if len(cs.batch) == 0 { @@ -696,10 +668,33 @@ func (cs *ChangeStream) next(ctx context.Context, nonBlocking bool) bool { } func (cs *ChangeStream) loopNext(ctx context.Context, nonBlocking bool) { - if !validChangeStreamTimeouts(ctx, cs) { - cs.err = fmt.Errorf("MaxAwaitTime must be less than the operation timeout") + // To avoid unnecessary socket timeouts, we attempt to short-circuit tailable + // awaitData "getMore" operations by ensuring that the maxAwaitTimeMS is less + // than the operation timeout. + // + // The specifications assume that drivers iteratively apply the timeout + // provided at the constructor level (e.g., (*collection).Find) for tailable + // awaitData cursors: + // + // If set, drivers MUST apply the timeoutMS option to the initial aggregate + // operation. Drivers MUST also apply the original timeoutMS value to each + // next call on the change stream but MUST NOT use it to derive a maxTimeMS + // field for getMore commands. + // + // The Go Driver might decide to support the above behavior with DRIVERS-2722. + // The principal concern is that it would be unexpected for users to apply an + // operation-level timeout via contexts to a constructor and then that timeout + // later be applied while working with a resulting cursor. Instead, it is more + // idiomatic to apply the timeout to the context passed to Next or TryNext. + if cs.options != nil && !nonBlocking { + maxAwaitTime := cs.cursorOptions.MaxAwaitTime + + // If maxAwaitTime is not set, this check is unnecessary. + if maxAwaitTime != nil && !mongoutil.TimeoutWithinContext(ctx, *maxAwaitTime) { + cs.err = fmt.Errorf("MaxAwaitTime must be less than the operation timeout") - return + return + } } // Apply the client-level timeout if the operation-level timeout is not set. @@ -719,7 +714,7 @@ func (cs *ChangeStream) loopNext(ctx context.Context, nonBlocking bool) { return } - cs.err = replaceErrors(cs.cursor.Err()) + cs.err = wrapErrors(cs.cursor.Err()) if cs.err == nil { // Check if cursor is alive if cs.ID() == 0 { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go index 09535f2b..cb2e5494 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client.go @@ -18,6 +18,7 @@ import ( "go.mongodb.org/mongo-driver/v2/internal/httputil" "go.mongodb.org/mongo-driver/v2/internal/logger" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/ptrutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/internal/uuid" @@ -82,7 +83,7 @@ type Client struct { cryptFLE driver.Crypt metadataClientFLE *Client internalClientFLE *Client - encryptedFieldsMap map[string]interface{} + encryptedFieldsMap map[string]any authenticator driver.Authenticator } @@ -239,7 +240,7 @@ func newClient(opts ...*options.ClientOptions) (*Client, error) { if client.deployment == nil { client.deployment, err = topology.New(cfg) if err != nil { - return nil, replaceErrors(err) + return nil, wrapErrors(err) } } @@ -261,7 +262,7 @@ func (c *Client) connect() error { if connector, ok := c.deployment.(driver.Connector); ok { err := connector.Connect() if err != nil { - return replaceErrors(err) + return wrapErrors(err) } } @@ -293,7 +294,7 @@ func (c *Client) connect() error { if subscriber, ok := c.deployment.(driver.Subscriber); ok { sub, err := subscriber.Subscribe() if err != nil { - return replaceErrors(err) + return wrapErrors(err) } updateChan = sub.Updates } @@ -350,7 +351,7 @@ func (c *Client) Disconnect(ctx context.Context) error { } if disconnector, ok := c.deployment.(driver.Disconnector); ok { - return replaceErrors(disconnector.Disconnect(ctx)) + return wrapErrors(disconnector.Disconnect(ctx)) } return nil @@ -381,7 +382,7 @@ func (c *Client) Ping(ctx context.Context, rp *readpref.ReadPref) error { {"ping", 1}, }, options.RunCmd().SetReadPreference(rp)) - return replaceErrors(res.Err()) + return wrapErrors(res.Err()) } // StartSession starts a new session configured with the given options. @@ -434,7 +435,7 @@ func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (* sess, err := session.NewClientSession(c.sessionPool, c.id, coreOpts) if err != nil { - return nil, replaceErrors(err) + return nil, wrapErrors(err) } return &Session{ @@ -609,7 +610,8 @@ func (c *Client) newMongoCrypt(opts *options.AutoEncryptionOptions) (*mongocrypt SetEncryptedFieldsMap(cryptEncryptedFieldsMap). SetCryptSharedLibDisabled(cryptSharedLibDisabled || bypassAutoEncryption). SetCryptSharedLibOverridePath(cryptSharedLibPath). - SetHTTPClient(opts.HTTPClient)) + SetHTTPClient(opts.HTTPClient). + SetKeyExpiration(opts.KeyExpiration)) if err != nil { return nil, err } @@ -679,7 +681,7 @@ func (c *Client) Database(name string, opts ...options.Lister[options.DatabaseOp // The opts parameter can be used to specify options for this operation (see the options.ListDatabasesOptions documentation). // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/listDatabases/. -func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ...options.Lister[options.ListDatabasesOptions]) (ListDatabasesResult, error) { +func (c *Client) ListDatabases(ctx context.Context, filter any, opts ...options.Lister[options.ListDatabasesOptions]) (ListDatabasesResult, error) { if ctx == nil { ctx = context.Background() } @@ -740,7 +742,7 @@ func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ... err = op.Execute(ctx) if err != nil { - return ListDatabasesResult{}, replaceErrors(err) + return ListDatabasesResult{}, wrapErrors(err) } return newListDatabasesResultFromOperation(op.Result()), nil @@ -757,7 +759,7 @@ func (c *Client) ListDatabases(ctx context.Context, filter interface{}, opts ... // documentation.) // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/listDatabases/. -func (c *Client) ListDatabaseNames(ctx context.Context, filter interface{}, opts ...options.Lister[options.ListDatabasesOptions]) ([]string, error) { +func (c *Client) ListDatabaseNames(ctx context.Context, filter any, opts ...options.Lister[options.ListDatabasesOptions]) ([]string, error) { opts = append(opts, options.ListDatabases().SetNameOnly(true)) res, err := c.ListDatabases(ctx, filter, opts...) @@ -840,7 +842,7 @@ func (c *Client) UseSessionWithOptions( // // The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptions // documentation). -func (c *Client) Watch(ctx context.Context, pipeline interface{}, +func (c *Client) Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { csConfig := changeStreamConfig{ readConcern: c.readConcern, @@ -888,7 +890,7 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, } if len(writes) == 0 { - return nil, ErrEmptySlice + return nil, fmt.Errorf("invalid writes: %w", ErrEmptySlice) } bwo, err := mongoutil.NewOptions(opts...) if err != nil { @@ -956,6 +958,11 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, selector: selector, writeConcern: wc, } + if rawDataOpt := optionsutil.Value(bwo.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op.rawData = &rawData + } + } if bwo.VerboseResults == nil || !(*bwo.VerboseResults) { op.errorsOnly = true } else if !acknowledged { @@ -964,7 +971,7 @@ func (c *Client) BulkWrite(ctx context.Context, writes []ClientBulkWrite, op.result.Acknowledged = acknowledged op.result.HasVerboseResults = !op.errorsOnly err = op.execute(ctx) - return &op.result, replaceErrors(err) + return &op.result, wrapErrors(err) } // newLogger will use the LoggerOptions to create an internal logger and publish diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go index ab2d8b6a..27c3ad3c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write.go @@ -30,7 +30,7 @@ const ( type clientBulkWritePair struct { namespace string - model interface{} + model any } type clientBulkWrite struct { @@ -38,23 +38,24 @@ type clientBulkWrite struct { errorsOnly bool ordered *bool bypassDocumentValidation *bool - comment interface{} - let interface{} + comment any + let any session *session.Client client *Client selector description.ServerSelector writeConcern *writeconcern.WriteConcern + rawData *bool result ClientBulkWriteResult } func (bw *clientBulkWrite) execute(ctx context.Context) error { if len(bw.writePairs) == 0 { - return ErrEmptySlice + return fmt.Errorf("invalid writes: %w", ErrEmptySlice) } - for _, m := range bw.writePairs { + for i, m := range bw.writePairs { if m.model == nil { - return ErrNilDocument + return fmt.Errorf("error from model at index %d: %w", i, ErrNilDocument) } } batches := &modelBatches{ @@ -143,6 +144,10 @@ func (bw *clientBulkWrite) newCommand() func([]byte, description.SelectedServer) } dst = bsoncore.AppendDocumentElement(dst, "let", let) } + // Set rawData for 8.2+ servers. + if bw.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *bw.rawData) + } return dst, nil } } @@ -156,7 +161,7 @@ type cursorInfo struct { N int32 NModified *int32 Upserted *struct { - ID interface{} `bson:"_id"` + ID any `bson:"_id"` } } @@ -188,7 +193,7 @@ type modelBatches struct { retryMode driver.RetryMode // RetryNone by default cursorHandlers []func(*cursorInfo, bson.Raw) bool - newIDMap map[int]interface{} + newIDMap map[int]any result *ClientBulkWriteResult writeConcernErrors []WriteConcernError @@ -261,7 +266,7 @@ func (mb *modelBatches) appendBatches(fn functionSet, dst []byte, maxCount, tota } mb.cursorHandlers = mb.cursorHandlers[:0] - mb.newIDMap = make(map[int]interface{}) + mb.newIDMap = make(map[int]any) nsMap := make(map[string]int) getNsIndex := func(namespace string) (int, bool) { @@ -296,7 +301,7 @@ func (mb *modelBatches) appendBatches(fn functionSet, dst []byte, maxCount, tota switch model := mb.writePairs[i].model.(type) { case *ClientInsertOneModel: mb.cursorHandlers = append(mb.cursorHandlers, mb.appendInsertResult) - var id interface{} + var id any id, doc, err = (&clientInsertDoc{ namespace: nsIdx, document: model.Document, @@ -471,7 +476,11 @@ func (mb *modelBatches) processResponse(ctx context.Context, resp bsoncore.Docum return err } var cursor *Cursor - cursor, err = newCursor(bCursor, mb.client.bsonOpts, mb.client.registry) + cursor, err = newCursor(bCursor, mb.client.bsonOpts, mb.client.registry, + + // This op doesn't return a cursor to the user, so setting the client + // timeout should be a no-op. + withCursorOptionClientTimeout(mb.client.timeout)) if err != nil { return err } @@ -577,10 +586,10 @@ func (mb *modelBatches) appendUpdateResult(cur *cursorInfo, raw bson.Raw) bool { type clientInsertDoc struct { namespace int - document interface{} + document any } -func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson.Registry) (interface{}, bsoncore.Document, error) { +func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson.Registry) (any, bsoncore.Document, error) { uidx, doc := bsoncore.AppendDocumentStart(nil) doc = bsoncore.AppendInt32Element(doc, "insert", int32(d.namespace)) @@ -588,7 +597,7 @@ func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson. if err != nil { return nil, nil, err } - var id interface{} + var id any f, id, err = ensureID(f, bson.NilObjectID, bsonOpts, registry) if err != nil { return nil, nil, err @@ -600,12 +609,12 @@ func (d *clientInsertDoc) marshal(bsonOpts *options.BSONOptions, registry *bson. type clientUpdateDoc struct { namespace int - filter interface{} - update interface{} - hint interface{} - arrayFilters []interface{} + filter any + update any + hint any + arrayFilters []any collation *options.Collation - sort interface{} + sort any upsert *bool multi bool checkDollarKey bool @@ -676,9 +685,9 @@ func (d *clientUpdateDoc) marshal(bsonOpts *options.BSONOptions, registry *bson. type clientDeleteDoc struct { namespace int - filter interface{} + filter any collation *options.Collation - hint interface{} + hint any multi bool } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go index 87550eee..da0ea18e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_bulk_write_models.go @@ -24,7 +24,7 @@ type ClientWriteModel interface { // // See corresponding setter methods for documentation. type ClientInsertOneModel struct { - Document interface{} + Document any } // NewClientInsertOneModel creates a new ClientInsertOneModel. @@ -37,7 +37,7 @@ func (*ClientInsertOneModel) clientWriteModel() {} // SetDocument specifies the document to be inserted. The document cannot be nil. If it does not have an _id field when // transformed into BSON, one will be added automatically to the marshalled document. The original document will not be // modified. -func (iom *ClientInsertOneModel) SetDocument(doc interface{}) *ClientInsertOneModel { +func (iom *ClientInsertOneModel) SetDocument(doc any) *ClientInsertOneModel { iom.Document = doc return iom } @@ -48,11 +48,11 @@ func (iom *ClientInsertOneModel) SetDocument(doc interface{}) *ClientInsertOneMo type ClientUpdateOneModel struct { Collation *options.Collation Upsert *bool - Filter interface{} - Update interface{} - ArrayFilters []interface{} - Hint interface{} - Sort interface{} + Filter any + Update any + ArrayFilters []any + Hint any + Sort any } // NewClientUpdateOneModel creates a new ClientUpdateOneModel. @@ -64,7 +64,7 @@ func (*ClientUpdateOneModel) clientWriteModel() {} // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (uom *ClientUpdateOneModel) SetHint(hint interface{}) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetHint(hint any) *ClientUpdateOneModel { uom.Hint = hint return uom } @@ -72,21 +72,21 @@ func (uom *ClientUpdateOneModel) SetHint(hint interface{}) *ClientUpdateOneModel // SetFilter specifies a filter to use to select the document to update. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (uom *ClientUpdateOneModel) SetFilter(filter interface{}) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetFilter(filter any) *ClientUpdateOneModel { uom.Filter = filter return uom } // SetUpdate specifies the modifications to be made to the selected document. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (uom *ClientUpdateOneModel) SetUpdate(update interface{}) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetUpdate(update any) *ClientUpdateOneModel { uom.Update = update return uom } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (uom *ClientUpdateOneModel) SetArrayFilters(filters []interface{}) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetArrayFilters(filters []any) *ClientUpdateOneModel { uom.ArrayFilters = filters return uom } @@ -110,7 +110,7 @@ func (uom *ClientUpdateOneModel) SetUpsert(upsert bool) *ClientUpdateOneModel { // matched by the sort order will be updated. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (uom *ClientUpdateOneModel) SetSort(sort interface{}) *ClientUpdateOneModel { +func (uom *ClientUpdateOneModel) SetSort(sort any) *ClientUpdateOneModel { uom.Sort = sort return uom } @@ -121,10 +121,10 @@ func (uom *ClientUpdateOneModel) SetSort(sort interface{}) *ClientUpdateOneModel type ClientUpdateManyModel struct { Collation *options.Collation Upsert *bool - Filter interface{} - Update interface{} - ArrayFilters []interface{} - Hint interface{} + Filter any + Update any + ArrayFilters []any + Hint any } // NewClientUpdateManyModel creates a new ClientUpdateManyModel. @@ -136,28 +136,28 @@ func (*ClientUpdateManyModel) clientWriteModel() {} // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (umm *ClientUpdateManyModel) SetHint(hint interface{}) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetHint(hint any) *ClientUpdateManyModel { umm.Hint = hint return umm } // SetFilter specifies a filter to use to select documents to update. The filter must be a document containing query // operators. It cannot be nil. -func (umm *ClientUpdateManyModel) SetFilter(filter interface{}) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetFilter(filter any) *ClientUpdateManyModel { umm.Filter = filter return umm } // SetUpdate specifies the modifications to be made to the selected documents. The value must be a document containing // update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). It cannot be nil or empty. -func (umm *ClientUpdateManyModel) SetUpdate(update interface{}) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetUpdate(update any) *ClientUpdateManyModel { umm.Update = update return umm } // SetArrayFilters specifies a set of filters to determine which elements should be modified when updating an array // field. -func (umm *ClientUpdateManyModel) SetArrayFilters(filters []interface{}) *ClientUpdateManyModel { +func (umm *ClientUpdateManyModel) SetArrayFilters(filters []any) *ClientUpdateManyModel { umm.ArrayFilters = filters return umm } @@ -183,10 +183,10 @@ func (umm *ClientUpdateManyModel) SetUpsert(upsert bool) *ClientUpdateManyModel type ClientReplaceOneModel struct { Collation *options.Collation Upsert *bool - Filter interface{} - Replacement interface{} - Hint interface{} - Sort interface{} + Filter any + Replacement any + Hint any + Sort any } // NewClientReplaceOneModel creates a new ClientReplaceOneModel. @@ -198,7 +198,7 @@ func (*ClientReplaceOneModel) clientWriteModel() {} // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (rom *ClientReplaceOneModel) SetHint(hint interface{}) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetHint(hint any) *ClientReplaceOneModel { rom.Hint = hint return rom } @@ -206,14 +206,14 @@ func (rom *ClientReplaceOneModel) SetHint(hint interface{}) *ClientReplaceOneMod // SetFilter specifies a filter to use to select the document to replace. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (rom *ClientReplaceOneModel) SetFilter(filter interface{}) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetFilter(filter any) *ClientReplaceOneModel { rom.Filter = filter return rom } // SetReplacement specifies a document that will be used to replace the selected document. It cannot be nil and cannot // contain any update operators (https://www.mongodb.com/docs/manual/reference/operator/update/). -func (rom *ClientReplaceOneModel) SetReplacement(rep interface{}) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetReplacement(rep any) *ClientReplaceOneModel { rom.Replacement = rep return rom } @@ -237,7 +237,7 @@ func (rom *ClientReplaceOneModel) SetUpsert(upsert bool) *ClientReplaceOneModel // matched by the sort order will be replaced. This option is only valid for MongoDB versions >= 8.0. The sort parameter // is evaluated sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). The // default value is nil. -func (rom *ClientReplaceOneModel) SetSort(sort interface{}) *ClientReplaceOneModel { +func (rom *ClientReplaceOneModel) SetSort(sort any) *ClientReplaceOneModel { rom.Sort = sort return rom } @@ -246,9 +246,9 @@ func (rom *ClientReplaceOneModel) SetSort(sort interface{}) *ClientReplaceOneMod // // See corresponding setter methods for documentation. type ClientDeleteOneModel struct { - Filter interface{} + Filter any Collation *options.Collation - Hint interface{} + Hint any } // NewClientDeleteOneModel creates a new ClientDeleteOneModel. @@ -261,7 +261,7 @@ func (*ClientDeleteOneModel) clientWriteModel() {} // SetFilter specifies a filter to use to select the document to delete. The filter must be a document containing query // operators. It cannot be nil. If the filter matches multiple documents, one will be selected from the matching // documents. -func (dom *ClientDeleteOneModel) SetFilter(filter interface{}) *ClientDeleteOneModel { +func (dom *ClientDeleteOneModel) SetFilter(filter any) *ClientDeleteOneModel { dom.Filter = filter return dom } @@ -275,7 +275,7 @@ func (dom *ClientDeleteOneModel) SetCollation(collation *options.Collation) *Cli // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (dom *ClientDeleteOneModel) SetHint(hint interface{}) *ClientDeleteOneModel { +func (dom *ClientDeleteOneModel) SetHint(hint any) *ClientDeleteOneModel { dom.Hint = hint return dom } @@ -284,9 +284,9 @@ func (dom *ClientDeleteOneModel) SetHint(hint interface{}) *ClientDeleteOneModel // // See corresponding setter methods for documentation. type ClientDeleteManyModel struct { - Filter interface{} + Filter any Collation *options.Collation - Hint interface{} + Hint any } // NewClientDeleteManyModel creates a new ClientDeleteManyModel. @@ -298,7 +298,7 @@ func (*ClientDeleteManyModel) clientWriteModel() {} // SetFilter specifies a filter to use to select documents to delete. The filter must be a document containing query // operators. It cannot be nil. -func (dmm *ClientDeleteManyModel) SetFilter(filter interface{}) *ClientDeleteManyModel { +func (dmm *ClientDeleteManyModel) SetFilter(filter any) *ClientDeleteManyModel { dmm.Filter = filter return dmm } @@ -312,7 +312,7 @@ func (dmm *ClientDeleteManyModel) SetCollation(collation *options.Collation) *Cl // SetHint specifies the index to use for the operation. This should either be the index name as a string or the index // specification as a document. The default value is nil, which means that no hint will be sent. -func (dmm *ClientDeleteManyModel) SetHint(hint interface{}) *ClientDeleteManyModel { +func (dmm *ClientDeleteManyModel) SetHint(hint any) *ClientDeleteManyModel { dmm.Hint = hint return dmm } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go index 07c18529..32851fff 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/client_encryption.go @@ -59,7 +59,8 @@ func NewClientEncryption(keyVaultClient *Client, opts ...options.Lister[options. // ClientEncryption because it's only needed for AutoEncryption and we don't expect users to // have the crypt_shared library installed if they're using ClientEncryption. SetCryptSharedLibDisabled(true). - SetHTTPClient(cea.HTTPClient)) + SetHTTPClient(cea.HTTPClient). + SetKeyExpiration(cea.KeyExpiration)) if err != nil { return nil, err } @@ -81,7 +82,7 @@ func NewClientEncryption(keyVaultClient *Client, opts ...options.Lister[options. // It returns the created collection and the encrypted fields document used to create it. func (ce *ClientEncryption) CreateEncryptedCollection(ctx context.Context, db *Database, coll string, createOpts options.Lister[options.CreateCollectionOptions], - kmsProvider string, masterKey interface{}) (*Collection, bson.M, error) { + kmsProvider string, masterKey any) (*Collection, bson.M, error) { if ce.closed { return nil, nil, ErrClientDisconnected } @@ -272,7 +273,7 @@ func (ce *ClientEncryption) Encrypt( // {$and: [{$gt: [, ]}, {$lt: [, ]}] // $gt may also be $gte. $lt may also be $lte. // Only supported for queryType "range" -func (ce *ClientEncryption) EncryptExpression(ctx context.Context, expr interface{}, result interface{}, opts ...options.Lister[options.EncryptOptions]) error { +func (ce *ClientEncryption) EncryptExpression(ctx context.Context, expr any, result any, opts ...options.Lister[options.EncryptOptions]) error { if ce.closed { return ErrClientDisconnected } @@ -443,7 +444,7 @@ func setRewrapManyDataKeyWriteModels(rewrappedDocuments []bsoncore.Document, wri // libmongocrypt 1.5.2 is required. An error is returned if the detected version of libmongocrypt is less than 1.5.2. func (ce *ClientEncryption) RewrapManyDataKey( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.RewrapManyDataKeyOptions], ) (*RewrapManyDataKeyResult, error) { // libmongocrypt versions 1.5.0 and 1.5.1 have a severe bug in RewrapManyDataKey. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go index a9279f13..ef4188d6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/collection.go @@ -17,6 +17,7 @@ import ( "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/internal/csfle" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/mongo/readconcern" @@ -46,7 +47,7 @@ type Collection struct { // aggregateParams is used to store information to configure an Aggregate operation. type aggregateParams struct { ctx context.Context - pipeline interface{} + pipeline any client *Client bsonOpts *options.BSONOptions registry *bson.Registry @@ -193,7 +194,7 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, opts ...options.Lister[options.BulkWriteOptions]) (*BulkWriteResult, error) { if len(models) == 0 { - return nil, ErrEmptySlice + return nil, fmt.Errorf("invalid models: %w", ErrEmptySlice) } if ctx == nil { @@ -221,9 +222,9 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, selector := makePinnedSelector(sess, coll.writeSelector) - for _, model := range models { + for i, model := range models { if model == nil { - return nil, ErrNilDocument + return nil, fmt.Errorf("invalid model at index %d: %w", i, ErrNilDocument) } } @@ -245,23 +246,28 @@ func (coll *Collection) BulkWrite(ctx context.Context, models []WriteModel, writeConcern: wc, let: args.Let, } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op.rawData = &rawData + } + } err = op.execute(ctx) - return &op.result, replaceErrors(err) + return &op.result, wrapErrors(err) } func (coll *Collection) insert( ctx context.Context, - documents []interface{}, + documents []any, opts ...options.Lister[options.InsertManyOptions], -) ([]interface{}, error) { +) ([]any, error) { if ctx == nil { ctx = context.Background() } - result := make([]interface{}, len(documents)) + result := make([]any, len(documents)) docs := make([]bsoncore.Document, len(documents)) for i, doc := range documents { @@ -324,6 +330,11 @@ func (coll *Collection) insert( if args.Ordered != nil { op = op.Ordered(*args.Ordered) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if coll.client.retryWrites { retry = driver.RetryOncePerCommand @@ -360,7 +371,7 @@ func (coll *Collection) insert( // The opts parameter can be used to specify options for the operation (see the options.InsertOneOptions documentation.) // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/insert/. -func (coll *Collection) InsertOne(ctx context.Context, document interface{}, +func (coll *Collection) InsertOne(ctx context.Context, document any, opts ...options.Lister[options.InsertOneOptions]) (*InsertOneResult, error) { args, err := mongoutil.NewOptions(opts...) @@ -375,7 +386,14 @@ func (coll *Collection) InsertOne(ctx context.Context, document interface{}, if args.Comment != nil { imOpts.SetComment(args.Comment) } - res, err := coll.insert(ctx, []interface{}{document}, imOpts) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + imOpts.Opts = append(imOpts.Opts, func(opts *options.InsertManyOptions) error { + optionsutil.WithValue(opts.Internal, "rawData", rawDataOpt) + + return nil + }) + } + res, err := coll.insert(ctx, []any{document}, imOpts) rr, err := processWriteError(err) if rr&rrOne == 0 && rr.isAcknowledged() { @@ -401,19 +419,19 @@ func (coll *Collection) InsertOne(ctx context.Context, document interface{}, // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/insert/. func (coll *Collection) InsertMany( ctx context.Context, - documents interface{}, + documents any, opts ...options.Lister[options.InsertManyOptions], ) (*InsertManyResult, error) { dv := reflect.ValueOf(documents) if dv.Kind() != reflect.Slice { - return nil, ErrNotSlice + return nil, fmt.Errorf("invalid documents: %w", ErrNotSlice) } if dv.Len() == 0 { - return nil, ErrEmptySlice + return nil, fmt.Errorf("invalid documents: %w", ErrEmptySlice) } - docSlice := make([]interface{}, 0, dv.Len()) + docSlice := make([]any, 0, dv.Len()) for i := 0; i < dv.Len(); i++ { docSlice = append(docSlice, dv.Index(i).Interface()) } @@ -451,7 +469,7 @@ func (coll *Collection) InsertMany( func (coll *Collection) delete( ctx context.Context, - filter interface{}, + filter any, deleteOne bool, expectedRr returnResult, args *options.DeleteManyOptions, @@ -534,6 +552,11 @@ func (coll *Collection) delete( } op = op.Let(let) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } // deleteMany cannot be retried retryMode := driver.RetryNone @@ -563,7 +586,7 @@ func (coll *Collection) delete( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/delete/. func (coll *Collection) DeleteOne( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.DeleteOneOptions], ) (*DeleteResult, error) { args, err := mongoutil.NewOptions[options.DeleteOneOptions](opts...) @@ -575,6 +598,7 @@ func (coll *Collection) DeleteOne( Comment: args.Comment, Hint: args.Hint, Let: args.Let, + Internal: args.Internal, } return coll.delete(ctx, filter, true, rrOne, deleteOptions) @@ -592,7 +616,7 @@ func (coll *Collection) DeleteOne( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/delete/. func (coll *Collection) DeleteMany( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.DeleteManyOptions], ) (*DeleteResult, error) { args, err := mongoutil.NewOptions[options.DeleteManyOptions](opts...) @@ -606,11 +630,11 @@ func (coll *Collection) DeleteMany( func (coll *Collection) updateOrReplace( ctx context.Context, filter bsoncore.Document, - update interface{}, + update any, multi bool, expectedRr returnResult, checkDollarKey bool, - sort interface{}, + sort any, args *options.UpdateManyOptions, ) (*UpdateResult, error) { @@ -681,6 +705,11 @@ func (coll *Collection) updateOrReplace( } op = op.Comment(comment) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone // retryable writes are only enabled updateOne/replaceOne operations if !multi && coll.client.retryWrites { @@ -724,12 +753,12 @@ func (coll *Collection) updateOrReplace( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) UpdateByID( ctx context.Context, - id interface{}, - update interface{}, + id any, + update any, opts ...options.Lister[options.UpdateOneOptions], ) (*UpdateResult, error) { if id == nil { - return nil, ErrNilValue + return nil, fmt.Errorf("invalid id: %w", ErrNilValue) } return coll.UpdateOne(ctx, bson.D{{"_id", id}}, update, opts...) } @@ -750,8 +779,8 @@ func (coll *Collection) UpdateByID( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) UpdateOne( ctx context.Context, - filter interface{}, - update interface{}, + filter any, + update any, opts ...options.Lister[options.UpdateOneOptions], ) (*UpdateResult, error) { if ctx == nil { @@ -775,6 +804,7 @@ func (coll *Collection) UpdateOne( Hint: args.Hint, Upsert: args.Upsert, Let: args.Let, + Internal: args.Internal, } return coll.updateOrReplace(ctx, f, update, false, rrOne, true, args.Sort, updateOptions) @@ -795,8 +825,8 @@ func (coll *Collection) UpdateOne( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) UpdateMany( ctx context.Context, - filter interface{}, - update interface{}, + filter any, + update any, opts ...options.Lister[options.UpdateManyOptions], ) (*UpdateResult, error) { if ctx == nil { @@ -831,8 +861,8 @@ func (coll *Collection) UpdateMany( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/update/. func (coll *Collection) ReplaceOne( ctx context.Context, - filter interface{}, - replacement interface{}, + filter any, + replacement any, opts ...options.Lister[options.ReplaceOptions], ) (*UpdateResult, error) { if ctx == nil { @@ -865,6 +895,7 @@ func (coll *Collection) ReplaceOne( Hint: args.Hint, Let: args.Let, Comment: args.Comment, + Internal: args.Internal, } return coll.updateOrReplace(ctx, f, r, false, rrOne, false, args.Sort, updateOptions) @@ -883,7 +914,7 @@ func (coll *Collection) ReplaceOne( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/aggregate/. func (coll *Collection) Aggregate( ctx context.Context, - pipeline interface{}, + pipeline any, opts ...options.Lister[options.AggregateOptions], ) (*Cursor, error) { a := aggregateParams{ @@ -1036,6 +1067,11 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption } op.CustomOptions(customOptions) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if a.retryRead && !hasOutputStage { @@ -1045,18 +1081,25 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption err = op.Execute(a.ctx) if err != nil { - if wce, ok := err.(driver.WriteCommandError); ok && wce.WriteConcernError != nil { + var wce driver.WriteCommandError + if errors.As(err, &wce) && wce.WriteConcernError != nil { return nil, *convertDriverWriteConcernError(wce.WriteConcernError) } - return nil, replaceErrors(err) + return nil, wrapErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { - return nil, replaceErrors(err) + return nil, wrapErrors(err) } - cursor, err := newCursorWithSession(bc, a.client.bsonOpts, a.registry, sess) - return cursor, replaceErrors(err) + cursor, err := newCursorWithSession(bc, a.client.bsonOpts, a.registry, sess, + + // The only way the server will return a tailable/awaitData cursor for an + // aggregate operation is for the first stage in the pipeline to + // be $changeStream, this is the only time maxAwaitTimeMS should be applied. + // For this reason, we pass the client timeout to the cursor. + withCursorOptionClientTimeout(a.client.timeout)) + return cursor, wrapErrors(err) } // CountDocuments returns the number of documents in the collection. For a fast count of the documents in the @@ -1067,7 +1110,7 @@ func aggregate(a aggregateParams, opts ...options.Lister[options.AggregateOption // result in a full collection scan. // // The opts parameter can be used to specify options for the operation (see the options.CountOptions documentation). -func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, +func (coll *Collection) CountDocuments(ctx context.Context, filter any, opts ...options.Lister[options.CountOptions]) (int64, error) { if ctx == nil { ctx = context.Background() @@ -1123,6 +1166,11 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, } op.Hint(hintVal) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if coll.client.retryReads { retry = driver.RetryOncePerCommand @@ -1131,7 +1179,7 @@ func (coll *Collection) CountDocuments(ctx context.Context, filter interface{}, err = op.Execute(ctx) if err != nil { - return 0, replaceErrors(err) + return 0, wrapErrors(err) } batch := op.ResultCursorResponse().FirstBatch @@ -1204,6 +1252,11 @@ func (coll *Collection) EstimatedDocumentCount( } op = op.Comment(comment) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if coll.client.retryReads { @@ -1212,7 +1265,7 @@ func (coll *Collection) EstimatedDocumentCount( op.Retry(retry) err = op.Execute(ctx) - return op.Result().N, replaceErrors(err) + return op.Result().N, wrapErrors(err) } // Distinct executes a distinct command to find the unique values for a specified field in the collection. @@ -1228,7 +1281,7 @@ func (coll *Collection) EstimatedDocumentCount( func (coll *Collection) Distinct( ctx context.Context, fieldName string, - filter interface{}, + filter any, opts ...options.Lister[options.DistinctOptions], ) *DistinctResult { if ctx == nil { @@ -1293,6 +1346,11 @@ func (coll *Collection) Distinct( } op.Hint(hint) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if coll.client.retryReads { retry = driver.RetryOncePerCommand @@ -1301,7 +1359,7 @@ func (coll *Collection) Distinct( err = op.Execute(ctx) if err != nil { - return &DistinctResult{err: replaceErrors(err)} + return &DistinctResult{err: wrapErrors(err)} } arr, ok := op.Result().Values.ArrayOK() @@ -1326,7 +1384,7 @@ func (coll *Collection) Distinct( // The opts parameter can be used to specify options for the operation (see the options.FindOptions documentation). // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/find/. -func (coll *Collection) Find(ctx context.Context, filter interface{}, +func (coll *Collection) Find(ctx context.Context, filter any, opts ...options.Lister[options.FindOptions]) (*Cursor, error) { args, err := mongoutil.NewOptions(opts...) if err != nil { @@ -1342,7 +1400,7 @@ func (coll *Collection) Find(ctx context.Context, filter interface{}, func (coll *Collection) find( ctx context.Context, - filter interface{}, + filter any, omitMaxTimeMS bool, args *options.FindOptions, ) (cur *Cursor, err error) { @@ -1496,6 +1554,11 @@ func (coll *Collection) find( } op.Sort(sort) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if coll.client.retryReads { retry = driver.RetryOncePerCommand @@ -1503,14 +1566,16 @@ func (coll *Collection) find( op = op.Retry(retry) if err = op.Execute(ctx); err != nil { - return nil, replaceErrors(err) + return nil, wrapErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { - return nil, replaceErrors(err) + return nil, wrapErrors(err) } - return newCursorWithSession(bc, coll.bsonOpts, coll.registry, sess) + + return newCursorWithSession(bc, coll.bsonOpts, coll.registry, sess, + withCursorOptionClientTimeout(coll.client.timeout)) } func newFindArgsFromFindOneArgs(args *options.FindOneOptions) *options.FindOptions { @@ -1529,6 +1594,7 @@ func newFindArgsFromFindOneArgs(args *options.FindOneOptions) *options.FindOptio v.ShowRecordID = args.ShowRecordID v.Skip = args.Skip v.Sort = args.Sort + v.Internal = args.Internal } return v } @@ -1542,7 +1608,7 @@ func newFindArgsFromFindOneArgs(args *options.FindOneOptions) *options.FindOptio // The opts parameter can be used to specify options for this operation (see the options.FindOneOptions documentation). // // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/find/. -func (coll *Collection) FindOne(ctx context.Context, filter interface{}, +func (coll *Collection) FindOne(ctx context.Context, filter any, opts ...options.Lister[options.FindOneOptions]) *SingleResult { if ctx == nil { @@ -1559,7 +1625,7 @@ func (coll *Collection) FindOne(ctx context.Context, filter interface{}, cur: cursor, bsonOpts: coll.bsonOpts, reg: coll.registry, - err: replaceErrors(err), + err: wrapErrors(err), } } @@ -1633,7 +1699,7 @@ func (coll *Collection) findAndModify(ctx context.Context, op *operation.FindAnd // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/findAndModify/. func (coll *Collection) FindOneAndDelete( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.FindOneAndDeleteOptions]) *SingleResult { f, err := marshal(filter, coll.bsonOpts, coll.registry) @@ -1691,6 +1757,11 @@ func (coll *Collection) FindOneAndDelete( } op = op.Let(let) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } return coll.findAndModify(ctx, op) } @@ -1711,8 +1782,8 @@ func (coll *Collection) FindOneAndDelete( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/findAndModify/. func (coll *Collection) FindOneAndReplace( ctx context.Context, - filter interface{}, - replacement interface{}, + filter any, + replacement any, opts ...options.Lister[options.FindOneAndReplaceOptions], ) *SingleResult { @@ -1788,6 +1859,11 @@ func (coll *Collection) FindOneAndReplace( } op = op.Let(let) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } return coll.findAndModify(ctx, op) } @@ -1809,8 +1885,8 @@ func (coll *Collection) FindOneAndReplace( // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/findAndModify/. func (coll *Collection) FindOneAndUpdate( ctx context.Context, - filter interface{}, - update interface{}, + filter any, + update any, opts ...options.Lister[options.FindOneAndUpdateOptions]) *SingleResult { if ctx == nil { @@ -1897,6 +1973,11 @@ func (coll *Collection) FindOneAndUpdate( } op = op.Let(let) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } return coll.findAndModify(ctx, op) } @@ -1914,7 +1995,7 @@ func (coll *Collection) FindOneAndUpdate( // // The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptions // documentation). -func (coll *Collection) Watch(ctx context.Context, pipeline interface{}, +func (coll *Collection) Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { csConfig := changeStreamConfig{ @@ -1975,7 +2056,7 @@ func (coll *Collection) Drop(ctx context.Context, opts ...options.Lister[options } // dropEncryptedCollection drops a collection with EncryptedFields. -func (coll *Collection) dropEncryptedCollection(ctx context.Context, ef interface{}) error { +func (coll *Collection) dropEncryptedCollection(ctx context.Context, ef any) error { efBSON, err := marshal(ef, coll.bsonOpts, coll.registry) if err != nil { return fmt.Errorf("error transforming document: %w", err) @@ -2041,9 +2122,9 @@ func (coll *Collection) drop(ctx context.Context) error { err = op.Execute(ctx) // ignore namespace not found errors - driverErr, ok := err.(driver.Error) - if !ok || (ok && !driverErr.NamespaceNotFound()) { - return replaceErrors(err) + var driverErr driver.Error + if !errors.As(err, &driverErr) || !driverErr.NamespaceNotFound() { + return wrapErrors(err) } return nil } @@ -2168,7 +2249,7 @@ func makeOutputAggregateSelector( // isUnorderedMap returns true if val is a map with more than 1 element. It is typically used to // check for unordered Go values that are used in nested command documents where different field // orders mean different things. Examples are the "sort" and "hint" fields. -func isUnorderedMap(val interface{}) bool { +func isUnorderedMap(val any) bool { refValue := reflect.ValueOf(val) return refValue.Kind() == reflect.Map && refValue.Len() > 1 } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go index 5134c4fe..bb77f4a2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/cursor.go @@ -16,6 +16,7 @@ import ( "time" "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/internal/mongoutil" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" @@ -30,22 +31,41 @@ type Cursor struct { // to Next or TryNext. If continued access is required, a copy must be made. Current bson.Raw - bc batchCursor - batch *bsoncore.Iterator - batchLength int - bsonOpts *options.BSONOptions - registry *bson.Registry - clientSession *session.Client + bc batchCursor + batch *bsoncore.Iterator + batchLength int + bsonOpts *options.BSONOptions + registry *bson.Registry + clientSession *session.Client + clientTimeout time.Duration + hasClientTimeout bool err error } +type cursorOptions struct { + clientTimeout time.Duration + hasClientTimeout bool +} + +type cursorOption func(*cursorOptions) + +func withCursorOptionClientTimeout(dur *time.Duration) cursorOption { + return func(opts *cursorOptions) { + if dur != nil && *dur > 0 { + opts.clientTimeout = *dur + opts.hasClientTimeout = true + } + } +} + func newCursor( bc batchCursor, bsonOpts *options.BSONOptions, registry *bson.Registry, + opts ...cursorOption, ) (*Cursor, error) { - return newCursorWithSession(bc, bsonOpts, registry, nil) + return newCursorWithSession(bc, bsonOpts, registry, nil, opts...) } func newCursorWithSession( @@ -53,6 +73,7 @@ func newCursorWithSession( bsonOpts *options.BSONOptions, registry *bson.Registry, clientSession *session.Client, + opts ...cursorOption, ) (*Cursor, error) { if registry == nil { registry = defaultRegistry @@ -60,11 +81,19 @@ func newCursorWithSession( if bc == nil { return nil, errors.New("batch cursor must not be nil") } + + cursorOpts := &cursorOptions{} + for _, opt := range opts { + opt(cursorOpts) + } + c := &Cursor{ - bc: bc, - bsonOpts: bsonOpts, - registry: registry, - clientSession: clientSession, + bc: bc, + bsonOpts: bsonOpts, + registry: registry, + clientSession: clientSession, + clientTimeout: cursorOpts.clientTimeout, + hasClientTimeout: cursorOpts.hasClientTimeout, } if bc.ID() == 0 { c.closeImplicitSession() @@ -85,7 +114,7 @@ func newEmptyCursor() *Cursor { // bson.NewRegistry() will be used. // // The documents parameter must be a slice of documents. The slice may be nil or empty, but all elements must be non-nil. -func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registry *bson.Registry) (*Cursor, error) { +func NewCursorFromDocuments(documents []any, preloadedErr error, registry *bson.Registry) (*Cursor, error) { if registry == nil { registry = defaultRegistry } @@ -97,7 +126,7 @@ func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registr for i, doc := range documents { switch t := doc.(type) { case nil: - return nil, ErrNilDocument + return nil, fmt.Errorf("invalid document at index %d: %w", i, ErrNilDocument) case []byte: // Slight optimization so we'll just use MarshalBSON and not go through the codec machinery. doc = bson.Raw(t) @@ -139,11 +168,17 @@ func NewCursorFromDocuments(documents []interface{}, preloadedErr error, registr // ID returns the ID of this cursor, or 0 if the cursor has been closed or exhausted. func (c *Cursor) ID() int64 { return c.bc.ID() } -// Next gets the next document for this cursor. It returns true if there were no errors and the cursor has not been -// exhausted. +// Next gets the next document for this cursor. It returns true if there were no +// errors and the cursor has not been exhausted. // -// Next blocks until a document is available or an error occurs. If the context expires, the cursor's error will -// be set to ctx.Err(). In case of an error, Next will return false. +// Next blocks until a document is available or an error occurs. If the context +// expires, the cursor's error will be set to ctx.Err(). In case of an error, +// Next will return false. +// +// If MaxAwaitTime is set, the operation will be bound by the Context's +// deadline. If the context does not have a deadline, the operation will be +// bound by the client-level timeout, if one is set. If MaxAwaitTime is greater +// than the user-provided timeout, Next will return false. // // If Next returns false, subsequent calls will also return false. func (c *Cursor) Next(ctx context.Context) bool { @@ -175,6 +210,41 @@ func (c *Cursor) next(ctx context.Context, nonBlocking bool) bool { if ctx == nil { ctx = context.Background() } + + // If the context does not have a deadline we defer to a client-level timeout, + // if one is set. + if _, ok := ctx.Deadline(); !ok && c.hasClientTimeout { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, c.clientTimeout) + + defer cancel() + } + + // To avoid unnecessary socket timeouts, we attempt to short-circuit tailable + // awaitData "getMore" operations by ensuring that the maxAwaitTimeMS is less + // than the operation timeout. + // + // The specifications assume that drivers iteratively apply the timeout + // provided at the constructor level (e.g., (*collection).Find) for tailable + // awaitData cursors: + // + // If set, drivers MUST apply the timeoutMS option to the initial aggregate + // operation. Drivers MUST also apply the original timeoutMS value to each + // next call on the change stream but MUST NOT use it to derive a maxTimeMS + // field for getMore commands. + // + // The Go Driver might decide to support the above behavior with DRIVERS-2722. + // The principal concern is that it would be unexpected for users to apply an + // operation-level timeout via contexts to a constructor and then that timeout + // later be applied while working with a resulting cursor. Instead, it is more + // idiomatic to apply the timeout to the context passed to Next or TryNext. + maxAwaitTime := c.bc.MaxAwaitTime() // + if maxAwaitTime != nil && !nonBlocking && !mongoutil.TimeoutWithinContext(ctx, *maxAwaitTime) { + c.err = fmt.Errorf("MaxAwaitTime must be less than the operation timeout") + + return false + } + val, err := c.batch.Next() switch { case err == nil: @@ -194,7 +264,7 @@ func (c *Cursor) next(ctx context.Context, nonBlocking bool) bool { // 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 = replaceErrors(c.bc.Err()) + c.err = wrapErrors(c.bc.Err()) if c.err != nil { return false } @@ -276,7 +346,7 @@ func getDecoder( // Decode will unmarshal the current document into val and return any errors from the unmarshalling process without any // modification. If val is nil or is a typed nil, an error will be returned. -func (c *Cursor) Decode(val interface{}) error { +func (c *Cursor) Decode(val any) error { dec := getDecoder(c.Current, c.bsonOpts, c.registry) return dec.Decode(val) @@ -289,7 +359,7 @@ func (c *Cursor) Err() error { return c.err } // the first call, any subsequent calls will not change the state. func (c *Cursor) Close(ctx context.Context) error { defer c.closeImplicitSession() - return replaceErrors(c.bc.Close(ctx)) + return wrapErrors(c.bc.Close(ctx)) } // All iterates the cursor and decodes each document into results. The results parameter must be a pointer to a slice. @@ -298,7 +368,7 @@ func (c *Cursor) Close(ctx context.Context) error { // cursor has been iterated, any previously iterated documents will not be included in results. // // This method requires driver version >= 1.1.0. -func (c *Cursor) All(ctx context.Context, results interface{}) error { +func (c *Cursor) All(ctx context.Context, results any) error { resultsVal := reflect.ValueOf(results) if resultsVal.Kind() != reflect.Ptr { return fmt.Errorf("results argument must be a pointer to a slice, but was a %s", resultsVal.Kind()) @@ -336,7 +406,7 @@ func (c *Cursor) All(ctx context.Context, results interface{}) error { batch = c.bc.Batch() } - if err = replaceErrors(c.bc.Err()); err != nil { + if err = wrapErrors(c.bc.Err()); err != nil { return err } @@ -407,7 +477,7 @@ func (c *Cursor) SetMaxAwaitTime(dur time.Duration) { // SetComment will set a user-configurable comment that can be used to identify // the operation in server logs. -func (c *Cursor) SetComment(comment interface{}) { +func (c *Cursor) SetComment(comment any) { c.bc.SetComment(comment) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go index 414971c8..e42097bb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/database.go @@ -16,6 +16,7 @@ import ( "go.mongodb.org/mongo-driver/v2/internal/csfle" "go.mongodb.org/mongo-driver/v2/internal/csot" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/mongo/readconcern" @@ -110,13 +111,15 @@ func (db *Database) Name() string { return db.name } -// Collection gets a handle for a collection with the given name configured with the given CollectionOptions. +// Collection returns a handle for a collection with the given name and options. +// +// If the collection does not exist on the server, it will be created when a +// write operation is performed. func (db *Database) Collection(name string, opts ...options.Lister[options.CollectionOptions]) *Collection { return newCollection(db, name, opts...) } -// Aggregate executes an aggregate command the database. This requires MongoDB version >= 3.6 and driver version >= -// 1.1.0. +// Aggregate executes an aggregate command the database. // // The pipeline parameter must be a slice of documents, each representing an aggregation stage. The pipeline // cannot be nil but can be empty. The stage documents must all be non-nil. For a pipeline of bson.D documents, the @@ -129,7 +132,7 @@ func (db *Database) Collection(name string, opts ...options.Lister[options.Colle // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/aggregate/. func (db *Database) Aggregate( ctx context.Context, - pipeline interface{}, + pipeline any, opts ...options.Lister[options.AggregateOptions], ) (*Cursor, error) { a := aggregateParams{ @@ -151,7 +154,7 @@ func (db *Database) Aggregate( func (db *Database) processRunCommand( ctx context.Context, - cmd interface{}, + cmd any, cursorCommand bool, opts ...options.Lister[options.RunCmdOptions], ) (*operation.Command, *session.Client, error) { @@ -234,7 +237,7 @@ func (db *Database) processRunCommand( // - maxTimeMS when Timeout is set on the Client func (db *Database) RunCommand( ctx context.Context, - runCommand interface{}, + runCommand any, opts ...options.Lister[options.RunCmdOptions], ) *SingleResult { if ctx == nil { @@ -276,7 +279,7 @@ func (db *Database) RunCommand( // - maxTimeMS when Timeout is set on the Client func (db *Database) RunCommandCursor( ctx context.Context, - runCommand interface{}, + runCommand any, opts ...options.Lister[options.RunCmdOptions], ) (*Cursor, error) { if ctx == nil { @@ -286,7 +289,7 @@ func (db *Database) RunCommandCursor( op, sess, err := db.processRunCommand(ctx, runCommand, true, opts...) if err != nil { closeImplicitSession(sess) - return nil, replaceErrors(err) + return nil, wrapErrors(err) } if err = op.Execute(ctx); err != nil { @@ -295,16 +298,17 @@ func (db *Database) RunCommandCursor( return nil, errors.New( "database response does not contain a cursor; try using RunCommand instead") } - return nil, replaceErrors(err) + return nil, wrapErrors(err) } bc, err := op.ResultCursor() if err != nil { closeImplicitSession(sess) - return nil, replaceErrors(err) + return nil, wrapErrors(err) } - cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess) - return cursor, replaceErrors(err) + cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess, + withCursorOptionClientTimeout(db.client.timeout)) + return cursor, wrapErrors(err) } // Drop drops the database on the server. This method ignores "namespace not found" errors so it is safe to drop @@ -343,9 +347,9 @@ func (db *Database) Drop(ctx context.Context) error { err = op.Execute(ctx) - driverErr, ok := err.(driver.Error) - if err != nil && (!ok || !driverErr.NamespaceNotFound()) { - return replaceErrors(err) + var driverErr driver.Error + if err != nil && (!errors.As(err, &driverErr) || !driverErr.NamespaceNotFound()) { + return wrapErrors(err) } return nil } @@ -363,7 +367,7 @@ func (db *Database) Drop(ctx context.Context) error { // For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/listCollections/. func (db *Database) ListCollectionSpecifications( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.ListCollectionsOptions], ) ([]CollectionSpecification, error) { cursor, err := db.ListCollections(ctx, filter, opts...) @@ -426,7 +430,7 @@ func (db *Database) ListCollectionSpecifications( // MongoDB version 2.6. func (db *Database) ListCollections( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.ListCollectionsOptions], ) (*Cursor, error) { if ctx == nil { @@ -485,6 +489,11 @@ func (db *Database) ListCollections( if args.AuthorizedCollections != nil { op = op.AuthorizedCollections(*args.AuthorizedCollections) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if db.client.retryReads { @@ -495,16 +504,17 @@ func (db *Database) ListCollections( err = op.Execute(ctx) if err != nil { closeImplicitSession(sess) - return nil, replaceErrors(err) + return nil, wrapErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { closeImplicitSession(sess) - return nil, replaceErrors(err) + return nil, wrapErrors(err) } - cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess) - return cursor, replaceErrors(err) + cursor, err := newCursorWithSession(bc, db.bsonOpts, db.registry, sess, + withCursorOptionClientTimeout(db.client.timeout)) + return cursor, wrapErrors(err) } // ListCollectionNames executes a listCollections command and returns a slice containing the names of the collections @@ -523,7 +533,7 @@ func (db *Database) ListCollections( // MongoDB version 2.6. func (db *Database) ListCollectionNames( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.ListCollectionsOptions], ) ([]string, error) { opts = append(opts, options.ListCollections().SetNameOnly(true)) @@ -567,7 +577,7 @@ func (db *Database) ListCollectionNames( // // The opts parameter can be used to specify options for change stream creation (see the options.ChangeStreamOptions // documentation). -func (db *Database) Watch(ctx context.Context, pipeline interface{}, +func (db *Database) Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*ChangeStream, error) { csConfig := changeStreamConfig{ @@ -583,14 +593,15 @@ func (db *Database) Watch(ctx context.Context, pipeline interface{}, return newChangeStream(ctx, csConfig, pipeline, opts...) } -// CreateCollection executes a create command to explicitly create a new collection with the specified name on the -// server. If the collection being created already exists, this method will return a mongo.CommandError. This method -// requires driver version 1.4.0 or higher. +// CreateCollection creates a new collection on the server with the specified +// name and options. // -// The opts parameter can be used to specify options for the operation (see the options.CreateCollectionOptions -// documentation). +// MongoDB versions < 7.0 will return an error if the collection already exists. +// MongoDB versions >= 7.0 will not return an error if an existing collection +// created with the same name and options already exists. // -// For more information about the command, see https://www.mongodb.com/docs/manual/reference/command/create/. +// For more information about the command, see +// https://www.mongodb.com/docs/manual/reference/command/create/. func (db *Database) CreateCollection(ctx context.Context, name string, opts ...options.Lister[options.CreateCollectionOptions]) error { args, err := mongoutil.NewOptions(opts...) if err != nil { @@ -613,7 +624,7 @@ func (db *Database) CreateCollection(ctx context.Context, name string, opts ...o // getEncryptedFieldsFromServer tries to get an "encryptedFields" document associated with collectionName by running the "listCollections" command. // Returns nil and no error if the listCollections command succeeds, but "encryptedFields" is not present. -func (db *Database) getEncryptedFieldsFromServer(ctx context.Context, collectionName string) (interface{}, error) { +func (db *Database) getEncryptedFieldsFromServer(ctx context.Context, collectionName string) (any, error) { // Check if collection has an EncryptedFields configured server-side. collSpecs, err := db.ListCollectionSpecifications(ctx, bson.D{{"name", collectionName}}) if err != nil { @@ -643,7 +654,7 @@ func (db *Database) getEncryptedFieldsFromServer(ctx context.Context, collection // getEncryptedFieldsFromMap tries to get an "encryptedFields" document associated with collectionName by checking the client EncryptedFieldsMap. // Returns nil and no error if an EncryptedFieldsMap is not configured, or does not contain an entry for collectionName. -func (db *Database) getEncryptedFieldsFromMap(collectionName string) interface{} { +func (db *Database) getEncryptedFieldsFromMap(collectionName string) any { // Check the EncryptedFieldsMap efMap := db.client.encryptedFieldsMap if efMap == nil { @@ -663,7 +674,7 @@ func (db *Database) getEncryptedFieldsFromMap(collectionName string) interface{} func (db *Database) createCollectionWithEncryptedFields( ctx context.Context, name string, - ef interface{}, + ef any, opts ...options.Lister[options.CreateCollectionOptions], ) error { efBSON, err := marshal(ef, db.bsonOpts, db.registry) @@ -873,20 +884,21 @@ func (db *Database) createCollectionOperation( return op, nil } -// CreateView executes a create command to explicitly create a view on the server. See -// https://www.mongodb.com/docs/manual/core/views/ for more information about views. This method requires driver version >= -// 1.4.0 and MongoDB version >= 3.4. -// -// The viewName parameter specifies the name of the view to create. +// CreateView creates a view on the server. // -// # The viewOn parameter specifies the name of the collection or view on which this view will be created +// The viewName parameter specifies the name of the view to create. The viewOn +// parameter specifies the name of the collection or view on which this view +// will be created. The pipeline parameter specifies an aggregation pipeline +// that will be exececuted against the source collection or view to create this +// view. // -// The pipeline parameter specifies an aggregation pipeline that will be exececuted against the source collection or -// view to create this view. +// MongoDB versions < 7.0 will return an error if the view already exists. +// MongoDB versions >= 7.0 will not return an error if an existing view created +// with the same name and options already exists. // -// The opts parameter can be used to specify options for the operation (see the options.CreateViewOptions -// documentation). -func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline interface{}, +// See https://www.mongodb.com/docs/manual/core/views/ for more information +// about views. +func (db *Database) CreateView(ctx context.Context, viewName, viewOn string, pipeline any, opts ...options.Lister[options.CreateViewOptions]) error { pipelineArray, _, err := marshalAggregatePipeline(pipeline, db.bsonOpts, db.registry) @@ -940,7 +952,7 @@ func (db *Database) executeCreateOperation(ctx context.Context, op *operation.Cr Deployment(db.client.deployment). Crypt(db.client.cryptFLE) - return replaceErrors(op.Execute(ctx)) + return wrapErrors(op.Execute(ctx)) } // GridFSBucket is used to construct a GridFS bucket which can be used as a diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go index 21e06b06..3756d58f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/doc.go @@ -73,8 +73,8 @@ // 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{}. +// All Client, Collection, and Database methods that take parameters of type any +// will return ErrNilDocument if nil is passed in for an any. // // Additional examples can be found under the examples directory in the driver's repository and // on the MongoDB website. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go index 07d713fd..234445ab 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/errors.go @@ -12,6 +12,7 @@ import ( "errors" "fmt" "net" + "reflect" "strings" "go.mongodb.org/mongo-driver/v2/bson" @@ -24,17 +25,35 @@ import ( // ErrClientDisconnected is returned when disconnected Client is used to run an operation. var ErrClientDisconnected = errors.New("client is disconnected") +// InvalidArgumentError wraps an invalid argument error. +type InvalidArgumentError struct { + wrapped error +} + +// Error implements the error interface. +func (e InvalidArgumentError) Error() string { + return e.wrapped.Error() +} + +// Unwrap returns the underlying error. +func (e InvalidArgumentError) Unwrap() error { + return e.wrapped +} + +// ErrMultipleIndexDrop is returned if multiple indexes would be dropped from a call to IndexView.DropOne. +var ErrMultipleIndexDrop error = InvalidArgumentError{errors.New("multiple indexes would be dropped")} + // ErrNilDocument is returned when a nil document is passed to a CRUD method. -var ErrNilDocument = errors.New("document is nil") +var ErrNilDocument error = InvalidArgumentError{errors.New("document is nil")} // ErrNilValue is returned when a nil value is passed to a CRUD method. -var ErrNilValue = errors.New("value is nil") +var ErrNilValue error = InvalidArgumentError{errors.New("value is nil")} // ErrEmptySlice is returned when an empty slice is passed to a CRUD method that requires a non-empty slice. -var ErrEmptySlice = errors.New("must provide at least one element in input slice") +var ErrEmptySlice error = InvalidArgumentError{errors.New("must provide at least one element in input slice")} // ErrNotSlice is returned when a type other than slice is passed to InsertMany. -var ErrNotSlice = errors.New("must provide a non-empty slice") +var ErrNotSlice error = InvalidArgumentError{errors.New("must provide a non-empty slice")} // ErrMapForOrderedArgument is returned when a map with multiple keys is passed to a CRUD method for an ordered parameter type ErrMapForOrderedArgument struct { @@ -46,7 +65,11 @@ func (e ErrMapForOrderedArgument) Error() string { return fmt.Sprintf("multi-key map passed in for ordered parameter %v", e.ParamName) } -func replaceErrors(err error) error { +// wrapErrors wraps error types and values that are defined in "internal" and +// "x" packages with error types and values that are defined in this package. +// That allows users to inspect the errors using errors.Is/errors.As without +// relying on "internal" or "x" packages. +func wrapErrors(err error) error { // Return nil when err is nil to avoid costly reflection logic below. if err == nil { return nil @@ -57,29 +80,45 @@ func replaceErrors(err error) error { // ignored. For non-DDL write commands (insert, update, etc), acknowledgement // should be be propagated at the result-level: e.g., // SingleResult.Acknowledged. - if err == driver.ErrUnacknowledgedWrite { + if errors.Is(err, driver.ErrUnacknowledgedWrite) { return nil } - if errors.Is(err, topology.ErrTopologyClosed) { return ErrClientDisconnected } - if de, ok := err.(driver.Error); ok { + + var de driver.Error + if errors.As(err, &de) { return CommandError{ Code: de.Code, Message: de.Message, Labels: de.Labels, Name: de.Name, - Wrapped: de.Wrapped, + Wrapped: err, Raw: bson.Raw(de.Raw), + + // Set wrappedMsgOnly=true here so that the Code and Message are not + // repeated multiple times in the error string. We expect that the + // wrapped driver.Error already contains that info in the error + // string. + wrappedMsgOnly: true, } } - if qe, ok := err.(driver.QueryFailureError); ok { + + var qe driver.QueryFailureError + if errors.As(err, &qe) { // qe.Message is "command failure" ce := CommandError{ Name: qe.Message, - Wrapped: qe.Wrapped, + Wrapped: err, Raw: bson.Raw(qe.Response), + + // Don't set wrappedMsgOnly=true here because the code below adds + // additional error context that is not provided by the + // driver.QueryFailureError. Additionally, driver.QueryFailureError + // is only returned when parsing OP_QUERY replies (OP_REPLY), so + // it's unlikely this block will ever be run now that MongoDB 3.6 is + // no longer supported. } dollarErr, err := qe.Response.LookupErr("$err") @@ -93,18 +132,37 @@ func replaceErrors(err error) error { return ce } - if me, ok := err.(mongocrypt.Error); ok { - return MongocryptError{Code: me.Code, Message: me.Message} + + var me mongocrypt.Error + if errors.As(err, &me) { + return MongocryptError{ + Code: me.Code, + Message: me.Message, + wrapped: err, + + // Set wrappedMsgOnly=true here so that the Code and Message are not + // repeated multiple times in the error string. We expect that the + // wrapped mongocrypt.Error already contains that info in the error + // string. + wrappedMsgOnly: true, + } } if errors.Is(err, codecutil.ErrNilValue) { return ErrNilValue } - if marshalErr, ok := err.(codecutil.MarshalError); ok { + var marshalErr codecutil.MarshalError + if errors.As(err, &marshalErr) { return MarshalError{ Value: marshalErr.Value, - Err: marshalErr.Err, + Err: err, + + // Set wrappedMsgOnly=true here so that the Value is not repeated + // multiple times in the error string. We expect that the wrapped + // codecutil.MarshalError already contains that info in the error + // string. + wrappedMsgOnly: true, } } @@ -177,17 +235,67 @@ func IsNetworkError(err error) bool { return errorHasLabel(err, "NetworkError") } +// MarshalError is returned when attempting to marshal a value into a document +// results in an error. +type MarshalError struct { + Value any + Err error + + // If wrappedMsgOnly is true, Error() only returns the error message from + // the "Err" error. + // + // This is typically only set by the wrapErrors function, which uses + // MarshalError to wrap codecutil.MarshalError, allowing users to access the + // "Value" from the underlying error but preventing duplication in the error + // string. + wrappedMsgOnly bool +} + +// Error implements the error interface. +func (me MarshalError) Error() string { + // If the MarshalError was created with wrappedMsgOnly=true, only return the + // error from the wrapped error. See the MarshalError.wrappedMsgOnly docs + // for more info. + if me.wrappedMsgOnly { + return me.Err.Error() + } + + return fmt.Sprintf("cannot marshal type %s to a BSON Document: %v", reflect.TypeOf(me.Value), me.Err) +} + +func (me MarshalError) Unwrap() error { return me.Err } + // MongocryptError represents an libmongocrypt error during in-use encryption. type MongocryptError struct { Code int32 Message string + wrapped error + + // If wrappedMsgOnly is true, Error() only returns the error message from + // the "wrapped" error. + // + // This is typically only set by the wrapErrors function, which uses + // MarshalError to wrap mongocrypt.Error, allowing users to access the + // "Code" and "Message" from the underlying error but preventing duplication + // in the error string. + wrappedMsgOnly bool } // Error implements the error interface. func (m MongocryptError) Error() string { + // If the MongocryptError was created with wrappedMsgOnly=true, only return + // the error from the wrapped error. See the MongocryptError.wrappedMsgOnly + // docs for more info. + if m.wrappedMsgOnly { + return m.wrapped.Error() + } + return fmt.Sprintf("mongocrypt error %d: %v", m.Code, m.Message) } +// Unwrap returns the underlying error. +func (m MongocryptError) Unwrap() error { return m.wrapped } + // EncryptionKeyVaultError represents an error while communicating with the key vault collection during in-use // encryption. type EncryptionKeyVaultError struct { @@ -271,14 +379,38 @@ type CommandError struct { Name string // A human-readable name corresponding to the error code Wrapped error // The underlying error, if one exists. Raw bson.Raw // The original server response containing the error. + + // If wrappedMsgOnly is true, Error() only returns the error message from + // the "Wrapped" error. + // + // This is typically only set by the wrapErrors function, which uses + // CommandError to wrap driver.Error, allowing users to access the "Code", + // "Message", "Labels", "Name", and "Raw" from the underlying error but + // preventing duplication in the error string. + wrappedMsgOnly bool } // Error implements the error interface. func (e CommandError) Error() string { + // If the CommandError was created with wrappedMsgOnly=true, only return the + // error from the wrapped error. See the CommandError.wrappedMsgOnly docs + // for more info. + if e.wrappedMsgOnly { + return e.Wrapped.Error() + } + + var msg string if e.Name != "" { - return fmt.Sprintf("(%v) %v", e.Name, e.Message) + msg += fmt.Sprintf("(%v)", e.Name) } - return e.Message + if e.Message != "" { + msg += " " + e.Message + } + if e.Wrapped != nil { + msg += ": " + e.Wrapped.Error() + } + + return msg } // Unwrap returns the underlying error. @@ -721,13 +853,13 @@ func processWriteError(err error) (returnResult, error) { // ignored. For non-DDL write commands (insert, update, etc), acknowledgement // should be be propagated at the result-level: e.g., // SingleResult.Acknowledged. - if err == driver.ErrUnacknowledgedWrite { + if errors.Is(err, driver.ErrUnacknowledgedWrite) { return rrAllUnacknowledged, nil } - wce, ok := err.(driver.WriteCommandError) - if !ok { - return rrNone, replaceErrors(err) + var wce driver.WriteCommandError + if !errors.As(err, &wce) { + return rrNone, wrapErrors(err) } return rrMany, WriteException{ diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go index 8bb418ad..74230770 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_bucket.go @@ -80,7 +80,7 @@ func (b *GridFSBucket) OpenUploadStream( // client-level timeout will be used to cap the lifetime of the stream. func (b *GridFSBucket) OpenUploadStreamWithID( ctx context.Context, - fileID interface{}, + fileID any, filename string, opts ...options.Lister[options.GridFSUploadOptions], ) (*GridFSUploadStream, error) { @@ -129,7 +129,7 @@ func (b *GridFSBucket) UploadFromStream( // client-level timeout will be used to cap the lifetime of the stream. func (b *GridFSBucket) UploadFromStreamWithID( ctx context.Context, - fileID interface{}, + fileID any, filename string, source io.Reader, opts ...options.Lister[options.GridFSUploadOptions], @@ -170,7 +170,7 @@ func (b *GridFSBucket) UploadFromStreamWithID( // The context provided to this method controls the entire lifetime of an // upload stream io.Writer. If the context does set a deadline, then the // client-level timeout will be used to cap the lifetime of the stream. -func (b *GridFSBucket) OpenDownloadStream(ctx context.Context, fileID interface{}) (*GridFSDownloadStream, error) { +func (b *GridFSBucket) OpenDownloadStream(ctx context.Context, fileID any) (*GridFSDownloadStream, error) { return b.openDownloadStream(ctx, bson.D{{"_id", fileID}}) } @@ -185,7 +185,7 @@ func (b *GridFSBucket) OpenDownloadStream(ctx context.Context, fileID interface{ // The context provided to this method controls the entire lifetime of an // upload stream io.Writer. If the context does set a deadline, then the // client-level timeout will be used to cap the lifetime of the stream. -func (b *GridFSBucket) DownloadToStream(ctx context.Context, fileID interface{}, stream io.Writer) (int64, error) { +func (b *GridFSBucket) DownloadToStream(ctx context.Context, fileID any, stream io.Writer) (int64, error) { ds, err := b.OpenDownloadStream(ctx, fileID) if err != nil { return 0, err @@ -254,7 +254,7 @@ func (b *GridFSBucket) DownloadToStreamByName( // Delete deletes all chunks and metadata associated with the file with the // given file ID and runs the underlying delete operations with the provided // context. -func (b *GridFSBucket) Delete(ctx context.Context, fileID interface{}) error { +func (b *GridFSBucket) Delete(ctx context.Context, fileID any) error { ctx, cancel := csot.WithTimeout(ctx, b.db.client.timeout) defer cancel() @@ -274,7 +274,7 @@ func (b *GridFSBucket) Delete(ctx context.Context, fileID interface{}) error { // runs the underlying find query with the provided context. func (b *GridFSBucket) Find( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.GridFSFindOptions], ) (*Cursor, error) { args, err := mongoutil.NewOptions[options.GridFSFindOptions](opts...) @@ -306,7 +306,7 @@ func (b *GridFSBucket) Find( } // Rename renames the stored file with the specified file ID. -func (b *GridFSBucket) Rename(ctx context.Context, fileID interface{}, newFilename string) error { +func (b *GridFSBucket) Rename(ctx context.Context, fileID any, newFilename string) error { res, err := b.filesColl.UpdateOne(ctx, bson.D{{"_id", fileID}}, bson.D{{"$set", bson.D{{"filename", newFilename}}}}, @@ -348,7 +348,7 @@ func (b *GridFSBucket) GetChunksCollection() *Collection { func (b *GridFSBucket) openDownloadStream( ctx context.Context, - filter interface{}, + filter any, opts ...options.Lister[options.FindOneOptions], ) (*GridFSDownloadStream, error) { ctx, cancel := csot.WithTimeout(ctx, b.db.client.timeout) @@ -398,12 +398,12 @@ func (b *GridFSBucket) downloadToStream(ds *GridFSDownloadStream, stream io.Writ return copied, ds.Close() } -func (b *GridFSBucket) deleteChunks(ctx context.Context, fileID interface{}) error { +func (b *GridFSBucket) deleteChunks(ctx context.Context, fileID any) error { _, err := b.chunksColl.DeleteMany(ctx, bson.D{{"files_id", fileID}}) return err } -func (b *GridFSBucket) findChunks(ctx context.Context, fileID interface{}) (*Cursor, error) { +func (b *GridFSBucket) findChunks(ctx context.Context, fileID any) (*Cursor, error) { chunksCursor, err := b.chunksColl.Find(ctx, bson.D{{"files_id", fileID}}, options.Find().SetSort(bson.D{{"n", 1}})) // sort by chunk index diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go index 29df84cc..c7967b74 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_download_stream.go @@ -53,7 +53,7 @@ type GridFSDownloadStream struct { type GridFSFile struct { // ID is the file's ID. This will match the file ID specified when uploading the file. If an upload helper that // does not require a file ID was used, this field will be a bson.ObjectID. - ID interface{} + ID any // Length is the length of this file in bytes. Length int64 @@ -73,16 +73,18 @@ type GridFSFile struct { Metadata bson.Raw } +var _ bson.Unmarshaler = &GridFSFile{} + // findFileResponse is a temporary type used to unmarshal documents from the // files collection and can be transformed into a File instance. This type // exists to avoid adding BSON struct tags to the exported File type. type findFileResponse struct { - ID interface{} `bson:"_id"` - Length int64 `bson:"length"` - ChunkSize int32 `bson:"chunkSize"` - UploadDate time.Time `bson:"uploadDate"` - Name string `bson:"filename"` - Metadata bson.Raw `bson:"metadata"` + ID any `bson:"_id"` + Length int64 `bson:"length"` + ChunkSize int32 `bson:"chunkSize"` + UploadDate time.Time `bson:"uploadDate"` + Name string `bson:"filename"` + Metadata bson.Raw `bson:"metadata"` } func newFileFromResponse(resp findFileResponse) *GridFSFile { @@ -96,6 +98,23 @@ func newFileFromResponse(resp findFileResponse) *GridFSFile { } } +// UnmarshalBSON implements the bson.Unmarshaler interface. +func (f *GridFSFile) UnmarshalBSON(data []byte) error { + var temp findFileResponse + if err := bson.Unmarshal(data, &temp); err != nil { + return err + } + + f.ID = temp.ID + f.Length = temp.Length + f.ChunkSize = temp.ChunkSize + f.UploadDate = temp.UploadDate + f.Name = temp.Name + f.Metadata = temp.Metadata + + return nil +} + func newGridFSDownloadStream( ctx context.Context, cancel context.CancelFunc, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go index c1f92774..ba7883d9 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/gridfs_upload_stream.go @@ -29,7 +29,7 @@ var ErrStreamClosed = errors.New("stream is closed or aborted") // metadata. type GridFSUploadStream struct { *upload // chunk size and metadata - FileID interface{} + FileID any chunkIndex int chunksColl *Collection // collection to store file chunks @@ -48,7 +48,7 @@ func newUploadStream( ctx context.Context, cancel context.CancelFunc, up *upload, - fileID interface{}, + fileID any, filename string, chunks, files *Collection, ) *GridFSUploadStream { @@ -150,7 +150,7 @@ func (us *GridFSUploadStream) uploadChunks(ctx context.Context, uploadPartial bo numChunks = int(math.Floor(chunks)) } - docs := make([]interface{}, numChunks) + docs := make([]any, numChunks) begChunkIndex := us.chunkIndex for i := 0; i < us.bufferIndex; i += int(us.chunkSize) { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go index 748957da..f8529c16 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/index_view.go @@ -14,6 +14,7 @@ import ( "strconv" "go.mongodb.org/mongo-driver/v2/internal/mongoutil" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/internal/serverselector" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/mongo/readpref" @@ -29,11 +30,10 @@ import ( var ErrInvalidIndexValue = errors.New("invalid index value") // ErrNonStringIndexName is returned if an index is created with a name that is not a string. +// +// Deprecated: it will be removed in the next major release var ErrNonStringIndexName = errors.New("index name must be a string") -// ErrMultipleIndexDrop is returned if multiple indexes would be dropped from a call to IndexView.DropOne. -var ErrMultipleIndexDrop = errors.New("multiple indexes would be dropped") - // IndexView is a type that can be used to create, drop, and list indexes on a collection. An IndexView for a collection // can be created by a call to Collection.Indexes(). type IndexView struct { @@ -45,19 +45,12 @@ type IndexModel struct { // A document describing which keys should be used for the index. It cannot be nil. This must be an order-preserving // type such as bson.D. Map types such as bson.M are not valid. See https://www.mongodb.com/docs/manual/indexes/#indexes // for examples of valid documents. - Keys interface{} + Keys any // The options to use to create the index. Options *options.IndexOptionsBuilder } -func isNamespaceNotFoundError(err error) bool { - if de, ok := err.(driver.Error); ok { - return de.Code == 26 - } - return false -} - // List executes a listIndexes command and returns a cursor over the indexes in the collection. // // The opts parameter can be used to specify options for this operation (see the options.ListIndexesOptions @@ -109,6 +102,11 @@ func (iv IndexView) List(ctx context.Context, opts ...options.Lister[options.Lis op = op.BatchSize(*args.BatchSize) cursorOpts.BatchSize = *args.BatchSize } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } retry := driver.RetryNone if iv.coll.client.retryReads { @@ -120,20 +118,26 @@ func (iv IndexView) List(ctx context.Context, opts ...options.Lister[options.Lis if err != nil { // for namespaceNotFound errors, return an empty cursor and do not throw an error closeImplicitSession(sess) - if isNamespaceNotFoundError(err) { + var de driver.Error + if errors.As(err, &de) && de.NamespaceNotFound() { return newEmptyCursor(), nil } - return nil, replaceErrors(err) + return nil, wrapErrors(err) } bc, err := op.Result(cursorOpts) if err != nil { closeImplicitSession(sess) - return nil, replaceErrors(err) + return nil, wrapErrors(err) } - cursor, err := newCursorWithSession(bc, iv.coll.bsonOpts, iv.coll.registry, sess) - return cursor, replaceErrors(err) + cursor, err := newCursorWithSession(bc, iv.coll.bsonOpts, iv.coll.registry, sess, + + // This value is included for completeness, but a server will never return + // a tailable awaitData cursor from a listIndexes operation. + withCursorOptionClientTimeout(iv.coll.client.timeout)) + + return cursor, wrapErrors(err) } // ListSpecifications executes a List command and returns a slice of returned IndexSpecifications @@ -286,6 +290,11 @@ func (iv IndexView) CreateMany( op.CommitQuorum(commitQuorum) } + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } _, err = processWriteError(op.Execute(ctx)) if err != nil { @@ -383,7 +392,12 @@ func (iv IndexView) createOptionsDoc(opts options.Lister[options.IndexOptions]) return optsDoc, nil } -func (iv IndexView) drop(ctx context.Context, index any, _ ...options.Lister[options.DropIndexesOptions]) error { +func (iv IndexView) drop(ctx context.Context, index any, opts ...options.Lister[options.DropIndexesOptions]) error { + args, err := mongoutil.NewOptions[options.DropIndexesOptions](opts...) + if err != nil { + return fmt.Errorf("failed to construct options from builder: %w", err) + } + if ctx == nil { ctx = context.Background() } @@ -394,7 +408,7 @@ func (iv IndexView) drop(ctx context.Context, index any, _ ...options.Lister[opt defer sess.EndSession() } - err := iv.coll.client.validSession(sess) + err = iv.coll.client.validSession(sess) if err != nil { return err } @@ -415,9 +429,15 @@ func (iv IndexView) drop(ctx context.Context, index any, _ ...options.Lister[opt Deployment(iv.coll.client.deployment).ServerAPI(iv.coll.client.serverAPI). Timeout(iv.coll.client.timeout).Crypt(iv.coll.client.cryptFLE).Authenticator(iv.coll.client.authenticator) + if rawDataOpt := optionsutil.Value(args.Internal, "rawData"); rawDataOpt != nil { + if rawData, ok := rawDataOpt.(bool); ok { + op = op.RawData(rawData) + } + } + err = op.Execute(ctx) if err != nil { - return replaceErrors(err) + return wrapErrors(err) } return nil @@ -450,7 +470,7 @@ func (iv IndexView) DropOne( // DropWithKey drops a collection index by key using the dropIndexes operation. // // This function is useful to drop an index using its key specification instead of its name. -func (iv IndexView) DropWithKey(ctx context.Context, keySpecDocument interface{}, opts ...options.Lister[options.DropIndexesOptions]) error { +func (iv IndexView) DropWithKey(ctx context.Context, keySpecDocument any, opts ...options.Lister[options.DropIndexesOptions]) error { doc, err := marshal(keySpecDocument, iv.coll.bsonOpts, iv.coll.registry) if err != nil { return err diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go index 260576bd..703115fd 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongo.go @@ -31,18 +31,6 @@ type Dialer interface { DialContext(ctx context.Context, network, address string) (net.Conn, error) } -// MarshalError is returned when attempting to marshal a value into a document -// results in an error. -type MarshalError struct { - Value interface{} - Err error -} - -// Error implements the error interface. -func (me MarshalError) Error() string { - return fmt.Sprintf("cannot marshal 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 // helper and is intended for serializing to BSON. // @@ -83,6 +71,9 @@ func getEncoder( if opts.OmitZeroStruct { enc.OmitZeroStruct() } + if opts.OmitEmpty { + enc.OmitEmpty() + } if opts.StringifyMapKeysWithFmt { enc.StringifyMapKeysWithFmt() } @@ -112,7 +103,7 @@ func newEncoderFn(opts *options.BSONOptions, registry *bson.Registry) codecutil. // If bsonOpts and registry are specified, the encoder is configured with the requested behaviors. // If they are nil, the default behaviors are used. func marshal( - val interface{}, + val any, bsonOpts *options.BSONOptions, registry *bson.Registry, ) (bsoncore.Document, error) { @@ -149,17 +140,17 @@ func ensureID( oid bson.ObjectID, bsonOpts *options.BSONOptions, reg *bson.Registry, -) (bsoncore.Document, interface{}, error) { +) (bsoncore.Document, any, error) { if reg == nil { reg = defaultRegistry } // Try to find the "_id" element. If it exists, try to unmarshal just the - // "_id" field as an interface{} and return it along with the unmodified + // "_id" field as an any and return it along with the unmodified // BSON document. if _, err := doc.LookupErr("_id"); err == nil { var id struct { - ID interface{} `bson:"_id"` + ID any `bson:"_id"` } dec := getDecoder(doc, bsonOpts, reg) err = dec.Decode(&id) @@ -214,7 +205,7 @@ func ensureNoDollarKey(doc bsoncore.Document) error { } func marshalAggregatePipeline( - pipeline interface{}, + pipeline any, bsonOpts *options.BSONOptions, registry *bson.Registry, ) (bsoncore.Document, bool, error) { @@ -302,7 +293,7 @@ func marshalAggregatePipeline( } func marshalUpdateValue( - update interface{}, + update any, bsonOpts *options.BSONOptions, registry *bson.Registry, dollarKeysAllowed bool, @@ -392,7 +383,7 @@ func marshalUpdateValue( } func marshalValue( - val interface{}, + val any, bsonOpts *options.BSONOptions, registry *bson.Registry, ) (bsoncore.Value, error) { @@ -401,7 +392,7 @@ func marshalValue( // Build the aggregation pipeline for the CountDocument command. func countDocumentsAggregatePipeline( - filter interface{}, + filter any, encOpts *options.BSONOptions, registry *bson.Registry, args *options.CountOptions, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go index 9e6e9daf..66aa12b9 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/mongocryptd.go @@ -132,7 +132,7 @@ func (mc *mongocryptdClient) spawnProcess() error { } // createSpawnArgs creates arguments to spawn mcryptClient. It returns the path and a slice of arguments. -func createSpawnArgs(opts map[string]interface{}) (string, []string) { +func createSpawnArgs(opts map[string]any) (string, []string) { var spawnArgs []string // get command path diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go index c49951dc..58ca97d6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/aggregateoptions.go @@ -10,6 +10,7 @@ import ( "time" "go.mongodb.org/mongo-driver/v2/bson" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" ) // AggregateOptions represents arguments that can be used to configure an @@ -22,10 +23,14 @@ type AggregateOptions struct { BypassDocumentValidation *bool Collation *Collation MaxAwaitTime *time.Duration - Comment interface{} - Hint interface{} - Let interface{} + Comment any + Hint any + Let any Custom bson.M + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // AggregateOptionsBuilder contains options to configure aggregate operations. @@ -70,8 +75,7 @@ func (ao *AggregateOptionsBuilder) SetBatchSize(i int32) *AggregateOptionsBuilde } // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes -// executed as part of the operation will opt out of document-level validation on the server. This -// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value +// executed as part of the operation will opt out of document-level validation on the server. The default value // is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about // document validation. func (ao *AggregateOptionsBuilder) SetBypassDocumentValidation(b bool) *AggregateOptionsBuilder { @@ -84,9 +88,8 @@ func (ao *AggregateOptionsBuilder) SetBypassDocumentValidation(b bool) *Aggregat return ao } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For previous -// server versions, the driver will return an error if this option is used. The default value is nil, +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, // which means the default collation of the collection will be used. func (ao *AggregateOptionsBuilder) SetCollation(c *Collation) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { @@ -99,8 +102,7 @@ func (ao *AggregateOptionsBuilder) SetCollation(c *Collation) *AggregateOptionsB } // SetMaxAwaitTime sets the value for the MaxAwaitTime field. Specifies maximum amount of time -// that the server should wait for new documents to satisfy a tailable cursor query. This option is -// only valid for MongoDB versions >= 3.2 and is ignored for previous server versions. +// that the server should wait for new documents to satisfy a tailable cursor query. func (ao *AggregateOptionsBuilder) SetMaxAwaitTime(d time.Duration) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.MaxAwaitTime = &d @@ -114,7 +116,7 @@ func (ao *AggregateOptionsBuilder) SetMaxAwaitTime(d time.Duration) *AggregateOp // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil, // which means that no comment will be included in the logs. -func (ao *AggregateOptionsBuilder) SetComment(comment interface{}) *AggregateOptionsBuilder { +func (ao *AggregateOptionsBuilder) SetComment(comment any) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.Comment = comment @@ -128,7 +130,7 @@ func (ao *AggregateOptionsBuilder) SetComment(comment interface{}) *AggregateOpt // either be the index name as a string or the index specification as a document. The hint does not apply to // $lookup and $graphLookup aggregation stages. The driver will return an error if the hint parameter // is a multi-key map. The default value is nil, which means that no hint will be sent. -func (ao *AggregateOptionsBuilder) SetHint(h interface{}) *AggregateOptionsBuilder { +func (ao *AggregateOptionsBuilder) SetHint(h any) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.Hint = h @@ -143,7 +145,7 @@ func (ao *AggregateOptionsBuilder) SetHint(h interface{}) *AggregateOptionsBuild // option. This must be a document mapping parameter names to values. Values must be constant or closed // expressions that do not reference document fields. Parameters can then be accessed as variables in // an aggregate expression context (e.g. "$$var"). -func (ao *AggregateOptionsBuilder) SetLet(let interface{}) *AggregateOptionsBuilder { +func (ao *AggregateOptionsBuilder) SetLet(let any) *AggregateOptionsBuilder { ao.Opts = append(ao.Opts, func(opts *AggregateOptions) error { opts.Let = let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go index c630659c..db3508fb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/autoencryptionoptions.go @@ -9,6 +9,7 @@ package options import ( "crypto/tls" "net/http" + "time" "go.mongodb.org/mongo-driver/v2/internal/httputil" ) @@ -32,14 +33,15 @@ import ( type AutoEncryptionOptions struct { KeyVaultClientOptions *ClientOptions KeyVaultNamespace string - KmsProviders map[string]map[string]interface{} - SchemaMap map[string]interface{} + KmsProviders map[string]map[string]any + SchemaMap map[string]any BypassAutoEncryption *bool - ExtraOptions map[string]interface{} + ExtraOptions map[string]any TLSConfig map[string]*tls.Config HTTPClient *http.Client - EncryptedFieldsMap map[string]interface{} + EncryptedFieldsMap map[string]any BypassQueryAnalysis *bool + KeyExpiration *time.Duration } // AutoEncryption creates a new AutoEncryptionOptions configured with default values. @@ -72,7 +74,7 @@ func (a *AutoEncryptionOptions) SetKeyVaultNamespace(ns string) *AutoEncryptionO } // SetKmsProviders specifies options for KMS providers. This is required. -func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string]interface{}) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string]any) *AutoEncryptionOptions { a.KmsProviders = providers return a @@ -85,7 +87,7 @@ func (a *AutoEncryptionOptions) SetKmsProviders(providers map[string]map[string] // Supplying a schemaMap provides more security than relying on JSON Schemas obtained from the server. It protects // against a malicious server advertising a false JSON Schema, which could trick the client into sending unencrypted // data that should be encrypted. -func (a *AutoEncryptionOptions) SetSchemaMap(schemaMap map[string]interface{}) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetSchemaMap(schemaMap map[string]any) *AutoEncryptionOptions { a.SchemaMap = schemaMap return a @@ -134,7 +136,7 @@ func (a *AutoEncryptionOptions) SetBypassAutoEncryption(bypass bool) *AutoEncryp // absolute path to the directory containing the linked libmongocrypt library. Setting an override // path disables the default system library search path. If an override path is specified but the // crypt_shared library cannot be loaded, Client creation will return an error. Must be a string. -func (a *AutoEncryptionOptions) SetExtraOptions(extraOpts map[string]interface{}) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetExtraOptions(extraOpts map[string]any) *AutoEncryptionOptions { a.ExtraOptions = extraOpts return a @@ -151,7 +153,7 @@ func (a *AutoEncryptionOptions) SetTLSConfig(cfg map[string]*tls.Config) *AutoEn // SetEncryptedFieldsMap specifies a map from namespace to local EncryptedFieldsMap document. // EncryptedFieldsMap is used for Queryable Encryption. -func (a *AutoEncryptionOptions) SetEncryptedFieldsMap(ef map[string]interface{}) *AutoEncryptionOptions { +func (a *AutoEncryptionOptions) SetEncryptedFieldsMap(ef map[string]any) *AutoEncryptionOptions { a.EncryptedFieldsMap = ef return a @@ -164,3 +166,11 @@ func (a *AutoEncryptionOptions) SetBypassQueryAnalysis(bypass bool) *AutoEncrypt return a } + +// SetKeyExpiration specifies duration for the key expiration. 0 or negative value means "never expire". +// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up. +func (a *AutoEncryptionOptions) SetKeyExpiration(expiration time.Duration) *AutoEncryptionOptions { + a.KeyExpiration = &expiration + + return a +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go index 11dd6c1b..cbdc7f48 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/bulkwriteoptions.go @@ -6,6 +6,8 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // DefaultOrdered is the default value for the Ordered option in BulkWriteOptions. var DefaultOrdered = true @@ -15,9 +17,13 @@ var DefaultOrdered = true // See corresponding setter methods for documentation. type BulkWriteOptions struct { BypassDocumentValidation *bool - Comment interface{} + Comment any Ordered *bool - Let interface{} + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // BulkWriteOptionsBuilder contains options to configure bulk write operations. @@ -43,7 +49,7 @@ func (b *BulkWriteOptionsBuilder) List() []func(*BulkWriteOptions) error { // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help tracethe operation. The default value is nil, // which means that no comment will be included in the logs. -func (b *BulkWriteOptionsBuilder) SetComment(comment interface{}) *BulkWriteOptionsBuilder { +func (b *BulkWriteOptionsBuilder) SetComment(comment any) *BulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error { opts.Comment = comment @@ -66,8 +72,7 @@ func (b *BulkWriteOptionsBuilder) SetOrdered(ordered bool) *BulkWriteOptionsBuil } // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes -// executed as part of the operation will opt out of document-level validation on the server. This option -// is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The default value is +// executed as part of the operation will opt out of document-level validation on the server. The default value is // false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about document // validation. func (b *BulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) *BulkWriteOptionsBuilder { @@ -84,7 +89,7 @@ func (b *BulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) *Bulk // This option is only valid for MongoDB versions >= 5.0. Older servers will report an error for using this option. // This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not // reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (b *BulkWriteOptionsBuilder) SetLet(let interface{}) *BulkWriteOptionsBuilder { +func (b *BulkWriteOptionsBuilder) SetLet(let any) *BulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *BulkWriteOptions) error { opts.Let = &let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go index 66f1899f..9e5bb93b 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/changestreamoptions.go @@ -18,14 +18,14 @@ import ( type ChangeStreamOptions struct { BatchSize *int32 Collation *Collation - Comment interface{} + Comment any FullDocument *FullDocument FullDocumentBeforeChange *FullDocument MaxAwaitTime *time.Duration - ResumeAfter interface{} + ResumeAfter any ShowExpandedEvents *bool StartAtOperationTime *bson.Timestamp - StartAfter interface{} + StartAfter any Custom bson.M CustomPipeline bson.M } @@ -57,10 +57,9 @@ func (cso *ChangeStreamOptionsBuilder) SetBatchSize(i int32) *ChangeStreamOption return cso } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string comparisons -// during the operation. This option is only valid for MongoDB versions >= 3.4. For previous server versions, -// the driver will return an error if this option is used. The default value is nil, which means the default -// collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (cso *ChangeStreamOptionsBuilder) SetCollation(c Collation) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.Collation = &c @@ -72,7 +71,7 @@ func (cso *ChangeStreamOptionsBuilder) SetCollation(c Collation) *ChangeStreamOp // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil, // which means that no comment will be included in the logs. -func (cso *ChangeStreamOptionsBuilder) SetComment(comment interface{}) *ChangeStreamOptionsBuilder { +func (cso *ChangeStreamOptionsBuilder) SetComment(comment any) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.Comment = comment return nil @@ -115,7 +114,7 @@ func (cso *ChangeStreamOptionsBuilder) SetMaxAwaitTime(d time.Duration) *ChangeS // SetResumeAfter sets the value for the ResumeAfter field. Specifies a document specifying the logical starting // point for the change stream. Only changes corresponding to an oplog entry immediately after the resume token // will be returned. If this is specified, StartAtOperationTime and StartAfter must not be set. -func (cso *ChangeStreamOptionsBuilder) SetResumeAfter(rt interface{}) *ChangeStreamOptionsBuilder { +func (cso *ChangeStreamOptionsBuilder) SetResumeAfter(rt any) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.ResumeAfter = rt return nil @@ -152,7 +151,7 @@ func (cso *ChangeStreamOptionsBuilder) SetStartAtOperationTime(t *bson.Timestamp // the collection has been dropped and recreated or renamed. Only changes corresponding to an oplog entry // immediately after the specified token will be returned. If this is specified, ResumeAfter and // StartAtOperationTime must not be set. This option is only valid for MongoDB versions >= 4.1.1. -func (cso *ChangeStreamOptionsBuilder) SetStartAfter(sa interface{}) *ChangeStreamOptionsBuilder { +func (cso *ChangeStreamOptionsBuilder) SetStartAfter(sa any) *ChangeStreamOptionsBuilder { cso.Opts = append(cso.Opts, func(opts *ChangeStreamOptions) error { opts.StartAfter = sa return nil diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go index a55ac27f..90d6c241 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientbulkwriteoptions.go @@ -7,6 +7,7 @@ package options import ( + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" ) @@ -15,11 +16,15 @@ import ( // See corresponding setter methods for documentation. type ClientBulkWriteOptions struct { BypassDocumentValidation *bool - Comment interface{} + Comment any Ordered *bool - Let interface{} + Let any WriteConcern *writeconcern.WriteConcern VerboseResults *bool + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // ClientBulkWriteOptionsBuilder contains options to configure client-level bulk @@ -46,7 +51,7 @@ func (b *ClientBulkWriteOptionsBuilder) List() []func(*ClientBulkWriteOptions) e // SetComment sets the value for the Comment field. Specifies a string or document that will be included in // server logs, profiling logs, and currentOp queries to help tracethe operation. The default value is nil, // which means that no comment will be included in the logs. -func (b *ClientBulkWriteOptionsBuilder) SetComment(comment interface{}) *ClientBulkWriteOptionsBuilder { +func (b *ClientBulkWriteOptionsBuilder) SetComment(comment any) *ClientBulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error { opts.Comment = comment @@ -85,7 +90,7 @@ func (b *ClientBulkWriteOptionsBuilder) SetBypassDocumentValidation(bypass bool) // SetLet sets the value for the Let field. Let specifies parameters for all update and delete commands in the BulkWrite. // This must be a document mapping parameter names to values. Values must be constant or closed expressions that do not // reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (b *ClientBulkWriteOptionsBuilder) SetLet(let interface{}) *ClientBulkWriteOptionsBuilder { +func (b *ClientBulkWriteOptionsBuilder) SetLet(let any) *ClientBulkWriteOptionsBuilder { b.Opts = append(b.Opts, func(opts *ClientBulkWriteOptions) error { opts.Let = &let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go index 3f9b3745..a6c477a7 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientencryptionoptions.go @@ -10,6 +10,7 @@ import ( "crypto/tls" "fmt" "net/http" + "time" "go.mongodb.org/mongo-driver/v2/internal/httputil" ) @@ -19,9 +20,10 @@ import ( // See corresponding setter methods for documentation. type ClientEncryptionOptions struct { KeyVaultNamespace string - KmsProviders map[string]map[string]interface{} + KmsProviders map[string]map[string]any TLSConfig map[string]*tls.Config HTTPClient *http.Client + KeyExpiration *time.Duration } // ClientEncryptionOptionsBuilder contains options to configure client @@ -58,7 +60,7 @@ func (c *ClientEncryptionOptionsBuilder) SetKeyVaultNamespace(ns string) *Client } // SetKmsProviders specifies options for KMS providers. This is required. -func (c *ClientEncryptionOptionsBuilder) SetKmsProviders(providers map[string]map[string]interface{}) *ClientEncryptionOptionsBuilder { +func (c *ClientEncryptionOptionsBuilder) SetKmsProviders(providers map[string]map[string]any) *ClientEncryptionOptionsBuilder { c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error { opts.KmsProviders = providers return nil @@ -80,6 +82,18 @@ func (c *ClientEncryptionOptionsBuilder) SetTLSConfig(cfg map[string]*tls.Config return c } +// SetKeyExpiration specifies duration for the key expiration. 0 or negative value means "never expire". +// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up. +func (c *ClientEncryptionOptionsBuilder) SetKeyExpiration(expiration time.Duration) *ClientEncryptionOptionsBuilder { + c.Opts = append(c.Opts, func(opts *ClientEncryptionOptions) error { + opts.KeyExpiration = &expiration + + return nil + }) + + return c +} + // BuildTLSConfig specifies tls.Config options for each KMS provider to use to configure TLS on all connections created // to the KMS provider. The input map should contain a mapping from each KMS provider to a document containing the necessary // options, as follows: @@ -103,7 +117,7 @@ func (c *ClientEncryptionOptionsBuilder) SetTLSConfig(cfg map[string]*tls.Config // to be considered trusted when making a TLS connection (e.g. "tlsCaFile=/path/to/caFile"). // // This should only be used to set custom TLS options. By default, the connection will use an empty tls.Config{} with MinVersion set to tls.VersionTLS12. -func BuildTLSConfig(tlsOpts map[string]interface{}) (*tls.Config, error) { +func BuildTLSConfig(tlsOpts map[string]any) (*tls.Config, error) { // use TLS min version 1.2 to enforce more secure hash algorithms and advanced cipher suites cfg := &tls.Config{MinVersion: tls.VersionTLS12} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go index 9623562e..adc880a5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/clientoptions.go @@ -26,6 +26,7 @@ import ( "go.mongodb.org/mongo-driver/v2/bson" "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/httputil" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/mongo/readconcern" "go.mongodb.org/mongo-driver/v2/mongo/readpref" "go.mongodb.org/mongo-driver/v2/mongo/writeconcern" @@ -67,7 +68,7 @@ type ContextDialer interface { // Credential can be used to provide authentication options when configuring a Client. // // AuthMechanism: the mechanism to use for authentication. Supported values include "SCRAM-SHA-256", "SCRAM-SHA-1", -// "MONGODB-CR", "PLAIN", "GSSAPI", "MONGODB-X509", and "MONGODB-AWS". This can also be set through the "authMechanism" +// "PLAIN", "GSSAPI", "MONGODB-X509", and "MONGODB-AWS". This can also be set through the "authMechanism" // URI option. (e.g. "authMechanism=PLAIN"). For more information, see // https://www.mongodb.com/docs/manual/core/authentication-mechanisms/. // @@ -182,9 +183,12 @@ type BSONOptions struct { // OmitZeroStruct causes the driver to consider the zero value for a struct // (e.g. MyStruct{}) as empty and omit it from the marshaled BSON when the - // "omitempty" struct tag option is set. + // "omitempty" struct tag option or the "OmitEmpty" field is set. OmitZeroStruct bool + // OmitEmpty causes the driver to omit empty values from the marshaled BSON. + OmitEmpty bool + // StringifyMapKeysWithFmt causes the driver to convert Go map keys to BSON // document field name strings using fmt.Sprint instead of the default // string conversion logic. @@ -203,7 +207,7 @@ type BSONOptions struct { // DefaultDocumentM causes the driver to always unmarshal documents into the // bson.M type. This behavior is restricted to data typed as - // "interface{}" or "map[string]interface{}". + // "any" or "map[string]any". DefaultDocumentM bool // ObjectIDAsHexString causes the Decoder to decode object IDs to their hex @@ -283,14 +287,22 @@ type ClientOptions struct { // encryption. // // Deprecated: This option is for internal use only and should not be set (see GODRIVER-2149). It may be - // changed or removed in any release. + // changed in any release. This option will be removed in 3.0 and replaced with the Custom options.Options + // pattern: SetInternalClientOptions(clientOptions, "crypt", myCrypt) Crypt driver.Crypt // Deployment specifies a custom deployment to use for the new Client. // + // Deprecated: This option is for internal use only and should not be set. It may be changed in any release. + // This option will be removed in 3.0 and replaced with the Custom options.Options pattern: + // SetInternalClientOptions(clientOptions, "deployment", myDeployment) + Deployment driver.Deployment + + // Custom specifies internal options for the new Client. + // // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any // release. - Deployment driver.Deployment + Custom optionsutil.Options connString *connstring.ConnString err error @@ -299,7 +311,7 @@ type ClientOptions struct { // Client creates a new ClientOptions instance. func Client() *ClientOptions { opts := &ClientOptions{} - opts = opts.SetHTTPClient(httputil.DefaultHTTPClient) + opts = opts.SetHTTPClient(httputil.NewHTTPClient()) return opts } @@ -593,24 +605,45 @@ func (c *ClientOptions) Validate() error { return fmt.Errorf("cannot set both OIDCMachineCallback and OIDCHumanCallback, only one may be specified") } if c.Auth.OIDCHumanCallback == nil && c.Auth.AuthMechanismProperties[auth.AllowedHostsProp] != "" { - return fmt.Errorf("Cannot specify ALLOWED_HOSTS without an OIDCHumanCallback") + return fmt.Errorf("cannot specify ALLOWED_HOSTS without an OIDCHumanCallback") + } + if c.Auth.OIDCMachineCallback == nil && c.Auth.OIDCHumanCallback == nil && c.Auth.AuthMechanismProperties[auth.EnvironmentProp] == "" { + return errors.New("must specify at least one of OIDCMachineCallback, OIDCHumanCallback, or ENVIRONMENT authMechanismProperty") + } + + // Return an error if an unsupported authMechanismProperty is specified + // for MONGODB-OIDC. + for prop := range c.Auth.AuthMechanismProperties { + switch prop { + case auth.AllowedHostsProp, auth.EnvironmentProp, auth.ResourceProp: + default: + return fmt.Errorf("auth mechanism property %q is not valid for MONGODB-OIDC", prop) + } } + if env, ok := c.Auth.AuthMechanismProperties[auth.EnvironmentProp]; ok { switch env { case auth.GCPEnvironmentValue, auth.AzureEnvironmentValue: + if c.Auth.AuthMechanismProperties[auth.ResourceProp] == "" { + return fmt.Errorf("%q must be set for the %s %q", auth.ResourceProp, env, auth.EnvironmentProp) + } + fallthrough + case auth.K8SEnvironmentValue: if c.Auth.OIDCMachineCallback != nil { return fmt.Errorf("OIDCMachineCallback cannot be specified with the %s %q", env, auth.EnvironmentProp) } if c.Auth.OIDCHumanCallback != nil { return fmt.Errorf("OIDCHumanCallback cannot be specified with the %s %q", env, auth.EnvironmentProp) } - if c.Auth.AuthMechanismProperties[auth.ResourceProp] == "" { - return fmt.Errorf("%q must be set for the %s %q", auth.ResourceProp, env, auth.EnvironmentProp) - } - default: + case auth.TestEnvironmentValue: if c.Auth.AuthMechanismProperties[auth.ResourceProp] != "" { return fmt.Errorf("%q must not be set for the %s %q", auth.ResourceProp, env, auth.EnvironmentProp) } + if c.Auth.Username != "" { + return fmt.Errorf("must not specify username for %s %q", env, auth.EnvironmentProp) + } + default: + return fmt.Errorf("the %s %q is not supported for MONGODB-OIDC", env, auth.EnvironmentProp) } } } @@ -662,9 +695,9 @@ func (c *ClientOptions) SetAuth(auth Credential) *ClientOptions { // SetCompressors sets the compressors that can be used when communicating with a server. Valid values are: // -// 1. "snappy" - requires server version >= 3.4 +// 1. "snappy" // -// 2. "zlib" - requires server version >= 3.6 +// 2. "zlib" // // 3. "zstd" - requires server version >= 4.2, and driver version >= 1.2.0 with cgo support enabled or driver // version >= 1.3.0 without cgo. @@ -896,9 +929,8 @@ func (c *ClientOptions) SetReplicaSet(s string) *ClientOptions { // DeleteManyModel instances to be considered retryable. Unacknowledged writes will not be retried, even if this option // is set to true. // -// This option requires server version >= 3.6 and a replica set or sharded cluster and will be ignored for any other -// cluster type. This can also be set through the "retryWrites" URI option (e.g. "retryWrites=true"). The default is -// true. +// This option only works on a replica set or sharded cluster and will be ignored for any other cluster type. +// This can also be set through the "retryWrites" URI option (e.g. "retryWrites=true"). The default is true. func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions { c.RetryWrites = &b @@ -912,7 +944,7 @@ func (c *ClientOptions) SetRetryWrites(b bool) *ClientOptions { // EstimatedDocumentCount, Watch (for Client, Database, and Collection), ListCollections, and ListDatabases. Note that // operations run through RunCommand are not retried. // -// This option requires server version >= 3.6 and driver version >= 1.1.0. The default is true. +// The default is true. func (c *ClientOptions) SetRetryReads(b bool) *ClientOptions { c.RetryReads = &b diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go index 8f92b62f..9cf5924a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/countoptions.go @@ -6,16 +6,22 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // CountOptions represents arguments that can be used to configure a // CountDocuments operation. // // See corresponding setter methods for documentation. type CountOptions struct { Collation *Collation - Comment interface{} - Hint interface{} + Comment any + Hint any Limit *int64 Skip *int64 + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // CountOptionsBuilder contains options to configure count operations. Each @@ -35,10 +41,9 @@ func (co *CountOptionsBuilder) List() []func(*CountOptions) error { return co.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string comparisons -// during the operation. This option is only valid for MongoDB versions >= 3.4. For previous server versions, -// the driver will return an error if this option is used. The default value is nil, which means the default -// collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (co *CountOptionsBuilder) SetCollation(c *Collation) *CountOptionsBuilder { co.Opts = append(co.Opts, func(opts *CountOptions) error { opts.Collation = c @@ -52,7 +57,7 @@ func (co *CountOptionsBuilder) SetCollation(c *Collation) *CountOptionsBuilder { // SetComment sets the value for the Comment field. Specifies a string or document that will be included // in server logs, profiling logs, and currentOp queries to help trace the operation. The default is nil, // which means that no comment will be included in the logs. -func (co *CountOptionsBuilder) SetComment(comment interface{}) *CountOptionsBuilder { +func (co *CountOptionsBuilder) SetComment(comment any) *CountOptionsBuilder { co.Opts = append(co.Opts, func(opts *CountOptions) error { opts.Comment = comment @@ -66,7 +71,7 @@ func (co *CountOptionsBuilder) SetComment(comment interface{}) *CountOptionsBuil // either be the index name as a string or the index specification as a document. The driver will return // an error if the hint parameter is a multi-key map. The default value is nil, which means that no hint // will be sent. -func (co *CountOptionsBuilder) SetHint(h interface{}) *CountOptionsBuilder { +func (co *CountOptionsBuilder) SetHint(h any) *CountOptionsBuilder { co.Opts = append(co.Opts, func(opts *CountOptions) error { opts.Hint = h diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go index fd0aad57..4bac0d04 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/createcollectionoptions.go @@ -16,7 +16,7 @@ import ( // // See corresponding setter methods for documentation. type DefaultIndexOptions struct { - StorageEngine interface{} + StorageEngine any } // DefaultIndexOptionsBuilder contains options to configure default index @@ -39,7 +39,7 @@ func (d *DefaultIndexOptionsBuilder) List() []func(*DefaultIndexOptions) error { // SetStorageEngine sets the value for the StorageEngine field. Specifies the storage engine to use for // the index. The value must be a document in the form {: }. The default // value is nil, which means that the default storage engine will be used. -func (d *DefaultIndexOptionsBuilder) SetStorageEngine(storageEngine interface{}) *DefaultIndexOptionsBuilder { +func (d *DefaultIndexOptionsBuilder) SetStorageEngine(storageEngine any) *DefaultIndexOptionsBuilder { d.Opts = append(d.Opts, func(opts *DefaultIndexOptions) error { opts.StorageEngine = storageEngine @@ -149,18 +149,18 @@ func (tso *TimeSeriesOptionsBuilder) SetBucketRounding(dur time.Duration) *TimeS type CreateCollectionOptions struct { Capped *bool Collation *Collation - ChangeStreamPreAndPostImages interface{} + ChangeStreamPreAndPostImages any DefaultIndexOptions *DefaultIndexOptionsBuilder MaxDocuments *int64 SizeInBytes *int64 - StorageEngine interface{} + StorageEngine any ValidationAction *string ValidationLevel *string - Validator interface{} + Validator any ExpireAfterSeconds *int64 TimeSeriesOptions *TimeSeriesOptionsBuilder - EncryptedFields interface{} - ClusteredIndex interface{} + EncryptedFields any + ClusteredIndex any } // CreateCollectionOptionsBuilder contains options to configure a new @@ -193,9 +193,8 @@ func (c *CreateCollectionOptionsBuilder) SetCapped(capped bool) *CreateCollectio return c } -// SetCollation sets the value for the Collation field. Specifies the default collation for the new -// collection. This option is only valid for MongoDB versions >= 3.4. For previous server versions, -// the driver will return an error if this option is used. The default value is nil. +// SetCollation sets the value for the Collation field. Specifies the default +// collation for the new collection. The default value is nil. func (c *CreateCollectionOptionsBuilder) SetCollation(collation *Collation) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.Collation = collation @@ -212,7 +211,7 @@ func (c *CreateCollectionOptionsBuilder) SetCollation(collation *Collation) *Cre // option is only valid for MongoDB versions >= 6.0. The default value is nil, which means that // change streams opened against the collection will not return pre- and post-images of updated // documents in any way. -func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi interface{}) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi any) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ChangeStreamPreAndPostImages = &csppi @@ -222,9 +221,9 @@ func (c *CreateCollectionOptionsBuilder) SetChangeStreamPreAndPostImages(csppi i return c } -// SetDefaultIndexOptions sets the value for the DefaultIndexOptions field. Specifies a default -// configuration for indexes on the collection. This option is only valid for MongoDB versions -// >= 3.4. The default value is nil, meaning indexes will be configured using server defaults. +// SetDefaultIndexOptions sets the value for the DefaultIndexOptions field. +// Specifies a default configuration for indexes on the collection. The default +// value is nil, meaning indexes will be configured using server defaults. func (c *CreateCollectionOptionsBuilder) SetDefaultIndexOptions(iopts *DefaultIndexOptionsBuilder) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.DefaultIndexOptions = iopts @@ -265,7 +264,7 @@ func (c *CreateCollectionOptionsBuilder) SetSizeInBytes(size int64) *CreateColle // SetStorageEngine sets the value for the StorageEngine field. Specifies the storage engine to use for // the index. The value must be a document in the form {: }. The default // value is nil, which means that the default storage engine will be used. -func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine interface{}) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine any) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.StorageEngine = &storageEngine @@ -278,7 +277,7 @@ func (c *CreateCollectionOptionsBuilder) SetStorageEngine(storageEngine interfac // SetValidationAction sets the value for the ValidationAction field. Specifies what should happen if a // document being inserted does not pass validation. Valid values are "error" and "warn". See // https://www.mongodb.com/docs/manual/core/schema-validation/#accept-or-reject-invalid-documents for more -// information. This option is only valid for MongoDB versions >= 3.2. The default value is "error". +// information. The default value is "error". func (c *CreateCollectionOptionsBuilder) SetValidationAction(action string) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ValidationAction = &action @@ -292,7 +291,7 @@ func (c *CreateCollectionOptionsBuilder) SetValidationAction(action string) *Cre // SetValidationLevel sets the value for the ValidationLevel field. Specifies how strictly the server applies // validation rules to existing documents in the collection during update operations. Valid values are "off", // "strict", and "moderate". See https://www.mongodb.com/docs/manual/core/schema-validation/#existing-documents -// for more information. This option is only valid for MongoDB versions >= 3.2. The default value is "strict". +// for more information. The default value is "strict". func (c *CreateCollectionOptionsBuilder) SetValidationLevel(level string) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ValidationLevel = &level @@ -305,9 +304,8 @@ func (c *CreateCollectionOptionsBuilder) SetValidationLevel(level string) *Creat // SetValidator sets the value for the Validator field. Sets a document specifying validation rules for the // collection. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more information about -// schema validation. This option is only valid for MongoDB versions >= 3.2. The default value is nil, -// meaning no validator will be used for the collection. -func (c *CreateCollectionOptionsBuilder) SetValidator(validator interface{}) *CreateCollectionOptionsBuilder { +// schema validation. The default value is nil, meaning no validator will be used for the collection. +func (c *CreateCollectionOptionsBuilder) SetValidator(validator any) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.Validator = validator @@ -353,7 +351,7 @@ func (c *CreateCollectionOptionsBuilder) SetTimeSeriesOptions(timeSeriesOpts *Ti // SetEncryptedFields sets the encrypted fields for encrypted collections. // // This option is only valid for MongoDB versions >= 6.0 -func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields interface{}) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.EncryptedFields = encryptedFields @@ -367,7 +365,7 @@ func (c *CreateCollectionOptionsBuilder) SetEncryptedFields(encryptedFields inte // to create a collection with a clustered index. // // This option is only valid for MongoDB versions >= 5.3 -func (c *CreateCollectionOptionsBuilder) SetClusteredIndex(clusteredIndex interface{}) *CreateCollectionOptionsBuilder { +func (c *CreateCollectionOptionsBuilder) SetClusteredIndex(clusteredIndex any) *CreateCollectionOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateCollectionOptions) error { opts.ClusteredIndex = clusteredIndex @@ -402,9 +400,8 @@ func (c *CreateViewOptionsBuilder) List() []func(*CreateViewOptions) error { return c.Opts } -// SetCollation sets the value for the Collation field. Specifies the default collation for the new -// collection. This option is only valid for MongoDB versions >= 3.4. For previous server versions, -// the driver will return an error if this option is used. The default value is nil. +// SetCollation sets the value for the Collation field. Specifies the default +// collation for the new collection. The default value is nil. func (c *CreateViewOptionsBuilder) SetCollation(collation *Collation) *CreateViewOptionsBuilder { c.Opts = append(c.Opts, func(opts *CreateViewOptions) error { opts.Collation = collation diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go index b7b2a192..8d24f9d1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/datakeyoptions.go @@ -10,7 +10,7 @@ package options // // See corresponding setter methods for documentation. type DataKeyOptions struct { - MasterKey interface{} + MasterKey any KeyAltNames []string KeyMaterial []byte } @@ -71,7 +71,7 @@ func (dk *DataKeyOptionsBuilder) List() []func(*DataKeyOptions) error { // } // // If unset, "keyVersion" defaults to the key's primary version and "endpoint" defaults to "cloudkms.googleapis.com". -func (dk *DataKeyOptionsBuilder) SetMasterKey(masterKey interface{}) *DataKeyOptionsBuilder { +func (dk *DataKeyOptionsBuilder) SetMasterKey(masterKey any) *DataKeyOptionsBuilder { dk.Opts = append(dk.Opts, func(opts *DataKeyOptions) error { opts.MasterKey = masterKey diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go index f0d88043..2206abb2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/deleteoptions.go @@ -6,15 +6,21 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // DeleteOneOptions represents arguments that can be used to configure DeleteOne // operations. // // See corresponding setter methods for documentation. type DeleteOneOptions struct { Collation *Collation - Comment interface{} - Hint interface{} - Let interface{} + Comment any + Hint any + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // DeleteOneOptionsBuilder contains options to configure DeleteOne operations. Each @@ -34,11 +40,9 @@ func (do *DeleteOneOptionsBuilder) List() []func(*DeleteOneOptions) error { return do.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to use for -// string comparisons during the operation. This option is only valid for MongoDB -// versions >= 3.4. For previous server versions, the driver will return an error if this -// option is used. The default value is nil, which means the default collation of the -// collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (do *DeleteOneOptionsBuilder) SetCollation(c *Collation) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Collation = c @@ -52,7 +56,7 @@ func (do *DeleteOneOptionsBuilder) SetCollation(c *Collation) *DeleteOneOptionsB // SetComment sets the value for the Comment field. Specifies a string or document that will // be included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (do *DeleteOneOptionsBuilder) SetComment(comment interface{}) *DeleteOneOptionsBuilder { +func (do *DeleteOneOptionsBuilder) SetComment(comment any) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Comment = comment @@ -62,14 +66,15 @@ func (do *DeleteOneOptionsBuilder) SetComment(comment interface{}) *DeleteOneOpt return do } -// SetHint sets the value for the Hint field. Specifies the index to use for the operation. This -// should either be the index name as a string or the index specification as a document. This option -// is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an error if this -// option is specified. For server versions < 3.4, the driver will return a client-side error if this -// option is specified. The driver will return an error if this option is specified during an -// unacknowledged write operation. The driver will return an error if the hint parameter is a -// multi-key map. The default value is nil, which means that no hint will be sent. -func (do *DeleteOneOptionsBuilder) SetHint(hint interface{}) *DeleteOneOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the +// operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions +// >= 4.4. Server versions < 4.4 will return an error if this option is +// specified. The driver will return an error if this option is specified during +// an unacknowledged write operation. The driver will return an error if the +// hint parameter is a multi-key map. The default value is nil, which means that +// no hint will be sent. +func (do *DeleteOneOptionsBuilder) SetHint(hint any) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Hint = hint @@ -84,7 +89,7 @@ func (do *DeleteOneOptionsBuilder) SetHint(hint interface{}) *DeleteOneOptionsBu // this option. This must be a document mapping parameter names to values. Values must be constant // or closed expressions that do not reference document fields. Parameters can then be accessed as // variables in an aggregate expression context (e.g. "$$var"). -func (do *DeleteOneOptionsBuilder) SetLet(let interface{}) *DeleteOneOptionsBuilder { +func (do *DeleteOneOptionsBuilder) SetLet(let any) *DeleteOneOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteOneOptions) error { opts.Let = let @@ -100,9 +105,13 @@ func (do *DeleteOneOptionsBuilder) SetLet(let interface{}) *DeleteOneOptionsBuil // See corresponding setter methods for documentation. type DeleteManyOptions struct { Collation *Collation - Comment interface{} - Hint interface{} - Let interface{} + Comment any + Hint any + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // DeleteManyOptionsBuilder contains options to configure DeleteMany operations. @@ -122,10 +131,9 @@ func (do *DeleteManyOptionsBuilder) List() []func(*DeleteManyOptions) error { return do.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. -// For previous server versions, the driver will return an error if this option is used. The -// default value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (do *DeleteManyOptionsBuilder) SetCollation(c *Collation) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Collation = c @@ -139,7 +147,7 @@ func (do *DeleteManyOptionsBuilder) SetCollation(c *Collation) *DeleteManyOption // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (do *DeleteManyOptionsBuilder) SetComment(comment interface{}) *DeleteManyOptionsBuilder { +func (do *DeleteManyOptionsBuilder) SetComment(comment any) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Comment = comment @@ -149,15 +157,15 @@ func (do *DeleteManyOptionsBuilder) SetComment(comment interface{}) *DeleteManyO return do } -// SetHint sets the value for the Hint field. Specifies the index to use for the operation. -// This should either be the index name as a string or the index specification as a document. -// This option is only valid for MongoDB versions >= 4.4. Server versions >= 3.4 will return an -// error if this option is specified. For server versions < 3.4, the driver will return a -// client-side error if this option is specified. The driver will return an error if this option -// is specified during an unacknowledged write operation. The driver will return an error if the -// hint parameter is a multi-key map. The default value is nil, which means that no hint will -// be sent. -func (do *DeleteManyOptionsBuilder) SetHint(hint interface{}) *DeleteManyOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the +// operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions +// >= 4.4. Server versions < 4.4 will return an error if this option is +// specified. The driver will return an error if this option is specified during +// an unacknowledged write operation. The driver will return an error if the +// hint parameter is a multi-key map. The default value is nil, which means that +// no hint will be sent. +func (do *DeleteManyOptionsBuilder) SetHint(hint any) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Hint = hint @@ -172,7 +180,7 @@ func (do *DeleteManyOptionsBuilder) SetHint(hint interface{}) *DeleteManyOptions // for using this option. This must be a document mapping parameter names to values. Values // must be constant or closed expressions that do not reference document fields. Parameters // can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (do *DeleteManyOptionsBuilder) SetLet(let interface{}) *DeleteManyOptionsBuilder { +func (do *DeleteManyOptionsBuilder) SetLet(let any) *DeleteManyOptionsBuilder { do.Opts = append(do.Opts, func(opts *DeleteManyOptions) error { opts.Let = let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go index 0b9167d5..476c1048 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/distinctoptions.go @@ -6,14 +6,20 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // DistinctOptions represents arguments that can be used to configure a Distinct // operation. // // See corresponding setter methods for documentation. type DistinctOptions struct { Collation *Collation - Comment interface{} - Hint interface{} + Comment any + Hint any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // DistinctOptionsBuilder contains options to configure distinct operations. Each @@ -33,11 +39,9 @@ func (do *DistinctOptionsBuilder) List() []func(*DistinctOptions) error { return do.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to use -// for string comparisons during the operation. This option is only valid for MongoDB -// versions >= 3.4. For previous server versions, the driver will return an error if -// this option is used. The default value is nil, which means the default collation -// of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (do *DistinctOptionsBuilder) SetCollation(c *Collation) *DistinctOptionsBuilder { do.Opts = append(do.Opts, func(opts *DistinctOptions) error { opts.Collation = c @@ -52,7 +56,7 @@ func (do *DistinctOptionsBuilder) SetCollation(c *Collation) *DistinctOptionsBui // will be included in server logs, profiling logs, and currentOp queries to help trace // the operation. The default value is nil, which means that no comment will be included // in the logs. -func (do *DistinctOptionsBuilder) SetComment(comment interface{}) *DistinctOptionsBuilder { +func (do *DistinctOptionsBuilder) SetComment(comment any) *DistinctOptionsBuilder { do.Opts = append(do.Opts, func(opts *DistinctOptions) error { opts.Comment = comment @@ -70,7 +74,7 @@ func (do *DistinctOptionsBuilder) SetComment(comment interface{}) *DistinctOptio // means that no index hint will be sent. // // SetHint sets the Hint field. -func (do *DistinctOptionsBuilder) SetHint(hint interface{}) *DistinctOptionsBuilder { +func (do *DistinctOptionsBuilder) SetHint(hint any) *DistinctOptionsBuilder { do.Opts = append(do.Opts, func(opts *DistinctOptions) error { opts.Hint = hint diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go index 4619b6b6..013b4bbb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/dropcollectionoptions.go @@ -11,7 +11,7 @@ package options // // See corresponding setter methods for documentation. type DropCollectionOptions struct { - EncryptedFields interface{} + EncryptedFields any } // DropCollectionOptionsBuilder contains options to configure collection drop @@ -34,7 +34,7 @@ func (d *DropCollectionOptionsBuilder) List() []func(*DropCollectionOptions) err // SetEncryptedFields sets the encrypted fields for encrypted collections. // // This option is only valid for MongoDB versions >= 6.0 -func (d *DropCollectionOptionsBuilder) SetEncryptedFields(encryptedFields interface{}) *DropCollectionOptionsBuilder { +func (d *DropCollectionOptionsBuilder) SetEncryptedFields(encryptedFields any) *DropCollectionOptionsBuilder { d.Opts = append(d.Opts, func(opts *DropCollectionOptions) error { opts.EncryptedFields = encryptedFields diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go index 2bee45a8..2fd8f87d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/estimatedcountoptions.go @@ -6,12 +6,18 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // EstimatedDocumentCountOptions represents arguments that can be used to configure // an EstimatedDocumentCount operation. // // See corresponding setter methods for documentation. type EstimatedDocumentCountOptions struct { - Comment interface{} + Comment any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // EstimatedDocumentCountOptionsBuilder contains options to estimate document @@ -35,7 +41,7 @@ func (eco *EstimatedDocumentCountOptionsBuilder) List() []func(*EstimatedDocumen // that will be included in server logs, profiling logs, and currentOp queries to help // trace the operation. The default is nil, which means that no comment will be // included in the logs. -func (eco *EstimatedDocumentCountOptionsBuilder) SetComment(comment interface{}) *EstimatedDocumentCountOptionsBuilder { +func (eco *EstimatedDocumentCountOptionsBuilder) SetComment(comment any) *EstimatedDocumentCountOptionsBuilder { eco.Opts = append(eco.Opts, func(opts *EstimatedDocumentCountOptions) error { opts.Comment = comment diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go index 92701c9d..b295bd51 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/findoptions.go @@ -8,6 +8,8 @@ package options import ( "time" + + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" ) // FindOptions represents arguments that can be used to configure a Find @@ -17,24 +19,28 @@ import ( type FindOptions struct { AllowPartialResults *bool Collation *Collation - Comment interface{} - Hint interface{} - Max interface{} + Comment any + Hint any + Max any MaxAwaitTime *time.Duration - Min interface{} + Min any OplogReplay *bool - Projection interface{} + Projection any ReturnKey *bool ShowRecordID *bool Skip *int64 - Sort interface{} + Sort any // The above are in common with FindOneopts. AllowDiskUse *bool BatchSize *int32 CursorType *CursorType - Let interface{} + Let any Limit *int64 NoCursorTimeout *bool + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // FindOptionsBuilder represents functional options that configure an Findopts. @@ -52,11 +58,11 @@ func (f *FindOptionsBuilder) List() []func(*FindOptions) error { return f.Opts } -// SetAllowDiskUse sets the value for the AllowDiskUse field. AllowDiskUse specifies whether the -// server can write temporary data to disk while executing the Find operation. This option is only -// valid for MongoDB versions >= 4.4. Server versions >= 3.2 will report an error if this option -// is specified. For server versions < 3.2, the driver will return a client-side error if this -// option is specified. The default value is false. +// SetAllowDiskUse sets the value for the AllowDiskUse field. AllowDiskUse +// specifies whether the server can write temporary data to disk while executing +// the Find operation. This option is only valid for MongoDB versions >= 4.4. +// Server versions < 4.4 will return an error if this option is specified. The +// default value is false. func (f *FindOptionsBuilder) SetAllowDiskUse(b bool) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.AllowDiskUse = &b @@ -86,10 +92,10 @@ func (f *FindOptionsBuilder) SetBatchSize(i int32) *FindOptionsBuilder { return f } -// SetCollation sets the value for the Collation field. Collation specifies a collation to use for -// string comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. -// For previous server versions, the driver will return an error if this option is used. The -// default value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Collation specifies a +// collation to use for string comparisons during the operation. The default +// value is nil, which means the default collation of the collection will be +// used. func (f *FindOptionsBuilder) SetCollation(collation *Collation) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Collation = collation @@ -101,7 +107,7 @@ func (f *FindOptionsBuilder) SetCollation(collation *Collation) *FindOptionsBuil // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default is nil, which means that no comment will be included in the logs. -func (f *FindOptionsBuilder) SetComment(comment interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetComment(comment any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Comment = &comment return nil @@ -124,7 +130,7 @@ func (f *FindOptionsBuilder) SetCursorType(ct CursorType) *FindOptionsBuilder { // This should either be the index name as a string or the index specification as a document. // The driver will return an error if the hint parameter is a multi-key map. The default // value is nil, which means that no hint will be sent. -func (f *FindOptionsBuilder) SetHint(hint interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetHint(hint any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Hint = hint return nil @@ -137,7 +143,7 @@ func (f *FindOptionsBuilder) SetHint(hint interface{}) *FindOptionsBuilder { // for using this option. This must be a document mapping parameter names to values. Values // must be constant or closed expressions that do not reference document fields. Parameters // can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (f *FindOptionsBuilder) SetLet(let interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetLet(let any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Let = let return nil @@ -159,7 +165,7 @@ func (f *FindOptionsBuilder) SetLimit(i int64) *FindOptionsBuilder { // SetMax sets the value for the Max field. Max is a document specifying the exclusive upper bound // for a specific index. The default value is nil, which means that there is no maximum value. -func (f *FindOptionsBuilder) SetMax(max interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetMax(max any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Max = max return nil @@ -167,11 +173,11 @@ func (f *FindOptionsBuilder) SetMax(max interface{}) *FindOptionsBuilder { return f } -// SetMaxAwaitTime sets the value for the MaxAwaitTime field. MaxAwaitTime is the maximum amount of -// time that the server should wait for new documents to satisfy a tailable cursor query. This -// option is only valid for tailable await cursors (see the CursorType option for more information) -// and MongoDB versions >= 3.2. For other cursor types or previous server versions, this option -// is ignored. +// SetMaxAwaitTime sets the value for the MaxAwaitTime field. MaxAwaitTime is +// the maximum amount of time that the server should wait for new documents to +// satisfy a tailable cursor query. This option is only valid for tailable await +// cursors (see the CursorType option for more information). For other cursor +// types, this option is ignored. func (f *FindOptionsBuilder) SetMaxAwaitTime(d time.Duration) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.MaxAwaitTime = &d @@ -182,7 +188,7 @@ func (f *FindOptionsBuilder) SetMaxAwaitTime(d time.Duration) *FindOptionsBuilde // SetMin sets the value for the Min field. Min is a document specifying the inclusive lower bound // for a specific index. The default value is 0, which means that there is no minimum value. -func (f *FindOptionsBuilder) SetMin(min interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetMin(min any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Min = min return nil @@ -217,7 +223,7 @@ func (f *FindOptionsBuilder) SetOplogReplay(b bool) *FindOptionsBuilder { // SetProjection sets the value for the Projection field. Projection is a document describing // which fields will be included in the documents returned by the Find operation. The // default value is nil, which means all fields will be included. -func (f *FindOptionsBuilder) SetProjection(projection interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetProjection(projection any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Projection = projection return nil @@ -260,7 +266,7 @@ func (f *FindOptionsBuilder) SetSkip(i int64) *FindOptionsBuilder { // SetSort sets the value for the Sort field. Sort is a document specifying the order in which // documents should be returned. The sort parameter is evaluated sequentially, so the driver will // return an error if it is a multi-key map (which is unordeded). The default value is nil. -func (f *FindOptionsBuilder) SetSort(sort interface{}) *FindOptionsBuilder { +func (f *FindOptionsBuilder) SetSort(sort any) *FindOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOptions) error { opts.Sort = sort return nil @@ -275,16 +281,20 @@ func (f *FindOptionsBuilder) SetSort(sort interface{}) *FindOptionsBuilder { type FindOneOptions struct { AllowPartialResults *bool Collation *Collation - Comment interface{} - Hint interface{} - Max interface{} - Min interface{} + Comment any + Hint any + Max any + Min any OplogReplay *bool - Projection interface{} + Projection any ReturnKey *bool ShowRecordID *bool Skip *int64 - Sort interface{} + Sort any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // FindOneOptionsBuilder represents functional options that configure an @@ -314,10 +324,9 @@ func (f *FindOneOptionsBuilder) SetAllowPartialResults(b bool) *FindOneOptionsBu return f } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For -// previous server versions, the driver will return an error if this option is used. The -// default value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (f *FindOneOptionsBuilder) SetCollation(collation *Collation) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Collation = collation @@ -329,7 +338,7 @@ func (f *FindOneOptionsBuilder) SetCollation(collation *Collation) *FindOneOptio // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default is nil, which means that no comment will be included in the logs. -func (f *FindOneOptionsBuilder) SetComment(comment interface{}) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetComment(comment any) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Comment = &comment return nil @@ -341,7 +350,7 @@ func (f *FindOneOptionsBuilder) SetComment(comment interface{}) *FindOneOptionsB // This should either be the index name as a string or the index specification as a document. // The driver will return an error if the hint parameter is a multi-key map. The default value // is nil, which means that no hint will be sent. -func (f *FindOneOptionsBuilder) SetHint(hint interface{}) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetHint(hint any) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Hint = hint return nil @@ -351,7 +360,7 @@ func (f *FindOneOptionsBuilder) SetHint(hint interface{}) *FindOneOptionsBuilder // SetMax sets the value for the Max field. Sets a document specifying the exclusive upper bound // for a specific index. The default value is nil, which means that there is no maximum value. -func (f *FindOneOptionsBuilder) SetMax(max interface{}) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetMax(max any) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Max = max return nil @@ -361,7 +370,7 @@ func (f *FindOneOptionsBuilder) SetMax(max interface{}) *FindOneOptionsBuilder { // SetMin sets the value for the Min field. Sets a document specifying the inclusive lower bound // for a specific index. The default value is 0, which means that there is no minimum value. -func (f *FindOneOptionsBuilder) SetMin(min interface{}) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetMin(min any) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Min = min return nil @@ -385,7 +394,7 @@ func (f *FindOneOptionsBuilder) SetOplogReplay(b bool) *FindOneOptionsBuilder { // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneOptionsBuilder) SetProjection(projection interface{}) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetProjection(projection any) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Projection = projection return nil @@ -429,7 +438,7 @@ func (f *FindOneOptionsBuilder) SetSkip(i int64) *FindOneOptionsBuilder { // apply to the query. The first document in the sorted order will be returned. The sort // parameter is evaluated sequentially, so the driver will return an error if it is a multi- // key map (which is unordeded). The default value is nil. -func (f *FindOneOptionsBuilder) SetSort(sort interface{}) *FindOneOptionsBuilder { +func (f *FindOneOptionsBuilder) SetSort(sort any) *FindOneOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneOptions) error { opts.Sort = sort return nil @@ -444,13 +453,17 @@ func (f *FindOneOptionsBuilder) SetSort(sort interface{}) *FindOneOptionsBuilder type FindOneAndReplaceOptions struct { BypassDocumentValidation *bool Collation *Collation - Comment interface{} - Projection interface{} + Comment any + Projection any ReturnDocument *ReturnDocument - Sort interface{} + Sort any Upsert *bool - Hint interface{} - Let interface{} + Hint any + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // FindOneAndReplaceOptionsBuilder contains options to perform a findAndModify @@ -471,8 +484,7 @@ func (f *FindOneAndReplaceOptionsBuilder) List() []func(*FindOneAndReplaceOption } // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, writes -// executed as part of the operation will opt out of document-level validation on the server. This -// option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. The +// executed as part of the operation will opt out of document-level validation on the server. The // default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for more // information about document validation. func (f *FindOneAndReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *FindOneAndReplaceOptionsBuilder { @@ -485,10 +497,9 @@ func (f *FindOneAndReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *F return f } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. -// For previous server versions, the driver will return an error if this option is used. The -// default value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (f *FindOneAndReplaceOptionsBuilder) SetCollation(collation *Collation) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Collation = collation @@ -502,7 +513,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetCollation(collation *Collation) *Fi // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment interface{}) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment any) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Comment = comment @@ -515,7 +526,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetComment(comment interface{}) *FindO // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneAndReplaceOptionsBuilder) SetProjection(projection interface{}) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetProjection(projection any) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Projection = projection @@ -543,7 +554,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetReturnDocument(rd ReturnDocument) * // If set, the first document in the sorted order will be replaced. The sort parameter is evaluated // sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *FindOneAndReplaceOptionsBuilder) SetSort(sort interface{}) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetSort(sort any) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Sort = sort @@ -573,7 +584,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetUpsert(b bool) *FindOneAndReplaceOp // with during an unacknowledged write operation. The driver will return an error if the // hint parameter is a multi-key map. The default value is nil, which means that no hint // will be sent. -func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint interface{}) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint any) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Hint = hint @@ -589,7 +600,7 @@ func (f *FindOneAndReplaceOptionsBuilder) SetHint(hint interface{}) *FindOneAndR // parameter names to values. Values must be constant or closed expressions that do not // reference document fields. Parameters can then be accessed as variables in an // aggregate expression context (e.g. "$$var"). -func (f *FindOneAndReplaceOptionsBuilder) SetLet(let interface{}) *FindOneAndReplaceOptionsBuilder { +func (f *FindOneAndReplaceOptionsBuilder) SetLet(let any) *FindOneAndReplaceOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndReplaceOptions) error { opts.Let = let @@ -604,16 +615,20 @@ func (f *FindOneAndReplaceOptionsBuilder) SetLet(let interface{}) *FindOneAndRep // // See corresponding setter methods for documentation. type FindOneAndUpdateOptions struct { - ArrayFilters []interface{} + ArrayFilters []any BypassDocumentValidation *bool Collation *Collation - Comment interface{} - Projection interface{} + Comment any + Projection any ReturnDocument *ReturnDocument - Sort interface{} + Sort any Upsert *bool - Hint interface{} - Let interface{} + Hint any + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // FindOneAndUpdateOptionsBuilder contains options to configure a @@ -633,12 +648,11 @@ func (f *FindOneAndUpdateOptionsBuilder) List() []func(*FindOneAndUpdateOptions) return f.Opts } -// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a set of filters -// specifying to which array elements an update should apply. This option is only valid for -// MongoDB versions >= 3.6. For previous server versions, the driver will return an error if -// this option is used. The default value is nil, which means the update will apply to all -// array elements. -func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []interface{}) *FindOneAndUpdateOptionsBuilder { +// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a +// set of filters specifying to which array elements an update should apply. The +// default value is nil, which means the update will apply to all array +// elements. +func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []any) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.ArrayFilters = filters @@ -650,7 +664,6 @@ func (f *FindOneAndUpdateOptionsBuilder) SetArrayFilters(filters []interface{}) // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. -// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ // for more information about document validation. func (f *FindOneAndUpdateOptionsBuilder) SetBypassDocumentValidation(b bool) *FindOneAndUpdateOptionsBuilder { @@ -663,10 +676,9 @@ func (f *FindOneAndUpdateOptionsBuilder) SetBypassDocumentValidation(b bool) *Fi return f } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For -// previous server versions, the driver will return an error if this option is used. The default -// value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (f *FindOneAndUpdateOptionsBuilder) SetCollation(collation *Collation) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Collation = collation @@ -680,7 +692,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetCollation(collation *Collation) *Fin // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment interface{}) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment any) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Comment = comment @@ -693,7 +705,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetComment(comment interface{}) *FindOn // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneAndUpdateOptionsBuilder) SetProjection(projection interface{}) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetProjection(projection any) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Projection = projection @@ -721,7 +733,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetReturnDocument(rd ReturnDocument) *F // If set, the first document in the sorted order will be updated. The sort parameter is evaluated // sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *FindOneAndUpdateOptionsBuilder) SetSort(sort interface{}) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetSort(sort any) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Sort = sort @@ -751,7 +763,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetUpsert(b bool) *FindOneAndUpdateOpti // with during an unacknowledged write operation. The driver will return an error if the // hint parameter is a multi-key map. The default value is nil, which means that no hint // will be sent. -func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint interface{}) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint any) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Hint = hint @@ -767,7 +779,7 @@ func (f *FindOneAndUpdateOptionsBuilder) SetHint(hint interface{}) *FindOneAndUp // to values. Values must be constant or closed expressions that do not reference document // fields. Parameters can then be accessed as variables in an aggregate expression context // (e.g. "$$var"). -func (f *FindOneAndUpdateOptionsBuilder) SetLet(let interface{}) *FindOneAndUpdateOptionsBuilder { +func (f *FindOneAndUpdateOptionsBuilder) SetLet(let any) *FindOneAndUpdateOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndUpdateOptions) error { opts.Let = let @@ -783,11 +795,15 @@ func (f *FindOneAndUpdateOptionsBuilder) SetLet(let interface{}) *FindOneAndUpda // See corresponding setter methods for documentation. type FindOneAndDeleteOptions struct { Collation *Collation - Comment interface{} - Projection interface{} - Sort interface{} - Hint interface{} - Let interface{} + Comment any + Projection any + Sort any + Hint any + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // FindOneAndDeleteOptionsBuilder contains options to configure delete @@ -807,10 +823,9 @@ func (f *FindOneAndDeleteOptionsBuilder) List() []func(*FindOneAndDeleteOptions) return f.Opts } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. -// For previous server versions, the driver will return an error if this option is used. The -// default value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (f *FindOneAndDeleteOptionsBuilder) SetCollation(collation *Collation) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Collation = collation @@ -824,7 +839,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetCollation(collation *Collation) *Fin // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment interface{}) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment any) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Comment = comment @@ -837,7 +852,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetComment(comment interface{}) *FindOn // SetProjection sets the value for the Projection field. Sets a document describing which fields // will be included in the document returned by the operation. The default value is nil, which // means all fields will be included. -func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection interface{}) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection any) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Projection = projection @@ -852,7 +867,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetProjection(projection interface{}) * // If set, the first document in the sorted order will be deleted. The sort parameter is evaluated // sequentially, so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort interface{}) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort any) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Sort = sort @@ -869,7 +884,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetSort(sort interface{}) *FindOneAndDe // error if this option is specified. The driver will return an error if this option is used // with during an unacknowledged write operation. The driver will return an error if the hint // parameter is a multi-key map. The default value is nil, which means that no hint will be sent. -func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint interface{}) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint any) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Hint = hint @@ -884,7 +899,7 @@ func (f *FindOneAndDeleteOptionsBuilder) SetHint(hint interface{}) *FindOneAndDe // report an error for using this option. This must be a document mapping parameter names to // values. Values must be constant or closed expressions that do not reference document fields. // Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (f *FindOneAndDeleteOptionsBuilder) SetLet(let interface{}) *FindOneAndDeleteOptionsBuilder { +func (f *FindOneAndDeleteOptionsBuilder) SetLet(let any) *FindOneAndDeleteOptionsBuilder { f.Opts = append(f.Opts, func(opts *FindOneAndDeleteOptions) error { opts.Let = let diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go index 43af42b4..676596cb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/gridfsoptions.go @@ -123,7 +123,7 @@ func (b *BucketOptionsBuilder) SetReadPreference(rp *readpref.ReadPref) *BucketO // See corresponding setter methods for documentation. type GridFSUploadOptions struct { ChunkSizeBytes *int32 - Metadata interface{} + Metadata any Registry *bson.Registry } @@ -163,7 +163,7 @@ func (u *GridFSUploadOptionsBuilder) SetChunkSizeBytes(i int32) *GridFSUploadOpt // that will be stored in the "metadata" field of the document in the files collection. // The default value is nil, which means that the document in the files collection will // not contain a "metadata" field. -func (u *GridFSUploadOptionsBuilder) SetMetadata(doc interface{}) *GridFSUploadOptionsBuilder { +func (u *GridFSUploadOptionsBuilder) SetMetadata(doc any) *GridFSUploadOptionsBuilder { u.Opts = append(u.Opts, func(opts *GridFSUploadOptions) error { opts.Metadata = doc @@ -242,7 +242,7 @@ type GridFSFindOptions struct { Limit *int32 NoCursorTimeout *bool Skip *int32 - Sort interface{} + Sort any } // GridFSFindOptionsBuilder contains options to configure find operations. Each @@ -331,7 +331,7 @@ func (f *GridFSFindOptionsBuilder) SetSkip(i int32) *GridFSFindOptionsBuilder { // in which documents should be returned. The sort parameter is evaluated sequentially, // so the driver will return an error if it is a multi-key map (which is unordeded). // The default value is nil. -func (f *GridFSFindOptionsBuilder) SetSort(sort interface{}) *GridFSFindOptionsBuilder { +func (f *GridFSFindOptionsBuilder) SetSort(sort any) *GridFSFindOptionsBuilder { f.Opts = append(f.Opts, func(opts *GridFSFindOptions) error { opts.Sort = sort diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go index 48ddac0b..309a77ba 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/indexoptions.go @@ -6,12 +6,18 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // CreateIndexesOptions represents arguments that can be used to configure // IndexView.CreateOne and IndexView.CreateMany operations. // // See corresponding setter methods for documentation. type CreateIndexesOptions struct { - CommitQuorum interface{} + CommitQuorum any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // CreateIndexesOptionsBuilder contains options to create indexes. Each option @@ -121,7 +127,11 @@ func (c *CreateIndexesOptionsBuilder) SetCommitQuorumVotingMembers() *CreateInde // DropIndexesOptions represents arguments that can be used to configure // IndexView.DropOne and IndexView.DropAll operations. -type DropIndexesOptions struct{} +type DropIndexesOptions struct { + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options +} // DropIndexesOptionsBuilder contains options to configure dropping indexes. // Each option can be set through setter functions. See documentation for each @@ -146,6 +156,10 @@ func (d *DropIndexesOptionsBuilder) List() []func(*DropIndexesOptions) error { // See corresponding setter methods for documentation. type ListIndexesOptions struct { BatchSize *int32 + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // ListIndexesOptionsBuilder contains options to configure count operations. Each @@ -185,21 +199,21 @@ type IndexOptions struct { ExpireAfterSeconds *int32 Name *string Sparse *bool - StorageEngine interface{} + StorageEngine any Unique *bool Version *int32 DefaultLanguage *string LanguageOverride *string TextVersion *int32 - Weights interface{} + Weights any SphereVersion *int32 Bits *int32 Max *float64 Min *float64 BucketSize *int32 - PartialFilterExpression interface{} + PartialFilterExpression any Collation *Collation - WildcardProjection interface{} + WildcardProjection any Hidden *bool } @@ -262,9 +276,8 @@ func (i *IndexOptionsBuilder) SetSparse(sparse bool) *IndexOptionsBuilder { // SetStorageEngine sets the value for the StorageEngine field. Specifies the // storage engine to use for the index. The value must be a document in the form // {: }. The default value is nil, which means that -// the default storage engine will be used. This option is only applicable for -// MongoDB versions >= 3.0 and is ignored for previous server versions. -func (i *IndexOptionsBuilder) SetStorageEngine(engine interface{}) *IndexOptionsBuilder { +// the default storage engine will be used. +func (i *IndexOptionsBuilder) SetStorageEngine(engine any) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.StorageEngine = engine @@ -346,7 +359,7 @@ func (i *IndexOptionsBuilder) SetTextVersion(version int32) *IndexOptionsBuilder // terms of the score. This option is only applicable for text indexes and is ignored // for other index types. The default value is nil, which means that every field will // have a weight of 1. -func (i *IndexOptionsBuilder) SetWeights(weights interface{}) *IndexOptionsBuilder { +func (i *IndexOptionsBuilder) SetWeights(weights any) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.Weights = weights @@ -424,9 +437,8 @@ func (i *IndexOptionsBuilder) SetBucketSize(bucketSize int32) *IndexOptionsBuild } // SetPartialFilterExpression sets the value for the PartialFilterExpression field. Sets -// a document that defines which collection documents the index should reference. This -// option is only valid for MongoDB versions >= 3.2 and is ignored for previous server versions. -func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression interface{}) *IndexOptionsBuilder { +// a document that defines which collection documents the index should reference. +func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression any) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.PartialFilterExpression = expression @@ -437,8 +449,7 @@ func (i *IndexOptionsBuilder) SetPartialFilterExpression(expression interface{}) } // SetCollation sets the value for the Collation field. Specifies the collation to use for -// string comparisons for the index. This option is only valid for MongoDB versions >= 3.4. -// For previous server versions, the driver will return an error if this option is used. +// string comparisons for the index. func (i *IndexOptionsBuilder) SetCollation(collation *Collation) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.Collation = collation @@ -451,7 +462,7 @@ func (i *IndexOptionsBuilder) SetCollation(collation *Collation) *IndexOptionsBu // SetWildcardProjection sets the value for the WildcardProjection field. Sets a document // that defines the wildcard projection for the index. -func (i *IndexOptionsBuilder) SetWildcardProjection(wildcardProjection interface{}) *IndexOptionsBuilder { +func (i *IndexOptionsBuilder) SetWildcardProjection(wildcardProjection any) *IndexOptionsBuilder { i.Opts = append(i.Opts, func(opts *IndexOptions) error { opts.WildcardProjection = wildcardProjection diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go index 43b87470..532f2850 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/insertoptions.go @@ -6,13 +6,19 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // InsertOneOptions represents arguments that can be used to configure an InsertOne // operation. // // See corresponding setter methods for documentation. type InsertOneOptions struct { BypassDocumentValidation *bool - Comment interface{} + Comment any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // InsertOneOptionsBuilder represents functional options that configure an @@ -33,8 +39,7 @@ func (ioo *InsertOneOptionsBuilder) List() []func(*InsertOneOptions) error { // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the -// server. This option is valid for MongoDB versions >= 3.2 and is ignored for previous server -// versions. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ +// server. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ // for more information about document validation. func (ioo *InsertOneOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertOneOptionsBuilder { ioo.Opts = append(ioo.Opts, func(opts *InsertOneOptions) error { @@ -46,7 +51,7 @@ func (ioo *InsertOneOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertO // SetComment sets the value for the Comment field. Specifies a string or document that will be included in server logs, profiling logs, and currentOp queries to help trace // the operation. The default value is nil, which means that no comment will be included in the logs. -func (ioo *InsertOneOptionsBuilder) SetComment(comment interface{}) *InsertOneOptionsBuilder { +func (ioo *InsertOneOptionsBuilder) SetComment(comment any) *InsertOneOptionsBuilder { ioo.Opts = append(ioo.Opts, func(opts *InsertOneOptions) error { opts.Comment = &comment return nil @@ -60,8 +65,12 @@ func (ioo *InsertOneOptionsBuilder) SetComment(comment interface{}) *InsertOneOp // See corresponding setter methods for documentation. type InsertManyOptions struct { BypassDocumentValidation *bool - Comment interface{} + Comment any Ordered *bool + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // InsertManyOptionsBuilder contains options to configure insert operations. @@ -86,8 +95,7 @@ func (imo *InsertManyOptionsBuilder) List() []func(*InsertManyOptions) error { // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the -// server. This option is valid for MongoDB versions >= 3.2 and is ignored for previous server -// versions. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ +// server. The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ // for more information about document validation. func (imo *InsertManyOptionsBuilder) SetBypassDocumentValidation(b bool) *InsertManyOptionsBuilder { imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error { @@ -102,7 +110,7 @@ func (imo *InsertManyOptionsBuilder) SetBypassDocumentValidation(b bool) *Insert // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (imo *InsertManyOptionsBuilder) SetComment(comment interface{}) *InsertManyOptionsBuilder { +func (imo *InsertManyOptionsBuilder) SetComment(comment any) *InsertManyOptionsBuilder { imo.Opts = append(imo.Opts, func(opts *InsertManyOptions) error { opts.Comment = comment diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go index 2106b2f9..14f96cc6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/listcollectionsoptions.go @@ -6,6 +6,8 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // ListCollectionsOptions represents arguments that can be used to configure a // ListCollections operation. // @@ -14,6 +16,10 @@ type ListCollectionsOptions struct { NameOnly *bool BatchSize *int32 AuthorizedCollections *bool + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // ListCollectionsOptionsBuilder contains options to configure list collection diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go index 3a5c0806..0eb7ce42 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/loggeroptions.go @@ -63,10 +63,10 @@ type LogSink interface { // // "Level V(0) is the default, and logger.V(0).Info() has the same // meaning as logger.Info()." - Info(level int, message string, keysAndValues ...interface{}) + Info(level int, message string, keysAndValues ...any) // Error logs an error message with the given key/value pairs - Error(err error, message string, keysAndValues ...interface{}) + Error(err error, message string, keysAndValues ...any) } // LoggerOptions represent arguments used to configure Logging in the Go Driver. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go index 0416d071..794a77eb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/replaceoptions.go @@ -6,6 +6,8 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // ReplaceOptions represents arguments that can be used to configure a ReplaceOne // operation. // @@ -13,11 +15,15 @@ package options type ReplaceOptions struct { BypassDocumentValidation *bool Collation *Collation - Comment interface{} - Hint interface{} + Comment any + Hint any Upsert *bool - Let interface{} - Sort interface{} + Let any + Sort any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // ReplaceOptionsBuilder contains options to configure replace operations. Each @@ -39,7 +45,6 @@ func (ro *ReplaceOptionsBuilder) List() []func(*ReplaceOptions) error { // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. -// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for // more information about document validation. func (ro *ReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *ReplaceOptionsBuilder { @@ -52,10 +57,9 @@ func (ro *ReplaceOptionsBuilder) SetBypassDocumentValidation(b bool) *ReplaceOpt return ro } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For -// previous server versions, the driver will return an error if this option is used. The -// default value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (ro *ReplaceOptionsBuilder) SetCollation(c *Collation) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Collation = c @@ -69,7 +73,7 @@ func (ro *ReplaceOptionsBuilder) SetCollation(c *Collation) *ReplaceOptionsBuild // SetComment sets the value for the Comment field. Specifies a string or document that will // be included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (ro *ReplaceOptionsBuilder) SetComment(comment interface{}) *ReplaceOptionsBuilder { +func (ro *ReplaceOptionsBuilder) SetComment(comment any) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Comment = comment @@ -79,15 +83,15 @@ func (ro *ReplaceOptionsBuilder) SetComment(comment interface{}) *ReplaceOptions return ro } -// SetHint sets the value for the Hint field. Specifies the index to use for the operation. -// This should either be the index name as a string or the index specification as a document. -// This option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return -// an error if this option is specified. For server versions < 3.4, the driver will return a -// client-side error if this option is specified. The driver will return an error if this option -// is specified during an unacknowledged write operation. The driver will return an error if -// the hint parameter is a multi-key map. The default value is nil, which means that no hint -// will be sent. -func (ro *ReplaceOptionsBuilder) SetHint(h interface{}) *ReplaceOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the +// operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions +// >= 4.2. Server versions < 4.2 will return an error if this option is +// specified. The driver will return an error if this option is specified during +// an unacknowledged write operation. The driver will return an error if the +// hint parameter is a multi-key map. The default value is nil, which means that +// no hint will be sent. +func (ro *ReplaceOptionsBuilder) SetHint(h any) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Hint = h @@ -114,7 +118,7 @@ func (ro *ReplaceOptionsBuilder) SetUpsert(b bool) *ReplaceOptionsBuilder { // for using this option. This must be a document mapping parameter names to values. Values // must be constant or closed expressions that do not reference document fields. Parameters // can then be accessed as variables in an aggregate expression context (e.g. "$$var"). -func (ro *ReplaceOptionsBuilder) SetLet(l interface{}) *ReplaceOptionsBuilder { +func (ro *ReplaceOptionsBuilder) SetLet(l any) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Let = l @@ -129,7 +133,7 @@ func (ro *ReplaceOptionsBuilder) SetLet(l interface{}) *ReplaceOptionsBuilder { // set, the first document in the sorted order will be replaced. This option is only valid for MongoDB // versions >= 8.0. The sort parameter is evaluated sequentially, so the driver will return an error // if it is a multi-key map (which is unordeded). The default value is nil. -func (ro *ReplaceOptionsBuilder) SetSort(s interface{}) *ReplaceOptionsBuilder { +func (ro *ReplaceOptionsBuilder) SetSort(s any) *ReplaceOptionsBuilder { ro.Opts = append(ro.Opts, func(opts *ReplaceOptions) error { opts.Sort = s diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go index 08d5bfc1..3dab855f 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/rewrapdatakeyoptions.go @@ -12,7 +12,7 @@ package options // See corresponding setter methods for documentation. type RewrapManyDataKeyOptions struct { Provider *string - MasterKey interface{} + MasterKey any } // RewrapManyDataKeyOptionsBuilder contains options to configure rewraping a @@ -46,7 +46,7 @@ func (rmdko *RewrapManyDataKeyOptionsBuilder) SetProvider(provider string) *Rewr // SetMasterKey sets the value for the MasterKey field. MasterKey identifies the new masterKey. // If omitted, rewraps with the current masterKey. -func (rmdko *RewrapManyDataKeyOptionsBuilder) SetMasterKey(masterKey interface{}) *RewrapManyDataKeyOptionsBuilder { +func (rmdko *RewrapManyDataKeyOptionsBuilder) SetMasterKey(masterKey any) *RewrapManyDataKeyOptionsBuilder { rmdko.Opts = append(rmdko.Opts, func(opts *RewrapManyDataKeyOptions) error { opts.MasterKey = masterKey diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go index bbf721b2..c5d15b7a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/options/updateoptions.go @@ -6,19 +6,25 @@ package options +import "go.mongodb.org/mongo-driver/v2/internal/optionsutil" + // UpdateOneOptions represents arguments that can be used to configure UpdateOne // operations. // // See corresponding setter methods for documentation. type UpdateOneOptions struct { - ArrayFilters []interface{} + ArrayFilters []any BypassDocumentValidation *bool Collation *Collation - Comment interface{} - Hint interface{} + Comment any + Hint any Upsert *bool - Let interface{} - Sort interface{} + Let any + Sort any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // UpdateOneOptionsBuilder contains options to configure UpdateOne operations. @@ -38,11 +44,11 @@ func (uo *UpdateOneOptionsBuilder) List() []func(*UpdateOneOptions) error { return uo.Opts } -// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a set of filters -// specifying to which array elements an update should apply. This option is only valid for MongoDB -// versions >= 3.6. For previous server versions, the driver will return an error if this option is -// used. The default value is nil, which means the update will apply to all array elements. -func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []interface{}) *UpdateOneOptionsBuilder { +// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a +// set of filters specifying to which array elements an update should apply. The +// default value is nil, which means the update will apply to all array +// elements. +func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []any) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.ArrayFilters = af @@ -54,7 +60,6 @@ func (uo *UpdateOneOptionsBuilder) SetArrayFilters(af []interface{}) *UpdateOneO // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. -// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for // more information about document validation. func (uo *UpdateOneOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateOneOptionsBuilder { @@ -67,10 +72,9 @@ func (uo *UpdateOneOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateOn return uo } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For -// previous server versions, the driver will return an error if this option is used. The default -// value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (uo *UpdateOneOptionsBuilder) SetCollation(c *Collation) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Collation = c @@ -84,7 +88,7 @@ func (uo *UpdateOneOptionsBuilder) SetCollation(c *Collation) *UpdateOneOptionsB // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (uo *UpdateOneOptionsBuilder) SetComment(comment interface{}) *UpdateOneOptionsBuilder { +func (uo *UpdateOneOptionsBuilder) SetComment(comment any) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Comment = comment @@ -94,14 +98,15 @@ func (uo *UpdateOneOptionsBuilder) SetComment(comment interface{}) *UpdateOneOpt return uo } -// SetHint sets the value for the Hint field. Specifies the index to use for the operation. This -// should either be the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error -// if this option is specified. For server versions < 3.4, the driver will return a client-side -// error if this option is specified. The driver will return an error if this option is specified -// during an unacknowledged write operation. The driver will return an error if the hint parameter -// is a multi-key map. The default value is nil, which means that no hint will be sent. -func (uo *UpdateOneOptionsBuilder) SetHint(h interface{}) *UpdateOneOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the +// operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions +// >= 4.2. Server versions < 4.2 will return an error if this option is +// specified. The driver will return an error if this option is specified during +// an unacknowledged write operation. The driver will return an error if the +// hint parameter is a multi-key map. The default value is nil, which means that +// no hint will be sent. +func (uo *UpdateOneOptionsBuilder) SetHint(h any) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Hint = h @@ -128,7 +133,7 @@ func (uo *UpdateOneOptionsBuilder) SetUpsert(b bool) *UpdateOneOptionsBuilder { // this option. This must be a document mapping parameter names to values. Values must be constant // or closed expressions that do not reference document fields. Parameters can then be accessed // as variables in an aggregate expression context (e.g. "$$var"). -func (uo *UpdateOneOptionsBuilder) SetLet(l interface{}) *UpdateOneOptionsBuilder { +func (uo *UpdateOneOptionsBuilder) SetLet(l any) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Let = l @@ -143,7 +148,7 @@ func (uo *UpdateOneOptionsBuilder) SetLet(l interface{}) *UpdateOneOptionsBuilde // set, the first document in the sorted order will be updated. This option is only valid for MongoDB // versions >= 8.0. The sort parameter is evaluated sequentially, so the driver will return an error // if it is a multi-key map (which is unordeded). The default value is nil. -func (uo *UpdateOneOptionsBuilder) SetSort(s interface{}) *UpdateOneOptionsBuilder { +func (uo *UpdateOneOptionsBuilder) SetSort(s any) *UpdateOneOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateOneOptions) error { opts.Sort = s @@ -158,13 +163,17 @@ func (uo *UpdateOneOptionsBuilder) SetSort(s interface{}) *UpdateOneOptionsBuild // // See corresponding setter methods for documentation. type UpdateManyOptions struct { - ArrayFilters []interface{} + ArrayFilters []any BypassDocumentValidation *bool Collation *Collation - Comment interface{} - Hint interface{} + Comment any + Hint any Upsert *bool - Let interface{} + Let any + + // Deprecated: This option is for internal use only and should not be set. It may be changed or removed in any + // release. + Internal optionsutil.Options } // UpdateManyOptionsBuilder contains options to configure UpdateMany operations. @@ -184,11 +193,11 @@ func (uo *UpdateManyOptionsBuilder) List() []func(*UpdateManyOptions) error { return uo.Opts } -// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a set of filters -// specifying to which array elements an update should apply. This option is only valid for MongoDB -// versions >= 3.6. For previous server versions, the driver will return an error if this option is -// used. The default value is nil, which means the update will apply to all array elements. -func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []interface{}) *UpdateManyOptionsBuilder { +// SetArrayFilters sets the value for the ArrayFilters field. ArrayFilters is a +// set of filters specifying to which array elements an update should apply. The +// default value is nil, which means the update will apply to all array +// elements. +func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []any) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.ArrayFilters = af @@ -200,7 +209,6 @@ func (uo *UpdateManyOptionsBuilder) SetArrayFilters(af []interface{}) *UpdateMan // SetBypassDocumentValidation sets the value for the BypassDocumentValidation field. If true, // writes executed as part of the operation will opt out of document-level validation on the server. -// This option is valid for MongoDB versions >= 3.2 and is ignored for previous server versions. // The default value is false. See https://www.mongodb.com/docs/manual/core/schema-validation/ for // more information about document validation. func (uo *UpdateManyOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateManyOptionsBuilder { @@ -213,10 +221,9 @@ func (uo *UpdateManyOptionsBuilder) SetBypassDocumentValidation(b bool) *UpdateM return uo } -// SetCollation sets the value for the Collation field. Specifies a collation to use for string -// comparisons during the operation. This option is only valid for MongoDB versions >= 3.4. For -// previous server versions, the driver will return an error if this option is used. The default -// value is nil, which means the default collation of the collection will be used. +// SetCollation sets the value for the Collation field. Specifies a collation to +// use for string comparisons during the operation. The default value is nil, +// which means the default collation of the collection will be used. func (uo *UpdateManyOptionsBuilder) SetCollation(c *Collation) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Collation = c @@ -230,7 +237,7 @@ func (uo *UpdateManyOptionsBuilder) SetCollation(c *Collation) *UpdateManyOption // SetComment sets the value for the Comment field. Specifies a string or document that will be // included in server logs, profiling logs, and currentOp queries to help trace the operation. // The default value is nil, which means that no comment will be included in the logs. -func (uo *UpdateManyOptionsBuilder) SetComment(comment interface{}) *UpdateManyOptionsBuilder { +func (uo *UpdateManyOptionsBuilder) SetComment(comment any) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Comment = comment @@ -240,14 +247,15 @@ func (uo *UpdateManyOptionsBuilder) SetComment(comment interface{}) *UpdateManyO return uo } -// SetHint sets the value for the Hint field. Specifies the index to use for the operation. This -// should either be the index name as a string or the index specification as a document. This -// option is only valid for MongoDB versions >= 4.2. Server versions >= 3.4 will return an error -// if this option is specified. For server versions < 3.4, the driver will return a client-side -// error if this option is specified. The driver will return an error if this option is specified -// during an unacknowledged write operation. The driver will return an error if the hint parameter -// is a multi-key map. The default value is nil, which means that no hint will be sent. -func (uo *UpdateManyOptionsBuilder) SetHint(h interface{}) *UpdateManyOptionsBuilder { +// SetHint sets the value for the Hint field. Specifies the index to use for the +// operation. This should either be the index name as a string or the index +// specification as a document. This option is only valid for MongoDB versions +// >= 4.2. Server versions < 4.2 will return an error if this option is +// specified. The driver will return an error if this option is specified during +// an unacknowledged write operation. The driver will return an error if the +// hint parameter is a multi-key map. The default value is nil, which means that +// no hint will be sent. +func (uo *UpdateManyOptionsBuilder) SetHint(h any) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Hint = h @@ -274,7 +282,7 @@ func (uo *UpdateManyOptionsBuilder) SetUpsert(b bool) *UpdateManyOptionsBuilder // this option. This must be a document mapping parameter names to values. Values must be constant // or closed expressions that do not reference document fields. Parameters can then be accessed // as variables in an aggregate expression context (e.g. "$$var"). -func (uo *UpdateManyOptionsBuilder) SetLet(l interface{}) *UpdateManyOptionsBuilder { +func (uo *UpdateManyOptionsBuilder) SetLet(l any) *UpdateManyOptionsBuilder { uo.Opts = append(uo.Opts, func(opts *UpdateManyOptions) error { opts.Let = l diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go index f4671d5d..5cd9c9f6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/options.go @@ -71,10 +71,15 @@ func WithTagSets(tagSets ...tag.Set) Option { } } -// WithHedgeEnabled specifies whether or not hedged reads should be enabled in the server. This feature requires MongoDB -// server version 4.4 or higher. For more information about hedged reads, see -// https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/#mongos-hedged-reads. If not specified, the default -// is to not send a value to the server, which will result in the server defaults being used. +// WithHedgeEnabled specifies whether or not hedged reads should be enabled in +// the server. This feature requires MongoDB server version 4.4 or higher. For +// more information about hedged reads, see +// https://www.mongodb.com/docs/manual/core/sharded-cluster-query-router/#mongos-hedged-reads. +// If not specified, the default is to not send a value to the server, which +// will result in the server defaults being used. +// +// Deprecated: Hedged reads are deprecated in MongoDB 8.0 and may be removed in +// a future MongoDB version. func WithHedgeEnabled(hedgeEnabled bool) Option { return func(rp *ReadPref) error { rp.hedgeEnabled = &hedgeEnabled diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go index 47e5b0cb..5f2320e2 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/readpref/readpref.go @@ -103,8 +103,12 @@ func (r *ReadPref) TagSets() []tag.Set { return r.tagSets } -// HedgeEnabled returns whether or not hedged reads are enabled for this read preference. If this option was not -// specified during read preference construction, nil is returned. +// HedgeEnabled returns whether or not hedged reads are enabled for this read +// preference. If this option was not specified during read preference +// construction, nil is returned. +// +// Deprecated: Hedged reads are deprecated in MongoDB 8.0 and may be removed in +// a future MongoDB version. func (r *ReadPref) HedgeEnabled() *bool { return r.hedgeEnabled } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go index d8407ef5..e50157e6 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/results.go @@ -50,14 +50,14 @@ type ClientBulkWriteResult struct { // ClientBulkWriteInsertResult is the result type returned by a client-level bulk write of InsertOne operation. type ClientBulkWriteInsertResult struct { // The _id of the inserted document. A value generated by the driver will be of type primitive.ObjectID. - InsertedID interface{} + InsertedID any } // ClientBulkWriteUpdateResult is the result type returned from a client-level bulk write of UpdateOne, UpdateMany, and ReplaceOne operation. type ClientBulkWriteUpdateResult struct { - MatchedCount int64 // The number of documents matched by the filter. - ModifiedCount int64 // The number of documents modified by the operation. - UpsertedID interface{} // The _id field of the upserted document, or nil if no upsert was done. + MatchedCount int64 // The number of documents matched by the filter. + ModifiedCount int64 // The number of documents modified by the operation. + UpsertedID any // The _id field of the upserted document, or nil if no upsert was done. } // ClientBulkWriteDeleteResult is the result type returned by a client-level bulk write DeleteOne and DeleteMany operation. @@ -83,7 +83,7 @@ type BulkWriteResult struct { UpsertedCount int64 // A map of operation index to the _id of each upserted document. - UpsertedIDs map[int64]interface{} + UpsertedIDs map[int64]any // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -93,7 +93,7 @@ type BulkWriteResult struct { // InsertOneResult is the result type returned by an InsertOne operation. type InsertOneResult struct { // The _id of the inserted document. A value generated by the driver will be of type bson.ObjectID. - InsertedID interface{} + InsertedID any // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -103,7 +103,7 @@ type InsertOneResult struct { // InsertManyResult is a result type returned by an InsertMany operation. type InsertManyResult struct { // The _id values of the inserted documents. Values generated by the driver will be of type bson.ObjectID. - InsertedIDs []interface{} + InsertedIDs []any // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -159,10 +159,10 @@ type DatabaseSpecification struct { // UpdateResult is the result type returned from UpdateOne, UpdateMany, and ReplaceOne operations. type UpdateResult struct { - MatchedCount int64 // The number of documents matched by the filter. - ModifiedCount int64 // The number of documents modified by the operation. - UpsertedCount int64 // The number of documents upserted by the operation. - UpsertedID interface{} // The _id field of the upserted document, or nil if no upsert was done. + MatchedCount int64 // The number of documents matched by the filter. + ModifiedCount int64 // The number of documents modified by the operation. + UpsertedCount int64 // The number of documents upserted by the operation. + UpsertedID any // The _id field of the upserted document, or nil if no upsert was done. // Operation performed with an acknowledged write. Values for other fields may // not be deterministic if the write operation was unacknowledged. @@ -220,11 +220,10 @@ type CollectionSpecification struct { // The type of the collection. This will either be "collection" or "view". Type string - // Whether or not the collection is readOnly. This will be false for MongoDB versions < 3.4. + // Whether or not the collection is readOnly. ReadOnly bool - // The collection UUID. This field will be nil for MongoDB versions < 3.6. For versions 3.6 and higher, this will - // be a bson.Binary with Subtype 4. + // The collection UUID as a bson.Binary with subtype 4. UUID *bson.Binary // A document containing the options used to construct the collection. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go index f62e4769..5df3b8fb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/search_index_view.go @@ -8,6 +8,7 @@ package mongo import ( "context" + "errors" "fmt" "strconv" @@ -36,7 +37,7 @@ type SearchIndexView struct { type SearchIndexModel struct { // A document describing the definition for the search index. It cannot be nil. // See https://www.mongodb.com/docs/atlas/atlas-search/create-index/ for reference. - Definition interface{} + Definition any // The search index options. Options *options.SearchIndexesOptionsBuilder @@ -229,7 +230,8 @@ func (siv SearchIndexView) DropOne( Timeout(siv.coll.client.timeout).Authenticator(siv.coll.client.authenticator) err = op.Execute(ctx) - if de, ok := err.(driver.Error); ok && de.NamespaceNotFound() { + var de driver.Error + if errors.As(err, &de) && de.NamespaceNotFound() { return nil } return err @@ -248,7 +250,7 @@ func (siv SearchIndexView) DropOne( func (siv SearchIndexView) UpdateOne( ctx context.Context, name string, - definition interface{}, + definition any, _ ...options.Lister[options.UpdateSearchIndexOptions], ) error { if definition == nil { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go index fb4da5bb..db08f125 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/session.go @@ -126,9 +126,9 @@ func (s *Session) EndSession(ctx context.Context) { // see the Client.StartSession method documentation. func (s *Session) WithTransaction( ctx context.Context, - fn func(ctx context.Context) (interface{}, error), + fn func(ctx context.Context) (any, error), opts ...options.Lister[options.TransactionOptions], -) (interface{}, error) { +) (any, error) { timeout := time.NewTimer(withTransactionTimeout) defer timeout.Stop() var err error @@ -193,7 +193,8 @@ func (s *Session) WithTransaction( default: } - if cerr, ok := err.(CommandError); ok { + var cerr CommandError + if errors.As(err, &cerr) { if cerr.HasErrorLabel(driver.UnknownTransactionCommitResult) && !cerr.IsMaxTimeMSExpiredError() { continue } @@ -291,7 +292,7 @@ func (s *Session) CommitTransaction(ctx context.Context) error { // Return error without updating transaction state if it is a timeout, as the transaction has not // actually been committed. if IsTimeout(err) { - return replaceErrors(err) + return wrapErrors(err) } s.clientSession.Committing = false commitErr := s.clientSession.CommitTransaction() @@ -300,7 +301,7 @@ func (s *Session) CommitTransaction(ctx context.Context) error { s.clientSession.UpdateCommitTransactionWriteConcern() if err != nil { - return replaceErrors(err) + return wrapErrors(err) } return commitErr } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go index 40b5a5c5..5cae2984 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/single_result.go @@ -41,7 +41,7 @@ type SingleResult struct { // // The document parameter must be a non-nil document. func NewSingleResultFromDocument( - document interface{}, + document any, err error, registry *bson.Registry, ) *SingleResult { @@ -52,7 +52,7 @@ func NewSingleResultFromDocument( registry = defaultRegistry } - cur, createErr := NewCursorFromDocuments([]interface{}{document}, err, registry) + cur, createErr := NewCursorFromDocuments([]any{document}, err, registry) if createErr != nil { return &SingleResult{err: createErr} } @@ -70,7 +70,7 @@ func NewSingleResultFromDocument( // // If the operation was successful and returned a document, Decode will return any errors from the unmarshalling process // without any modification. If v is nil or is a typed nil, an error will be returned. -func (sr *SingleResult) Decode(v interface{}) error { +func (sr *SingleResult) Decode(v any) error { if sr.err != nil { return sr.err } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go b/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go index 00e60e1c..208f230e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/mongo/writeconcern/writeconcern.go @@ -36,7 +36,7 @@ type WriteConcern struct { // // For more information about the "w" option, see // https://www.mongodb.com/docs/manual/reference/write-concern/#w-option - W interface{} + W any // Journal requests acknowledgment from MongoDB that the write operation has // been written to the on-disk journal. It sets the "j" option in a MongoDB diff --git a/vendor/go.mongodb.org/mongo-driver/v2/version/version.go b/vendor/go.mongodb.org/mongo-driver/v2/version/version.go index be3f65c3..2b483845 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/version/version.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/version/version.go @@ -11,4 +11,4 @@ package version // Driver is the current version of the driver. -var Driver = "2.1.0" +var Driver = "2.3.1" diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go index 0efbdc0f..bfedbc86 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/array.go @@ -9,7 +9,6 @@ package bsoncore import ( "fmt" "io" - "math" "strconv" "strings" ) @@ -83,55 +82,79 @@ func (a Array) DebugString() string { // String outputs an ExtendedJSON version of Array. If the Array is not valid, this method // returns an empty string. func (a Array) String() string { - return a.StringN(math.MaxInt) + str, _ := a.StringN(-1) + return str } -// StringN stringifies an array upto N bytes -func (a Array) StringN(n int) string { - if lens, _, _ := ReadLength(a); lens < 5 || n <= 0 { - return "" +// StringN stringifies an array. If N is non-negative, it will truncate the string to N bytes. +// Otherwise, it will return the full string representation. The second return value indicates +// whether the string was truncated or not. +func (a Array) StringN(n int) (string, bool) { + length, rem, ok := ReadLength(a) + if !ok || length < 5 { + return "", false + } + length -= 4 // length bytes + length-- // final null byte + + if n == 0 { + return "", true } var buf strings.Builder buf.WriteByte('[') - length, rem, _ := ReadLength(a) // We know we have enough bytes to read the length - length -= 4 - + var truncated bool var elem Element - var ok bool - - if n > 0 { - for length > 1 { - elem, rem, ok = ReadElement(rem) - - length -= int32(len(elem)) - if !ok { - return "" - } - - str := elem.Value().StringN(n - buf.Len()) - - buf.WriteString(str) - - if buf.Len() == n { - return buf.String() + var str string + first := true + for length > 0 && !truncated { + needStrLen := -1 + // Set needStrLen if n is positive, meaning we want to limit the string length. + if n > 0 { + // Stop stringifying if we reach the limit, that also ensures needStrLen is + // greater than 0 if we need to limit the length. + if buf.Len() >= n { + truncated = true + break } + needStrLen = n - buf.Len() + } - if length > 1 { - buf.WriteByte(',') + // Append a comma if this is not the first element. + if !first { + buf.WriteByte(',') + // If we are truncating, we need to account for the comma in the length. + if needStrLen > 0 { + needStrLen-- + if needStrLen == 0 { + truncated = true + break + } } } - if length != 1 { // Missing final null byte or inaccurate length - return "" + + elem, rem, ok = ReadElement(rem) + length -= int32(len(elem)) + // Exit on malformed element. + if !ok || length < 0 { + return "", false } + + // Delegate to StringN() on the element. + str, truncated = elem.Value().StringN(needStrLen) + buf.WriteString(str) + + first = false } - if buf.Len()+1 <= n { + if n <= 0 || (buf.Len() < n && !truncated) { buf.WriteByte(']') + } else { + truncated = true } - return buf.String() + return buf.String(), truncated } // Values returns this array as a slice of values. The returned slice will contain valid values. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go index 6a59908d..03e78e59 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/document.go @@ -10,11 +10,8 @@ import ( "errors" "fmt" "io" - "math" "strconv" "strings" - - "go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil" ) // ValidationError is an error type returned when attempting to validate a document or array. @@ -264,58 +261,79 @@ func (d Document) DebugString() string { // String outputs an ExtendedJSON version of Document. If the document is not valid, this method // returns an empty string. func (d Document) String() string { - return d.StringN(math.MaxInt) + str, _ := d.StringN(-1) + return str } -// StringN stringifies a document upto N bytes -func (d Document) StringN(n int) string { - if len(d) < 5 || n <= 0 { - return "" +// StringN stringifies a document. If N is non-negative, it will truncate the string to N bytes. +// Otherwise, it will return the full string representation. The second return value indicates +// whether the string was truncated or not. +func (d Document) StringN(n int) (string, bool) { + length, rem, ok := ReadLength(d) + if !ok || length < 5 { + return "", false } + length -= 4 // length bytes + length-- // final null byte - var buf strings.Builder + if n == 0 { + return "", true + } + var buf strings.Builder buf.WriteByte('{') - length, rem, _ := ReadLength(d) - length -= 4 - + var truncated bool var elem Element - var ok bool - + var str string first := true - truncated := false - - if n > 0 { - for length > 1 { - if !first { - buf.WriteByte(',') - } - elem, rem, ok = ReadElement(rem) - length -= int32(len(elem)) - if !ok { - return "" - } - - str := elem.StringN(n) - if buf.Len()+len(str) > n { - truncatedStr := bsoncoreutil.Truncate(str, n-buf.Len()) - buf.WriteString(truncatedStr) - + for length > 0 && !truncated { + needStrLen := -1 + // Set needStrLen if n is positive, meaning we want to limit the string length. + if n > 0 { + // Stop stringifying if we reach the limit, that also ensures needStrLen is + // greater than 0 if we need to limit the length. + if buf.Len() >= n { truncated = true break } + needStrLen = n - buf.Len() + } + + // Append a comma if this is not the first element. + if !first { + buf.WriteByte(',') + // If we are truncating, we need to account for the comma in the length. + if needStrLen > 0 { + needStrLen-- + if needStrLen == 0 { + truncated = true + break + } + } + } - buf.WriteString(str) - first = false + elem, rem, ok = ReadElement(rem) + length -= int32(len(elem)) + // Exit on malformed element. + if !ok || length < 0 { + return "", false } + + // Delegate to StringN() on the element. + str, truncated = elem.StringN(needStrLen) + buf.WriteString(str) + + first = false } - if !truncated { + if n <= 0 || (buf.Len() < n && !truncated) { buf.WriteByte('}') + } else { + truncated = true } - return buf.String() + return buf.String(), truncated } // Elements returns this document as a slice of elements. The returned slice will contain valid diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go index dcb5e86e..4214e5a7 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/element.go @@ -9,7 +9,9 @@ package bsoncore import ( "bytes" "fmt" - "math" + "strings" + + "go.mongodb.org/mongo-driver/v2/internal/bsoncoreutil" ) // MalformedElementError represents a class of errors that RawElement methods return. @@ -115,35 +117,80 @@ func (e Element) ValueErr() (Value, error) { // String implements the fmt.String interface. The output will be in extended JSON format. func (e Element) String() string { - return e.StringN(math.MaxInt) + str, _ := e.StringN(-1) + return str } -// StringN implements the fmt.String interface for upto N bytes. The output will be in extended JSON format. -func (e Element) StringN(n int) string { +// StringN will return values in extended JSON format that will stringify an element upto N bytes. +// If N is non-negative, it will truncate the string to N bytes. Otherwise, it will return the full +// string representation. The second return value indicates whether the string was truncated or not. +// If the element is not valid, this returns an empty string +func (e Element) StringN(n int) (string, bool) { if len(e) == 0 { - return "" + return "", false + } + if n == 0 { + return "", true } + if n == 1 { + return `"`, true + } + t := Type(e[0]) idx := bytes.IndexByte(e[1:], 0x00) - if idx == -1 { - return "" - } - key, valBytes := []byte(e[1:idx+1]), []byte(e[idx+2:]) - val, _, valid := ReadValue(valBytes, t) + if idx <= 0 { + return "", false + } + key := e[1 : idx+1] + + var buf strings.Builder + buf.WriteByte('"') + const suffix = `": ` + switch { + case n < 0 || idx <= n-buf.Len()-len(suffix): + buf.Write(key) + buf.WriteString(suffix) + case idx < n: + buf.Write(key) + buf.WriteString(suffix[:n-idx-1]) + return buf.String(), true + default: + buf.WriteString(bsoncoreutil.Truncate(string(key), n-1)) + return buf.String(), true + } + + needStrLen := -1 + // Set needStrLen if n is positive, meaning we want to limit the string length. + if n > 0 { + // Stop stringifying if we reach the limit, that also ensures needStrLen is + // greater than 0 if we need to limit the length. + if buf.Len() >= n { + return buf.String(), true + } + needStrLen = n - buf.Len() + } + + val, _, valid := ReadValue(e[idx+2:], t) if !valid { - return "" + return "", false } var str string + var truncated bool if _, ok := val.StringValueOK(); ok { - str = val.StringN(n) + str, truncated = val.StringN(needStrLen) } else if arr, ok := val.ArrayOK(); ok { - str = arr.StringN(n) + str, truncated = arr.StringN(needStrLen) } else { str = val.String() + if needStrLen > 0 && len(str) > needStrLen { + truncated = true + str = bsoncoreutil.Truncate(str, needStrLen) + } } - return "\"" + string(key) + "\": " + str + buf.WriteString(str) + return buf.String(), truncated } // DebugString outputs a human readable version of RawElement. It will attempt to stringify the diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go index b0fd9074..fec33029 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore/value.go @@ -218,138 +218,137 @@ func idHex(id [12]byte) string { // String implements the fmt.String interface. This method will return values in extended JSON // format. If the value is not valid, this returns an empty string func (v Value) String() string { - return v.StringN(math.MaxInt) + str, _ := v.StringN(-1) + return str } -// StringN implements the fmt.String interface. This method will return values in extended JSON -// format that will stringify a value upto N bytes. If the value is not valid, this returns an empty string -func (v Value) StringN(n int) string { - if n <= 0 { - return "" - } - +// StringN will return values in extended JSON format that will stringify a value upto N bytes. +// If N is non-negative, it will truncate the string to N bytes. Otherwise, it will return the full +// string representation. The second return value indicates whether the string was truncated or not. +// If the value is not valid, this returns an empty string +func (v Value) StringN(n int) (string, bool) { + var str string switch v.Type { case TypeString: - str, ok := v.StringValueOK() + s, ok := v.StringValueOK() if !ok { - return "" - } - str = escapeString(str) - if len(str) > n { - truncatedStr := bsoncoreutil.Truncate(str, n) - return truncatedStr + return "", false } - return str + str = escapeString(s) case TypeEmbeddedDocument: doc, ok := v.DocumentOK() if !ok { - return "" + return "", false } return doc.StringN(n) case TypeArray: arr, ok := v.ArrayOK() if !ok { - return "" + return "", false } return arr.StringN(n) case TypeDouble: f64, ok := v.DoubleOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberDouble":"%s"}`, formatDouble(f64)), n) + str = fmt.Sprintf(`{"$numberDouble":"%s"}`, formatDouble(f64)) case TypeBinary: subtype, data, ok := v.BinaryOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$binary":{"base64":"%s","subType":"%02x"}}`, base64.StdEncoding.EncodeToString(data), subtype), n) + str = fmt.Sprintf(`{"$binary":{"base64":"%s","subType":"%02x"}}`, base64.StdEncoding.EncodeToString(data), subtype) case TypeUndefined: - return bsoncoreutil.Truncate(`{"$undefined":true}`, n) + str = `{"$undefined":true}` case TypeObjectID: oid, ok := v.ObjectIDOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$oid":"%s"}`, idHex(oid)), n) + str = fmt.Sprintf(`{"$oid":"%s"}`, idHex(oid)) case TypeBoolean: b, ok := v.BooleanOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(strconv.FormatBool(b), n) + str = strconv.FormatBool(b) case TypeDateTime: dt, ok := v.DateTimeOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$date":{"$numberLong":"%d"}}`, dt), n) + str = fmt.Sprintf(`{"$date":{"$numberLong":"%d"}}`, dt) case TypeNull: - return bsoncoreutil.Truncate("null", n) + str = "null" case TypeRegex: pattern, options, ok := v.RegexOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf( + str = fmt.Sprintf( `{"$regularExpression":{"pattern":%s,"options":"%s"}}`, escapeString(pattern), sortStringAlphebeticAscending(options), - ), n) + ) case TypeDBPointer: ns, pointer, ok := v.DBPointerOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$dbPointer":{"$ref":%s,"$id":{"$oid":"%s"}}}`, escapeString(ns), idHex(pointer)), n) + str = fmt.Sprintf(`{"$dbPointer":{"$ref":%s,"$id":{"$oid":"%s"}}}`, escapeString(ns), idHex(pointer)) case TypeJavaScript: js, ok := v.JavaScriptOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$code":%s}`, escapeString(js)), n) + str = fmt.Sprintf(`{"$code":%s}`, escapeString(js)) case TypeSymbol: symbol, ok := v.SymbolOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$symbol":%s}`, escapeString(symbol)), n) + str = fmt.Sprintf(`{"$symbol":%s}`, escapeString(symbol)) case TypeCodeWithScope: code, scope, ok := v.CodeWithScopeOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$code":%s,"$scope":%s}`, code, scope), n) + str = fmt.Sprintf(`{"$code":%s,"$scope":%s}`, code, scope) case TypeInt32: i32, ok := v.Int32OK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberInt":"%d"}`, i32), n) + str = fmt.Sprintf(`{"$numberInt":"%d"}`, i32) case TypeTimestamp: t, i, ok := v.TimestampOK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$timestamp":{"t":%v,"i":%v}}`, t, i), n) + str = fmt.Sprintf(`{"$timestamp":{"t":%v,"i":%v}}`, t, i) case TypeInt64: i64, ok := v.Int64OK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberLong":"%d"}`, i64), n) + str = fmt.Sprintf(`{"$numberLong":"%d"}`, i64) case TypeDecimal128: h, l, ok := v.Decimal128OK() if !ok { - return "" + return "", false } - return bsoncoreutil.Truncate(fmt.Sprintf(`{"$numberDecimal":"%s"}`, decimal128.String(h, l)), n) + str = fmt.Sprintf(`{"$numberDecimal":"%s"}`, decimal128.String(h, l)) case TypeMinKey: - return bsoncoreutil.Truncate(`{"$minKey":1}`, n) + str = `{"$minKey":1}` case TypeMaxKey: - return bsoncoreutil.Truncate(`{"$maxKey":1}`, n) + str = `{"$maxKey":1}` default: - return "" + str = "" + } + if n >= 0 && len(str) > n { + return bsoncoreutil.Truncate(str, n), true } + return str, false } // DebugString outputs a human readable version of Document. It will attempt to stringify the diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go index 843715dc..bfc7bbdb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/auth.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "net/http" + "strings" "go.mongodb.org/mongo-driver/v2/mongo/address" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" @@ -31,7 +32,6 @@ func init() { RegisterAuthenticatorFactory("", newDefaultAuthenticator) RegisterAuthenticatorFactory(SCRAMSHA1, newScramSHA1Authenticator) RegisterAuthenticatorFactory(SCRAMSHA256, newScramSHA256Authenticator) - RegisterAuthenticatorFactory(MONGODBCR, newMongoDBCRAuthenticator) RegisterAuthenticatorFactory(PLAIN, newPlainAuthenticator) RegisterAuthenticatorFactory(GSSAPI, newGSSAPIAuthenticator) RegisterAuthenticatorFactory(MongoDBX509, newMongoDBX509Authenticator) @@ -41,6 +41,12 @@ func init() { // CreateAuthenticator creates an authenticator. func CreateAuthenticator(name string, cred *Cred, httpClient *http.Client) (Authenticator, error) { + // Return a custom error to indicate why auth mechanism "MONGODB-CR" is + // missing, even though it was previously available. + if strings.EqualFold(name, "MONGODB-CR") { + return nil, errors.New(`auth mechanism "MONGODB-CR" is no longer available in any supported version of MongoDB`) + } + if f, ok := authFactories[name]; ok { return f(cred, httpClient) } diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go index 6982ccc0..0033379d 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/default.go @@ -32,8 +32,8 @@ func newDefaultAuthenticator(cred *Cred, httpClient *http.Client) (Authenticator }, nil } -// DefaultAuthenticator uses SCRAM-SHA-1 or MONGODB-CR depending -// on the server version. +// DefaultAuthenticator uses SCRAM-SHA-1 or SCRAM-SHA-256, depending on the +// server's SASL supported mechanisms. type DefaultAuthenticator struct { Cred *Cred @@ -53,18 +53,20 @@ func (a *DefaultAuthenticator) CreateSpeculativeConversation() (SpeculativeConve // Auth authenticates the connection. func (a *DefaultAuthenticator) Auth(ctx context.Context, cfg *driver.AuthConfig) error { - var actual Authenticator - var err error - - switch chooseAuthMechanism(cfg) { - case SCRAMSHA256: - actual, err = newScramSHA256Authenticator(a.Cred, a.httpClient) - case SCRAMSHA1: - actual, err = newScramSHA1Authenticator(a.Cred, a.httpClient) - default: - actual, err = newMongoDBCRAuthenticator(a.Cred, a.httpClient) - } + actual, err := func() (Authenticator, error) { + // If a server provides a list of supported mechanisms, we choose + // SCRAM-SHA-256 if it exists or else MUST use SCRAM-SHA-1. + // Otherwise, we decide based on what is supported. + if saslSupportedMechs := cfg.HandshakeInfo.SaslSupportedMechs; saslSupportedMechs != nil { + for _, v := range saslSupportedMechs { + if v == SCRAMSHA256 { + return newScramSHA256Authenticator(a.Cred, a.httpClient) + } + } + } + return newScramSHA1Authenticator(a.Cred, a.httpClient) + }() if err != nil { return newAuthError("error creating authenticator", err) } @@ -76,18 +78,3 @@ func (a *DefaultAuthenticator) Auth(ctx context.Context, cfg *driver.AuthConfig) func (a *DefaultAuthenticator) Reauth(_ context.Context, _ *driver.AuthConfig) error { return newAuthError("DefaultAuthenticator does not support reauthentication", nil) } - -// If a server provides a list of supported mechanisms, we choose -// SCRAM-SHA-256 if it exists or else MUST use SCRAM-SHA-1. -// Otherwise, we decide based on what is supported. -func chooseAuthMechanism(cfg *driver.AuthConfig) string { - if saslSupportedMechs := cfg.HandshakeInfo.SaslSupportedMechs; saslSupportedMechs != nil { - for _, v := range saslSupportedMechs { - if v == SCRAMSHA256 { - return v - } - } - } - - return SCRAMSHA1 -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go deleted file mode 100644 index f8c1466d..00000000 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/mongodbcr.go +++ /dev/null @@ -1,120 +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 auth - -import ( - "context" - "fmt" - "io" - "net/http" - - // Ignore gosec warning "Blocklisted import crypto/md5: weak cryptographic primitive". We need - // to use MD5 here to implement the MONGODB-CR specification. - /* #nosec G501 */ - "crypto/md5" - - "go.mongodb.org/mongo-driver/v2/bson" - "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" - "go.mongodb.org/mongo-driver/v2/x/mongo/driver" - "go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation" -) - -// MONGODBCR is the mechanism name for MONGODB-CR. -// -// The MONGODB-CR authentication mechanism is deprecated in MongoDB 3.6 and removed in -// MongoDB 4.0. -const MONGODBCR = "MONGODB-CR" - -func newMongoDBCRAuthenticator(cred *Cred, _ *http.Client) (Authenticator, error) { - source := cred.Source - if source == "" { - source = "admin" - } - return &MongoDBCRAuthenticator{ - DB: source, - Username: cred.Username, - Password: cred.Password, - }, nil -} - -// MongoDBCRAuthenticator uses the MONGODB-CR algorithm to authenticate a connection. -// -// The MONGODB-CR authentication mechanism is deprecated in MongoDB 3.6 and removed in -// MongoDB 4.0. -type MongoDBCRAuthenticator struct { - DB string - Username string - Password string -} - -// Auth authenticates the connection. -// -// The MONGODB-CR authentication mechanism is deprecated in MongoDB 3.6 and removed in -// MongoDB 4.0. -func (a *MongoDBCRAuthenticator) Auth(ctx context.Context, cfg *driver.AuthConfig) error { - - db := a.DB - if db == "" { - db = defaultAuthDB - } - - doc := bsoncore.BuildDocumentFromElements(nil, bsoncore.AppendInt32Element(nil, "getnonce", 1)) - cmd := operation.NewCommand(doc). - Database(db). - Deployment(driver.SingleConnectionDeployment{C: cfg.Connection}). - ClusterClock(cfg.ClusterClock). - ServerAPI(cfg.ServerAPI) - err := cmd.Execute(ctx) - if err != nil { - return newError(err, MONGODBCR) - } - rdr := cmd.Result() - - var getNonceResult struct { - Nonce string `bson:"nonce"` - } - - err = bson.Unmarshal(rdr, &getNonceResult) - if err != nil { - return newAuthError("unmarshal error", err) - } - - doc = bsoncore.BuildDocumentFromElements(nil, - bsoncore.AppendInt32Element(nil, "authenticate", 1), - bsoncore.AppendStringElement(nil, "user", a.Username), - bsoncore.AppendStringElement(nil, "nonce", getNonceResult.Nonce), - bsoncore.AppendStringElement(nil, "key", a.createKey(getNonceResult.Nonce)), - ) - cmd = operation.NewCommand(doc). - Database(db). - Deployment(driver.SingleConnectionDeployment{C: cfg.Connection}). - ClusterClock(cfg.ClusterClock). - ServerAPI(cfg.ServerAPI) - err = cmd.Execute(ctx) - if err != nil { - return newError(err, MONGODBCR) - } - - return nil -} - -// Reauth reauthenticates the connection. -func (a *MongoDBCRAuthenticator) Reauth(_ context.Context, _ *driver.AuthConfig) error { - return newAuthError("MONGODB-CR does not support reauthentication", nil) -} - -func (a *MongoDBCRAuthenticator) createKey(nonce string) string { - // Ignore gosec warning "Use of weak cryptographic primitive". We need to use MD5 here to - // implement the MONGODB-CR specification. - /* #nosec G401 */ - h := md5.New() - - _, _ = io.WriteString(h, nonce) - _, _ = io.WriteString(h, a.Username) - _, _ = io.WriteString(h, mongoPasswordDigest(a.Username, a.Password)) - return fmt.Sprintf("%x", h.Sum(nil)) -} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go index c476ac86..11d52621 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth/oidc.go @@ -13,6 +13,7 @@ import ( "io" "net/http" "net/url" + "os" "regexp" "strings" "sync" @@ -27,33 +28,44 @@ import ( // MongoDBOIDC is the string constant for the MONGODB-OIDC authentication mechanism. const MongoDBOIDC = "MONGODB-OIDC" -// EnvironmentProp is the property key name that specifies the environment for the OIDC authenticator. -const EnvironmentProp = "ENVIRONMENT" +// Valid authMechanismProperties keys for MONGODB-OIDC. +const ( + // EnvironmentProp is the property key name that specifies the environment for the OIDC authenticator. + EnvironmentProp = "ENVIRONMENT" -// ResourceProp is the property key name that specifies the token resource for GCP and AZURE OIDC auth. -const ResourceProp = "TOKEN_RESOURCE" + // ResourceProp is the property key name that specifies the token resource for GCP and AZURE OIDC auth. + ResourceProp = "TOKEN_RESOURCE" -// AllowedHostsProp is the property key name that specifies the allowed hosts for the OIDC authenticator. -const AllowedHostsProp = "ALLOWED_HOSTS" + // AllowedHostsProp is the property key name that specifies the allowed hosts for the OIDC authenticator. + AllowedHostsProp = "ALLOWED_HOSTS" +) + +// Valid ENVIRONMENT authMechismProperty values for MONGODB-OIDC. +const ( + // AzureEnvironmentValue is the value for the Azure environment. + AzureEnvironmentValue = "azure" -// AzureEnvironmentValue is the value for the Azure environment. -const AzureEnvironmentValue = "azure" + // GCPEnvironmentValue is the value for the GCP environment. + GCPEnvironmentValue = "gcp" -// GCPEnvironmentValue is the value for the GCP environment. -const GCPEnvironmentValue = "gcp" + // K8SEnvironmentValue is the value for Kubernetes environments. + K8SEnvironmentValue = "k8s" -// TestEnvironmentValue is the value for the test environment. -const TestEnvironmentValue = "test" + // TestEnvironmentValue is the value for the test environment. + TestEnvironmentValue = "test" +) -const apiVersion = 1 -const invalidateSleepTimeout = 100 * time.Millisecond +const ( + apiVersion = 1 + invalidateSleepTimeout = 100 * time.Millisecond -// The CSOT specification says to apply a 1-minute timeout if "CSOT is not applied". That's -// ambiguous for the v1.x Go Driver because it could mean either "no timeout provided" or "CSOT not -// enabled". Always use a maximum timeout duration of 1 minute, allowing us to ignore the ambiguity. -// Contexts with a shorter timeout are unaffected. -const machineCallbackTimeout = time.Minute -const humanCallbackTimeout = 5 * time.Minute + // The CSOT specification says to apply a 1-minute timeout if "CSOT is not applied". That's + // ambiguous for the v1.x Go Driver because it could mean either "no timeout provided" or "CSOT not + // enabled". Always use a maximum timeout duration of 1 minute, allowing us to ignore the ambiguity. + // Contexts with a shorter timeout are unaffected. + machineCallbackTimeout = time.Minute + humanCallbackTimeout = 5 * time.Minute +) var defaultAllowedHosts = []*regexp.Regexp{ regexp.MustCompile(`^.*[.]mongodb[.]net(:\d+)?$`), @@ -119,14 +131,12 @@ func newOIDCAuthenticator(cred *Cred, httpClient *http.Client) (Authenticator, e if cred.Props != nil { if env, ok := cred.Props[EnvironmentProp]; ok { switch strings.ToLower(env) { - case AzureEnvironmentValue: - fallthrough - case GCPEnvironmentValue: + case AzureEnvironmentValue, GCPEnvironmentValue: if _, ok := cred.Props[ResourceProp]; !ok { return nil, fmt.Errorf("%q must be specified for %q %q", ResourceProp, env, EnvironmentProp) } fallthrough - case TestEnvironmentValue: + case K8SEnvironmentValue, TestEnvironmentValue: if cred.OIDCMachineCallback != nil || cred.OIDCHumanCallback != nil { return nil, fmt.Errorf("OIDC callbacks are not allowed for %q %q", env, EnvironmentProp) } @@ -281,6 +291,8 @@ func (oa *OIDCAuthenticator) providerCallback() (OIDCCallback, error) { return nil, newAuthError(fmt.Sprintf("%q must be specified for GCP OIDC", ResourceProp), nil) } return getGCPOIDCCallback(resource, oa.httpClient), nil + case K8SEnvironmentValue: + return k8sOIDCCallback, nil } return nil, fmt.Errorf("%q %q not supported for MONGODB-OIDC", EnvironmentProp, env) @@ -360,6 +372,29 @@ func getGCPOIDCCallback(resource string, httpClient *http.Client) OIDCCallback { } } +// k8sOIDCCallbackfunc is the callback for the Kubernetes token provider. +func k8sOIDCCallback(context.Context, *OIDCArgs) (*OIDCCredential, error) { + // Check for the presence of the Azure and AWS token file path environment + // variables. If neither are set, use the GKE default token file path. + var path string + if p := os.Getenv("AZURE_FEDERATED_TOKEN_FILE"); p != "" { + path = p + } else if p := os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE"); p != "" { + path = p + } else { + path = "/var/run/secrets/kubernetes.io/serviceaccount/token" + } + + token, err := os.ReadFile(path) + if err != nil { + return nil, fmt.Errorf("error reading OIDC token from %q: %w", path, err) + } + + return &OIDCCredential{ + AccessToken: string(token), + }, nil +} + func (oa *OIDCAuthenticator) getAccessToken( ctx context.Context, conn *mnet.Connection, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go index f4447396..00674fbd 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/batch_cursor.go @@ -34,7 +34,7 @@ var ErrNoCursor = errors.New("database response does not contain a cursor") type BatchCursor struct { clientSession *session.Client clock *session.ClusterClock - comment interface{} + comment any encoderFn codecutil.EncoderFn database string collection string @@ -381,14 +381,40 @@ func (bc *BatchCursor) getMore(ctx context.Context) { bc.err = Operation{ CommandFn: func(dst []byte, _ description.SelectedServer) ([]byte, error) { + // If maxAwaitTime > remaining timeoutMS - minRoundTripTime, then use + // send remaining TimeoutMS - minRoundTripTime allowing the server an + // opportunity to respond with an empty batch. + var maxTimeMS int64 + if bc.maxAwaitTime != nil { + _, ctxDeadlineSet := ctx.Deadline() + + if ctxDeadlineSet { + rttMonitor := bc.Server().RTTMonitor() + + var ok bool + maxTimeMS, ok = driverutil.CalculateMaxTimeMS(ctx, rttMonitor.Min()) + if !ok && maxTimeMS <= 0 { + return nil, fmt.Errorf( + "calculated server-side timeout (%v ms) is less than or equal to 0 (%v): %w", + maxTimeMS, + rttMonitor.Stats(), + ErrDeadlineWouldBeExceeded) + } + } + + if !ctxDeadlineSet || bc.maxAwaitTime.Milliseconds() < maxTimeMS { + maxTimeMS = bc.maxAwaitTime.Milliseconds() + } + } + dst = bsoncore.AppendInt64Element(dst, "getMore", bc.id) dst = bsoncore.AppendStringElement(dst, "collection", bc.collection) if numToReturn > 0 { dst = bsoncore.AppendInt32Element(dst, "batchSize", numToReturn) } - if bc.maxAwaitTime != nil && *bc.maxAwaitTime > 0 { - dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", int64(*bc.maxAwaitTime)/int64(time.Millisecond)) + if maxTimeMS > 0 { + dst = bsoncore.AppendInt64Element(dst, "maxTimeMS", maxTimeMS) } comment, err := codecutil.MarshalValue(bc.comment, bc.encoderFn) @@ -505,7 +531,7 @@ func (bc *BatchCursor) SetMaxAwaitTime(dur time.Duration) { } // SetComment sets the comment for future getMore operations. -func (bc *BatchCursor) SetComment(comment interface{}) { +func (bc *BatchCursor) SetComment(comment any) { bc.comment = comment } @@ -519,6 +545,12 @@ func (bc *BatchCursor) getOperationDeployment() Deployment { return SingleServerDeployment{bc.server} } +// MaxAwaitTime returns the maximum amount of time the server will allow +// the operations to execute. This is only valid for tailable awaitData cursors. +func (bc *BatchCursor) MaxAwaitTime() *time.Duration { + return bc.maxAwaitTime +} + // loadBalancedCursorDeployment is used as a Deployment for getMore and killCursors commands when pinning to a // connection in load balanced mode. This type also functions as an ErrorProcessor to ensure that SDAM errors are // handled for these commands in this mode. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go index c9f9fd46..ccf4534e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/compression.go @@ -110,7 +110,7 @@ func (e *zlibEncoder) Encode(dst, src []byte) ([]byte, error) { } var zstdBufPool = sync.Pool{ - New: func() interface{} { + New: func() any { s := make([]byte, 0) return &s }, @@ -147,7 +147,7 @@ func CompressPayload(in []byte, opts CompressionOpts) ([]byte, error) { } var zstdReaderPool = sync.Pool{ - New: func() interface{} { + New: func() any { r, _ := zstd.NewReader(nil) return r }, diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go index ece143a1..8edad674 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/connstring/connstring.go @@ -297,8 +297,6 @@ func (u *ConnString) setDefaultAuthParams(dbName string) error { } else if u.AuthSource != "$external" { return fmt.Errorf("auth source must be $external") } - case "mongodb-cr": - fallthrough case "scram-sha-1": fallthrough case "scram-sha-256": @@ -696,16 +694,6 @@ func (u *ConnString) addOptions(connectionArgPairs []string) error { func (u *ConnString) validateAuth() error { switch strings.ToLower(u.AuthMechanism) { - case "mongodb-cr": - if u.Username == "" { - return fmt.Errorf("username required for MONGO-CR") - } - if u.Password == "" { - return fmt.Errorf("password required for MONGO-CR") - } - if u.AuthMechanismProperties != nil { - return fmt.Errorf("MONGO-CR cannot have mechanism properties") - } case "mongodb-x509": if u.Password != "" { return fmt.Errorf("password cannot be specified for MONGO-X509") diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go index 7f7c3e8f..91b950c3 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/mongocrypt.go @@ -20,6 +20,7 @@ import ( "errors" "fmt" "net/http" + "time" "unsafe" "go.mongodb.org/mongo-driver/v2/bson" @@ -89,6 +90,17 @@ func NewMongoCrypt(opts *options.MongoCryptOptions) (*MongoCrypt, error) { C.mongocrypt_setopt_bypass_query_analysis(crypt.wrapped) } + var keyExpirationMs uint64 = 60_000 // 60,000 ms + if opts.KeyExpiration != nil { + if *opts.KeyExpiration <= 0 { + keyExpirationMs = 0 + } else { + // find the ceiling integer millisecond for the expiration + keyExpirationMs = uint64((*opts.KeyExpiration + time.Millisecond - 1) / time.Millisecond) + } + } + C.mongocrypt_setopt_key_expiration(crypt.wrapped, C.uint64_t(keyExpirationMs)) + // If loading the crypt_shared library isn't disabled, set the default library search path "$SYSTEM" // and set a library override path if one was provided. if !opts.CryptSharedLibDisabled { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go index c6474a4b..504065d4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/mongocrypt/options/mongocrypt_options.go @@ -8,6 +8,7 @@ package options import ( "net/http" + "time" "go.mongodb.org/mongo-driver/v2/x/bsonx/bsoncore" ) @@ -21,6 +22,7 @@ type MongoCryptOptions struct { CryptSharedLibDisabled bool CryptSharedLibOverridePath string HTTPClient *http.Client + KeyExpiration *time.Duration } // MongoCrypt creates a new MongoCryptOptions instance. @@ -70,3 +72,10 @@ func (mo *MongoCryptOptions) SetHTTPClient(httpClient *http.Client) *MongoCryptO mo.HTTPClient = httpClient return mo } + +// SetKeyExpiration sets the key expiration duration. 0 means "never expire". +// The granularity is in milliseconds. Any sub-millisecond fraction will be rounded up. +func (mo *MongoCryptOptions) SetKeyExpiration(expiration *time.Duration) *MongoCryptOptions { + mo.KeyExpiration = expiration + return mo +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go index 2597a5de..57ec762e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation.go @@ -158,13 +158,43 @@ type ResponseInfo struct { } func redactStartedInformationCmd(info startedInformation) bson.Raw { + intLen := func(n int) int { + if n == 0 { + return 1 // Special case: 0 has one digit + } + count := 0 + for n > 0 { + n /= 10 + count++ + } + return count + } + var cmdCopy bson.Raw // Make a copy of the command. Redact if the command is security // sensitive and cannot be monitored. If there was a type 1 payload for // the current batch, convert it to a BSON array if !info.redacted { - cmdCopy = make([]byte, 0, len(info.cmd)) + cmdLen := len(info.cmd) + for _, seq := range info.documentSequences { + cmdLen += 7 // 2 (header) + 4 (array length) + 1 (array end) + cmdLen += len(seq.identifier) + data := seq.data + i := 0 + for { + doc, rest, ok := bsoncore.ReadDocument(data) + if !ok { + break + } + data = rest + cmdLen += len(doc) + cmdLen += intLen(i) + i++ + } + } + + cmdCopy = make([]byte, 0, cmdLen) cmdCopy = append(cmdCopy, info.cmd...) if len(info.documentSequences) > 0 { @@ -504,7 +534,7 @@ func (op Operation) Validate() error { } var memoryPool = sync.Pool{ - New: func() interface{} { + New: func() any { // Start with 1kb buffers. b := make([]byte, 1024) // Return a pointer as the static analysis tool suggests. @@ -1724,34 +1754,16 @@ func (op Operation) calculateMaxTimeMS(ctx context.Context, rttMin time.Duration return 0, nil } - deadline, ok := ctx.Deadline() - if !ok { - return 0, nil - } - - remainingTimeout := time.Until(deadline) - - // Always round up to the next millisecond value so we never truncate the calculated - // maxTimeMS value (e.g. 400 microseconds evaluates to 1ms, not 0ms). - maxTimeMS := int64((remainingTimeout - rttMin + time.Millisecond - 1) / time.Millisecond) - if maxTimeMS <= 0 { + // Calculate maxTimeMS value to potentially be appended to the wire message. + maxTimeMS, ok := driverutil.CalculateMaxTimeMS(ctx, rttMin) + if !ok && maxTimeMS <= 0 { return 0, fmt.Errorf( - "remaining time %v until context deadline is less than or equal to min network round-trip time %v (%v): %w", - remainingTimeout, - rttMin, + "calculated server-side timeout (%v ms) is less than or equal to 0 (%v): %w", + maxTimeMS, rttStats, ErrDeadlineWouldBeExceeded) } - // The server will return a "BadValue" error if maxTimeMS is greater - // than the maximum positive int32 value (about 24.9 days). If the - // user specified a timeout value greater than that, omit maxTimeMS - // and let the client-side timeout handle cancelling the op if the - // timeout is ever reached. - if maxTimeMS > math.MaxInt32 { - return 0, nil - } - return maxTimeMS, nil } @@ -1826,7 +1838,6 @@ func (op Operation) createReadPref(desc description.SelectedServer, isOpQuery bo // TODO if supplied readPreference was "overwritten" with primary in description.selectForReplicaSet. if desc.Server.Kind == description.ServerKindStandalone || (isOpQuery && desc.Server.Kind != description.ServerKindMongos) || - op.Type == Write || (op.IsOutputAggregate && desc.Server.WireVersion.Max < 13) { // Don't send read preference for: // 1. all standalones diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go index 396a5693..380789ab 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/aggregate.go @@ -50,6 +50,7 @@ type Aggregate struct { customOptions map[string]bsoncore.Value timeout *time.Duration omitMaxTimeMS bool + rawData *bool result driver.CursorResponse } @@ -159,6 +160,10 @@ func (a *Aggregate) command(dst []byte, desc description.SelectedServer) ([]byte if a.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", a.let) } + // Set rawData for 8.2+ servers. + if a.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *a.rawData) + } for optionName, optionValue := range a.customOptions { dst = bsoncore.AppendValueElement(dst, optionName, optionValue) } @@ -198,7 +203,7 @@ func (a *Aggregate) BypassDocumentValidation(bypassDocumentValidation bool) *Agg return a } -// Collation specifies a collation. This option is only valid for server versions 3.4 and above. +// Collation specifies a collation. func (a *Aggregate) Collation(collation bsoncore.Document) *Aggregate { if a == nil { a = new(Aggregate) @@ -431,3 +436,13 @@ func (a *Aggregate) OmitMaxTimeMS(omit bool) *Aggregate { a.omitMaxTimeMS = omit return a } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (a *Aggregate) RawData(rawData bool) *Aggregate { + if a == nil { + a = new(Aggregate) + } + + a.rawData = &rawData + return a +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go index 5ecaa3a9..d056702a 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/count.go @@ -41,6 +41,7 @@ type Count struct { result CountResult serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool } // CountResult represents a count result returned by the server. @@ -139,7 +140,7 @@ func (c *Count) Execute(ctx context.Context) error { return err } -func (c *Count) command(dst []byte, _ description.SelectedServer) ([]byte, error) { +func (c *Count) command(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "count", c.collection) if c.query != nil { dst = bsoncore.AppendDocumentElement(dst, "query", c.query) @@ -147,6 +148,10 @@ func (c *Count) command(dst []byte, _ description.SelectedServer) ([]byte, error if c.comment.Type != bsoncore.Type(0) { dst = bsoncore.AppendValueElement(dst, "comment", c.comment) } + // Set rawData for 8.2+ servers. + if c.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *c.rawData) + } return dst, nil } @@ -310,3 +315,13 @@ func (c *Count) Authenticator(authenticator driver.Authenticator) *Count { c.authenticator = authenticator return c } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (c *Count) RawData(rawData bool) *Count { + if c == nil { + c = new(Count) + } + + c.rawData = &rawData + return c +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go index 840d0ba4..f9a406db 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create.go @@ -151,7 +151,7 @@ func (c *Create) Capped(capped bool) *Create { return c } -// Collation specifies a collation. This option is only valid for server versions 3.4 and above. +// Collation specifies a collation. func (c *Create) Collation(collation bsoncore.Document) *Create { if c == nil { c = new(Create) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go index 0380a55a..17e88ba8 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/create_indexes.go @@ -38,6 +38,7 @@ type CreateIndexes struct { result CreateIndexesResult serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool } // CreateIndexesResult represents a createIndexes result returned by the server. @@ -133,6 +134,10 @@ func (ci *CreateIndexes) command(dst []byte, desc description.SelectedServer) ([ if ci.indexes != nil { dst = bsoncore.AppendArrayElement(dst, "indexes", ci.indexes) } + // Set rawData for 8.2+ servers. + if ci.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *ci.rawData) + } return dst, nil } @@ -277,3 +282,13 @@ func (ci *CreateIndexes) Authenticator(authenticator driver.Authenticator) *Crea ci.authenticator = authenticator return ci } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (ci *CreateIndexes) RawData(rawData bool) *CreateIndexes { + if ci == nil { + ci = new(CreateIndexes) + } + + ci.rawData = &rawData + return ci +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go index 39420efc..e4510fb8 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/delete.go @@ -43,6 +43,7 @@ type Delete struct { serverAPI *driver.ServerAPIOptions let bsoncore.Document timeout *time.Duration + rawData *bool logger *logger.Logger } @@ -139,6 +140,10 @@ func (d *Delete) command(dst []byte, desc description.SelectedServer) ([]byte, e if d.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", d.let) } + // Set rawData for 8.2+ servers. + if d.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *d.rawData) + } return dst, nil } @@ -277,8 +282,7 @@ func (d *Delete) Retry(retry driver.RetryMode) *Delete { } // Hint is a flag to indicate that the update document contains a hint. Hint is only supported by -// servers >= 4.4. Older servers >= 3.4 will report an error for using the hint option. For servers < -// 3.4, the driver will return an error if the hint option is used. +// servers >= 4.4. Older servers will report an error for using the hint option. func (d *Delete) Hint(hint bool) *Delete { if d == nil { d = new(Delete) @@ -338,3 +342,13 @@ func (d *Delete) Authenticator(authenticator driver.Authenticator) *Delete { d.authenticator = authenticator return d } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (d *Delete) RawData(rawData bool) *Delete { + if d == nil { + d = new(Delete) + } + + d.rawData = &rawData + return d +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go index 89d412de..ef235e24 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/distinct.go @@ -43,6 +43,7 @@ type Distinct struct { result DistinctResult serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool } // DistinctResult represents a distinct result returned by the server. @@ -130,6 +131,10 @@ func (d *Distinct) command(dst []byte, desc description.SelectedServer) ([]byte, if d.query != nil { dst = bsoncore.AppendDocumentElement(dst, "query", d.query) } + // Set rawData for 8.2+ servers. + if d.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *d.rawData) + } return dst, nil } @@ -323,3 +328,13 @@ func (d *Distinct) Authenticator(authenticator driver.Authenticator) *Distinct { d.authenticator = authenticator return d } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (d *Distinct) RawData(rawData bool) *Distinct { + if d == nil { + d = new(Distinct) + } + + d.rawData = &rawData + return d +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go index e57cff72..14ecbdc1 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/drop_indexes.go @@ -37,6 +37,7 @@ type DropIndexes struct { result DropIndexesResult serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool } // DropIndexesResult represents a dropIndexes result returned by the server. @@ -104,7 +105,7 @@ func (di *DropIndexes) Execute(ctx context.Context) error { } -func (di *DropIndexes) command(dst []byte, _ description.SelectedServer) ([]byte, error) { +func (di *DropIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "dropIndexes", di.collection) switch t := di.index.(type) { @@ -115,6 +116,10 @@ func (di *DropIndexes) command(dst []byte, _ description.SelectedServer) ([]byte dst = bsoncore.AppendDocumentElement(dst, "index", t) } } + // Set rawData for 8.2+ servers. + if di.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *di.rawData) + } return dst, nil } @@ -248,3 +253,13 @@ func (di *DropIndexes) Authenticator(authenticator driver.Authenticator) *DropIn di.authenticator = authenticator return di } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (di *DropIndexes) RawData(rawData bool) *DropIndexes { + if di == nil { + di = new(DropIndexes) + } + + di.rawData = &rawData + return di +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go index b607cb14..615e2408 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find.go @@ -61,6 +61,7 @@ type Find struct { result driver.CursorResponse serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool logger *logger.Logger omitMaxTimeMS bool } @@ -191,6 +192,10 @@ func (f *Find) command(dst []byte, desc description.SelectedServer) ([]byte, err if f.tailable != nil { dst = bsoncore.AppendBooleanElement(dst, "tailable", *f.tailable) } + // Set rawData for 8.2+ servers. + if f.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *f.rawData) + } return dst, nil } @@ -565,6 +570,16 @@ func (f *Find) Authenticator(authenticator driver.Authenticator) *Find { return f } +// RawData sets the rawData to access timeseries data in the compressed format. +func (f *Find) RawData(rawData bool) *Find { + if f == nil { + f = new(Find) + } + + f.rawData = &rawData + return f +} + // OmitMaxTimeMS omits the automatically-calculated "maxTimeMS" from the // command. func (f *Find) OmitMaxTimeMS(omit bool) *Find { diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go index 505c56b0..09205681 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/find_and_modify.go @@ -50,6 +50,7 @@ type FindAndModify struct { serverAPI *driver.ServerAPIOptions let bsoncore.Document timeout *time.Duration + rawData *bool result FindAndModifyResult } @@ -59,7 +60,7 @@ type LastErrorObject struct { // True if an update modified an existing document UpdatedExisting bool // Object ID of the upserted document. - Upserted interface{} + Upserted any } // FindAndModifyResult represents a findAndModify result returned by the server. @@ -211,6 +212,10 @@ func (fam *FindAndModify) command(dst []byte, desc description.SelectedServer) ( if fam.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", fam.let) } + // Set rawData for 8.2+ servers. + if fam.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *fam.rawData) + } return dst, nil } @@ -476,3 +481,13 @@ func (fam *FindAndModify) Authenticator(authenticator driver.Authenticator) *Fin fam.authenticator = authenticator return fam } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (fam *FindAndModify) RawData(rawData bool) *FindAndModify { + if fam == nil { + fam = new(FindAndModify) + } + + fam.rawData = &rawData + return fam +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go index b48e2c85..57d461ae 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/insert.go @@ -42,6 +42,7 @@ type Insert struct { result InsertResult serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool logger *logger.Logger } @@ -132,6 +133,10 @@ func (i *Insert) command(dst []byte, desc description.SelectedServer) ([]byte, e if i.ordered != nil { dst = bsoncore.AppendBooleanElement(dst, "ordered", *i.ordered) } + // Set rawData for 8.2+ servers. + if i.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *i.rawData) + } return dst, nil } @@ -318,3 +323,13 @@ func (i *Insert) Authenticator(authenticator driver.Authenticator) *Insert { i.authenticator = authenticator return i } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (i *Insert) RawData(rawData bool) *Insert { + if i == nil { + i = new(Insert) + } + + i.rawData = &rawData + return i +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go index 3f9b55a6..672404cb 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_collections.go @@ -39,6 +39,7 @@ type ListCollections struct { batchSize *int32 serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool } // NewListCollections constructs and returns a new ListCollections. @@ -92,7 +93,7 @@ func (lc *ListCollections) Execute(ctx context.Context) error { } -func (lc *ListCollections) command(dst []byte, _ description.SelectedServer) ([]byte, error) { +func (lc *ListCollections) command(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendInt32Element(dst, "listCollections", 1) if lc.filter != nil { dst = bsoncore.AppendDocumentElement(dst, "filter", lc.filter) @@ -110,6 +111,11 @@ func (lc *ListCollections) command(dst []byte, _ description.SelectedServer) ([] } dst = bsoncore.AppendDocumentElement(dst, "cursor", cursorDoc.Build()) + // Set rawData for 8.2+ servers. + if lc.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *lc.rawData) + } + return dst, nil } @@ -274,3 +280,13 @@ func (lc *ListCollections) Authenticator(authenticator driver.Authenticator) *Li lc.authenticator = authenticator return lc } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (lc *ListCollections) RawData(rawData bool) *ListCollections { + if lc == nil { + lc = new(ListCollections) + } + + lc.rawData = &rawData + return lc +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go index d7642a19..21b138a4 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/list_indexes.go @@ -34,6 +34,7 @@ type ListIndexes struct { crypt driver.Crypt serverAPI *driver.ServerAPIOptions timeout *time.Duration + rawData *bool result driver.CursorResponse } @@ -91,16 +92,19 @@ func (li *ListIndexes) Execute(ctx context.Context) error { } -func (li *ListIndexes) command(dst []byte, _ description.SelectedServer) ([]byte, error) { +func (li *ListIndexes) command(dst []byte, desc description.SelectedServer) ([]byte, error) { dst = bsoncore.AppendStringElement(dst, "listIndexes", li.collection) cursorIdx, cursorDoc := bsoncore.AppendDocumentStart(nil) if li.batchSize != nil { - cursorDoc = bsoncore.AppendInt32Element(cursorDoc, "batchSize", *li.batchSize) } cursorDoc, _ = bsoncore.AppendDocumentEnd(cursorDoc, cursorIdx) dst = bsoncore.AppendDocumentElement(dst, "cursor", cursorDoc) + // Set rawData for 8.2+ servers. + if li.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *li.rawData) + } return dst, nil } @@ -235,3 +239,13 @@ func (li *ListIndexes) Authenticator(authenticator driver.Authenticator) *ListIn li.authenticator = authenticator return li } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (li *ListIndexes) RawData(rawData bool) *ListIndexes { + if li == nil { + li = new(ListIndexes) + } + + li.rawData = &rawData + return li +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go index 186f9463..00e193ef 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation/update.go @@ -46,13 +46,14 @@ type Update struct { serverAPI *driver.ServerAPIOptions let bsoncore.Document timeout *time.Duration + rawData *bool logger *logger.Logger } // Upsert contains the information for an upsert in an Update operation. type Upsert struct { Index int64 - ID interface{} `bson:"_id"` + ID any `bson:"_id"` } // UpdateResult contains information for the result of an Update operation. @@ -203,12 +204,15 @@ func (u *Update) command(dst []byte, desc description.SelectedServer) ([]byte, e if u.let != nil { dst = bsoncore.AppendDocumentElement(dst, "let", u.let) } + // Set rawData for 8.2+ servers. + if u.rawData != nil && desc.WireVersion != nil && driverutil.VersionRangeIncludes(*desc.WireVersion, 27) { + dst = bsoncore.AppendBooleanElement(dst, "rawData", *u.rawData) + } return dst, nil } -// BypassDocumentValidation allows the operation to opt-out of document level validation. Valid -// for server versions >= 3.2. For servers < 3.2, this setting is ignored. +// BypassDocumentValidation allows the operation to opt-out of document level validation. func (u *Update) BypassDocumentValidation(bypassDocumentValidation bool) *Update { if u == nil { u = new(Update) @@ -219,8 +223,7 @@ func (u *Update) BypassDocumentValidation(bypassDocumentValidation bool) *Update } // Hint is a flag to indicate that the update document contains a hint. Hint is only supported by -// servers >= 4.2. Older servers >= 3.4 will report an error for using the hint option. For servers < -// 3.4, the driver will return an error if the hint option is used. +// servers >= 4.2. Older servers will report an error for using the hint option. func (u *Update) Hint(hint bool) *Update { if u == nil { u = new(Update) @@ -230,8 +233,7 @@ func (u *Update) Hint(hint bool) *Update { return u } -// ArrayFilters is a flag to indicate that the update document contains an arrayFilters field. This option is only -// supported on server versions 3.6 and higher. For servers < 3.6, the driver will return an error. +// ArrayFilters is a flag to indicate that the update document contains an arrayFilters field. func (u *Update) ArrayFilters(arrayFilters bool) *Update { if u == nil { u = new(Update) @@ -425,3 +427,13 @@ func (u *Update) Authenticator(authenticator driver.Authenticator) *Update { u.authenticator = authenticator return u } + +// RawData sets the rawData to access timeseries data in the compressed format. +func (u *Update) RawData(rawData bool) *Update { + if u == nil { + u = new(Update) + } + + u.rawData = &rawData + return u +} diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go index 24ad6a3a..b1bf1d13 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/connection.go @@ -14,7 +14,6 @@ import ( "fmt" "io" "net" - "os" "strings" "sync" "sync/atomic" @@ -212,7 +211,7 @@ func (c *connection) connect(ctx context.Context) (err error) { // Assign the result of DialContext to a temporary net.Conn to ensure that c.nc is not set in an error case. tempNc, err := c.config.dialer.DialContext(ctx, c.addr.Network(), c.addr.String()) if err != nil { - return ConnectionError{Wrapped: err, init: true} + return ConnectionError{Wrapped: err, init: true, message: fmt.Sprintf("failed to connect to %s", c.addr)} } c.nc = tempNc @@ -229,7 +228,7 @@ func (c *connection) connect(ctx context.Context) (err error) { tlsNc, err := configureTLS(ctx, c.config.tlsConnectionSource, c.nc, c.addr, tlsConfig, ocspOpts) if err != nil { - return ConnectionError{Wrapped: err, init: true} + return ConnectionError{Wrapped: err, init: true, message: fmt.Sprintf("failed to configure TLS for %s", c.addr)} } c.nc = tlsNc } @@ -341,7 +340,10 @@ func transformNetworkError(ctx context.Context, originalError error, contextDead return originalError } if netErr, ok := originalError.(net.Error); ok && netErr.Timeout() { - return fmt.Errorf("%w: %s", context.DeadlineExceeded, originalError.Error()) + return fmt.Errorf("%w: %s: %s", + context.DeadlineExceeded, + "client timed out waiting for server response", + originalError.Error()) } return originalError @@ -413,9 +415,6 @@ func (c *connection) readWireMessage(ctx context.Context) ([]byte, error) { c.close() } message := errMsg - if errors.Is(err, io.EOF) { - message = "socket was unexpectedly closed" - } return nil, ConnectionError{ ConnectionID: c.id, Wrapped: transformNetworkError(ctx, err, contextDeadlineUsed), @@ -526,48 +525,6 @@ func (c *connection) closed() bool { return atomic.LoadInt64(&c.state) == connDisconnected } -// isAlive returns true if the connection is alive and ready to be used for an -// operation. -// -// Note that the liveness check can be slow (at least 1ms), so isAlive only -// checks the liveness of the connection if it's been idle for at least 10 -// seconds. For frequently in-use connections, a network error during an -// operation will be the first indication of a dead connection. -func (c *connection) isAlive() bool { - if c.nc == nil { - return false - } - - // If the connection has been idle for less than 10 seconds, skip the - // liveness check. - // - // The 10-seconds idle bypass is based on the liveness check implementation - // in the Python Driver. That implementation uses 1 second as the idle - // threshold, but we chose to be more conservative in the Go Driver because - // this is new behavior with unknown side-effects. See - // https://github.com/mongodb/mongo-python-driver/blob/e6b95f65953e01e435004af069a6976473eaf841/pymongo/synchronous/pool.py#L983-L985 - idleStart, ok := c.idleStart.Load().(time.Time) - if !ok || idleStart.Add(10*time.Second).After(time.Now()) { - return true - } - - // Set a 1ms read deadline and attempt to read 1 byte from the connection. - // Expect it to block for 1ms then return a deadline exceeded error. If it - // returns any other error, the connection is not usable, so return false. - // If it doesn't return an error and actually reads data, the connection is - // also not usable, so return false. - // - // Note that we don't need to un-set the read deadline because the "read" - // and "write" methods always reset the deadlines. - err := c.nc.SetReadDeadline(time.Now().Add(1 * time.Millisecond)) - if err != nil { - return false - } - var b [1]byte - _, err = c.nc.Read(b[:]) - return errors.Is(err, os.ErrDeadlineExceeded) -} - func (c *connection) idleTimeoutExpired() bool { if c.idleTimeout == 0 { return false diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go index 79f11f7f..dee19415 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/errors.go @@ -10,11 +10,17 @@ import ( "context" "errors" "fmt" + "io" + "net" + "os" + "strings" "time" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" ) +var _ error = ConnectionError{} + // ConnectionError represents a connection error. type ConnectionError struct { ConnectionID string @@ -28,21 +34,28 @@ type ConnectionError struct { // Error implements the error interface. func (e ConnectionError) Error() string { - message := e.message + var messages []string if e.init { - fullMsg := "error occurred during connection handshake" - if message != "" { - fullMsg = fmt.Sprintf("%s: %s", fullMsg, message) - } - message = fullMsg + messages = append(messages, "error occurred during connection handshake") } - if e.Wrapped != nil && message != "" { - return fmt.Sprintf("connection(%s) %s: %s", e.ConnectionID, message, e.Wrapped.Error()) + if e.message != "" { + messages = append(messages, e.message) } if e.Wrapped != nil { - return fmt.Sprintf("connection(%s) %s", e.ConnectionID, e.Wrapped.Error()) + if errors.Is(e.Wrapped, io.EOF) { + messages = append(messages, "connection closed unexpectedly by the other side") + } + if errors.Is(e.Wrapped, os.ErrDeadlineExceeded) { + messages = append(messages, "client timed out waiting for server response") + } else if err, ok := e.Wrapped.(net.Error); ok && err.Timeout() { + messages = append(messages, "client timed out waiting for server response") + } + messages = append(messages, e.Wrapped.Error()) + } + if len(messages) > 0 { + return fmt.Sprintf("connection(%s) %s", e.ConnectionID, strings.Join(messages, ": ")) } - return fmt.Sprintf("connection(%s) %s", e.ConnectionID, message) + return fmt.Sprintf("connection(%s)", e.ConnectionID) } // Unwrap returns the underlying error. diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go index 3cc06656..530b2169 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/fsm.go @@ -20,7 +20,7 @@ import ( var ( // MinSupportedMongoDBVersion is the version string for the lowest MongoDB version supported by the driver. - MinSupportedMongoDBVersion = "3.6" + MinSupportedMongoDBVersion = "4.0" // SupportedWireVersions is the range of wire versions supported by the driver. SupportedWireVersions = driverutil.NewVersionRange(driverutil.MinWireVersion, driverutil.MaxWireVersion) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go index d6568e84..23656864 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/pool.go @@ -143,7 +143,7 @@ func mustLogPoolMessage(pool *pool) bool { logger.LevelDebug, logger.ComponentConnection) } -func logPoolMessage(pool *pool, msg string, keysAndValues ...interface{}) { +func logPoolMessage(pool *pool, msg string, keysAndValues ...any) { host, port, err := net.SplitHostPort(pool.address.String()) if err != nil { host = pool.address.String() @@ -169,11 +169,9 @@ type reason struct { // connectionPerished checks if a given connection is perished and should be removed from the pool. func connectionPerished(conn *connection) (reason, bool) { switch { - case conn.closed() || !conn.isAlive(): + case conn.closed(): // A connection would only be closed if it encountered a network error - // during an operation and closed itself. If a connection is not alive - // (e.g. the connection was closed by the server-side), it's also - // considered a network error. + // during an operation and closed itself. return reason{ loggerConn: logger.ReasonConnClosedError, event: event.ReasonError, @@ -505,7 +503,19 @@ func (p *pool) checkOut(ctx context.Context) (conn *connection, err error) { } return nil, ErrPoolClosed case poolPaused: - err := poolClearedError{err: p.lastClearErr, address: p.address} + // Wrap poolCleared in a driver.Error so we can add the + // "TransientTransactionError" label. This will add + // "TransientTransactionError" to all poolClearedError instances, not + // just those that happened during transactions. While that behavior is + // different than other places we add "TransientTransactionError", it is + // consistent with the Transactions specification and simplifies the + // code. + pcErr := poolClearedError{err: p.lastClearErr, address: p.address} + err := driver.Error{ + Message: pcErr.Error(), + Labels: []string{driver.TransientTransactionError}, + Wrapped: pcErr, + } p.stateMu.RUnlock() duration := time.Since(start) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go index 7fab1136..90cee89e 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/server.go @@ -228,7 +228,7 @@ func mustLogServerMessage(srv *Server) bool { logger.LevelDebug, logger.ComponentTopology) } -func logServerMessage(srv *Server, msg string, keysAndValues ...interface{}) { +func logServerMessage(srv *Server, msg string, keysAndValues ...any) { serverHost, serverPort, err := net.SplitHostPort(srv.address.String()) if err != nil { serverHost = srv.address.String() diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go index 5c1e1342..5343934c 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology.go @@ -167,7 +167,7 @@ func mustLogTopologyMessage(topo *Topology, level logger.Level) bool { level, logger.ComponentTopology) } -func logTopologyMessage(topo *Topology, level logger.Level, msg string, keysAndValues ...interface{}) { +func logTopologyMessage(topo *Topology, level logger.Level, msg string, keysAndValues ...any) { topo.cfg.logger.Print(level, logger.ComponentTopology, msg, @@ -218,7 +218,7 @@ func logServerSelection( level logger.Level, msg string, srvSelector description.ServerSelector, - keysAndValues ...interface{}, + keysAndValues ...any, ) { var srvSelectorString string @@ -405,7 +405,10 @@ func (t *Topology) Disconnect(ctx context.Context) error { t.pollingwg.Wait() } - t.desc.Store(description.Topology{}) + oldDesc := t.fsm.Topology + t.fsm = newFSM() + t.desc.Store(t.fsm.Topology) + t.publishTopologyDescriptionChangedEvent(oldDesc, t.fsm.Topology) atomic.StoreInt64(&t.state, topologyDisconnected) t.publishTopologyClosedEvent() @@ -691,7 +694,6 @@ func (t *Topology) selectServerFromSubscription( case <-ctx.Done(): return nil, ServerSelectionError{Wrapped: ctx.Err(), Desc: current} case current = <-subscriptionCh: - default: } suitable, err := t.selectServerFromDescription(current, srvSelector) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go index aefa74c5..2ddc7434 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/topology/topology_options.go @@ -15,9 +15,11 @@ import ( "go.mongodb.org/mongo-driver/v2/event" "go.mongodb.org/mongo-driver/v2/internal/logger" + "go.mongodb.org/mongo-driver/v2/internal/optionsutil" "go.mongodb.org/mongo-driver/v2/mongo/options" "go.mongodb.org/mongo-driver/v2/x/mongo/driver" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/auth" + "go.mongodb.org/mongo-driver/v2/x/mongo/driver/description" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/ocsp" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/operation" "go.mongodb.org/mongo-driver/v2/x/mongo/driver/session" @@ -270,6 +272,14 @@ func NewConfigFromOptionsWithAuthenticator(opts *options.ClientOptions, clock *s // Required for SASL mechanism negotiation during handshake handshakeOpts.DBUser = opts.Auth.AuthSource + "." + opts.Auth.Username } + if a := optionsutil.Value(opts.Custom, "authenticateToAnything"); a != nil { + if v, ok := a.(bool); ok && v { + // Authenticate arbiters + handshakeOpts.PerformAuthentication = func(_ description.Server) bool { + return true + } + } + } handshaker = func(driver.Handshaker) driver.Handshaker { return auth.Handshaker(nil, handshakeOpts) diff --git a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go index dd16cb7b..f0b1b5e5 100644 --- a/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go +++ b/vendor/go.mongodb.org/mongo-driver/v2/x/mongo/driver/wiremessage/wiremessage.go @@ -406,7 +406,7 @@ func ReadMsgSectionDocumentSequence(src []byte) (identifier string, docs []bsonc // sequence data. func ReadMsgSectionRawDocumentSequence(src []byte) (identifier string, data []byte, rem []byte, ok bool) { length, rem, ok := readi32(src) - if !ok || int(length) > len(src) || length-4 < 0 { + if !ok || int(length) > len(src) || length < 4 { return "", nil, src, false } diff --git a/vendor/modules.txt b/vendor/modules.txt index e9af4278..10f4b1d0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -240,8 +240,8 @@ github.com/xdg-go/stringprep # github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 ## explicit; go 1.17 github.com/youmark/pkcs8 -# go.mongodb.org/mongo-driver/v2 v2.1.0 -## explicit; go 1.18 +# go.mongodb.org/mongo-driver/v2 v2.3.1 +## explicit; go 1.19 go.mongodb.org/mongo-driver/v2/bson go.mongodb.org/mongo-driver/v2/event go.mongodb.org/mongo-driver/v2/internal/aws @@ -260,6 +260,7 @@ go.mongodb.org/mongo-driver/v2/internal/handshake go.mongodb.org/mongo-driver/v2/internal/httputil go.mongodb.org/mongo-driver/v2/internal/logger go.mongodb.org/mongo-driver/v2/internal/mongoutil +go.mongodb.org/mongo-driver/v2/internal/optionsutil go.mongodb.org/mongo-driver/v2/internal/ptrutil go.mongodb.org/mongo-driver/v2/internal/rand go.mongodb.org/mongo-driver/v2/internal/randutil From abfec45836ff944a5a3515322a44e89693374051 Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 11:40:03 -0500 Subject: [PATCH 19/21] revert some --- internal/verifier/compare.go | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/internal/verifier/compare.go b/internal/verifier/compare.go index 4b90db14..85fbfca0 100644 --- a/internal/verifier/compare.go +++ b/internal/verifier/compare.go @@ -700,22 +700,20 @@ func transformPipelineForToHashedIndexKey( ) mongo.Pipeline { return append( slices.Clone(in), - bson.D{{"$replaceRoot", bson.D{ - {"newRoot", bson.D{ - // Single-letter field names minimize the document size. - {docKeyInHashedCompare, dockey.ExtractTrueDocKeyAgg( - task.QueryFilter.GetDocKeyFields(), - "$$ROOT", - )}, - {"h", bson.D{ - {"$toHashedIndexKey", bson.D{ - {"$_internalKeyStringValue", bson.D{ - {"input", "$$ROOT"}, - }}, + bson.D{{"$replaceWith", bson.D{ + // Single-letter field names minimize the document size. + {docKeyInHashedCompare, dockey.ExtractTrueDocKeyAgg( + task.QueryFilter.GetDocKeyFields(), + "$$ROOT", + )}, + {"h", bson.D{ + {"$toHashedIndexKey", bson.D{ + {"$_internalKeyStringValue", bson.D{ + {"input", "$$ROOT"}, }}, }}, - {"s", bson.D{{"$bsonSize", "$$ROOT"}}}, }}, + {"s", bson.D{{"$bsonSize", "$$ROOT"}}}, }}}, ) } From a69ccdf177379381e9994f769f39c74d1b10d44a Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 13:00:58 -0500 Subject: [PATCH 20/21] add comment --- go.mod | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/go.mod b/go.mod index 618f88cc..bf1d6478 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,7 @@ require ( github.com/samber/mo v1.13.0 github.com/stretchr/testify v1.10.0 github.com/urfave/cli v1.22.9 - go.mongodb.org/mongo-driver/v2 v2.3.1 + go.mongodb.org/mongo-driver/v2 v2.3.1 # NB: Pinned pre-2.4 to support 4.0. golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 golang.org/x/sync v0.13.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0 From c3840a65a71136780d16ca12c5864bc63bb7ce5a Mon Sep 17 00:00:00 2001 From: Felipe Gasper Date: Fri, 14 Nov 2025 13:03:46 -0500 Subject: [PATCH 21/21] comment --- go.mod | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index bf1d6478..850f163d 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,9 @@ require ( github.com/samber/mo v1.13.0 github.com/stretchr/testify v1.10.0 github.com/urfave/cli v1.22.9 - go.mongodb.org/mongo-driver/v2 v2.3.1 # NB: Pinned pre-2.4 to support 4.0. + + // NB: This is the last driver version that supported 4.0. + go.mongodb.org/mongo-driver/v2 v2.3.1 golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 golang.org/x/sync v0.13.0 gopkg.in/natefinch/lumberjack.v2 v2.0.0