driver

package
v2.0.0-beta2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 18, 2024 License: Apache-2.0 Imports: 34 Imported by: 1

Documentation

Overview

Package driver is intended for internal use only. It is made available to facilitate use cases that require access to internal MongoDB driver functionality and state. The API of this package is not stable and there is no backward compatibility guarantee.

WARNING: THIS PACKAGE IS EXPERIMENTAL AND MAY BE MODIFIED OR REMOVED WITHOUT NOTICE! USE WITH EXTREME CAUTION!

Index

Constants

View Source
const LegacyNotPrimaryErrMsg = "not master"

LegacyNotPrimaryErrMsg is the error message that older MongoDB servers (see SERVER-50412 for versions) return when a write operation is erroneously sent to a non-primary node.

View Source
const TestServerAPIVersion = "1"

TestServerAPIVersion is the most recent, stable variant of options.ServerAPIVersion. Only to be used in testing.

Variables

View Source
var (
	// UnknownTransactionCommitResult is an error label for unknown transaction commit results.
	UnknownTransactionCommitResult = "UnknownTransactionCommitResult"
	// TransientTransactionError is an error label for transient errors with transactions.
	TransientTransactionError = "TransientTransactionError"
	// NetworkError is an error label for network errors.
	NetworkError = "NetworkError"
	// RetryableWriteError is an error label for retryable write errors.
	RetryableWriteError = "RetryableWriteError"
	// NoWritesPerformed is an error label indicated that no writes were performed for an operation.
	NoWritesPerformed = "NoWritesPerformed"
	// ErrCursorNotFound is the cursor not found error for legacy find operations.
	ErrCursorNotFound = errors.New("cursor not found")
	// ErrUnacknowledgedWrite is returned from functions that have an unacknowledged
	// write concern.
	ErrUnacknowledgedWrite = errors.New("unacknowledged write")
	// ErrUnsupportedStorageEngine is returned when a retryable write is attempted against a server
	// that uses a storage engine that does not support retryable writes
	ErrUnsupportedStorageEngine = errors.New("this MongoDB deployment does not support retryable writes. Please add retryWrites=false to your connection string")
	// ErrDeadlineWouldBeExceeded is returned when a Timeout set on an operation
	// would be exceeded if the operation were sent to the server. It wraps
	// context.DeadlineExceeded.
	ErrDeadlineWouldBeExceeded = fmt.Errorf(
		"operation not sent to server, as Timeout would be exceeded: %w",
		context.DeadlineExceeded)
)
View Source
var (
	// ErrNoDocCommandResponse occurs when the server indicated a response existed, but none was found.
	ErrNoDocCommandResponse = errors.New("command returned no documents")
	// ErrMultiDocCommandResponse occurs when the server sent multiple documents in response to a command.
	ErrMultiDocCommandResponse = errors.New("command returned multiple documents")
	// ErrReplyDocumentMismatch occurs when the number of documents returned in an OP_QUERY does not match the numberReturned field.
	ErrReplyDocumentMismatch = errors.New("number of documents returned does not match numberReturned field")
	// ErrNonPrimaryReadPref is returned when a read is attempted in a transaction with a non-primary read preference.
	ErrNonPrimaryReadPref = errors.New("read preference in a transaction must be primary")
	// ErrEmptyReadConcern indicates that a read concern has no fields set.
	ErrEmptyReadConcern = errors.New("a read concern must have at least one field set")
	// ErrEmptyWriteConcern indicates that a write concern has no fields set.
	ErrEmptyWriteConcern = errors.New("a write concern must have at least one field set")
)
View Source
var ErrDocumentTooLarge = errors.New("an inserted document is too large")

ErrDocumentTooLarge occurs when a document that is larger than the maximum size accepted by a server is passed to an insert command.

View Source
var ErrNoCursor = errors.New("database response does not contain a cursor")

ErrNoCursor is returned by NewCursorResponse when the database response does not contain a cursor.

Functions

func CompressPayload

func CompressPayload(in []byte, opts CompressionOpts) ([]byte, error)

CompressPayload takes a byte slice and compresses it according to the options passed

func DecompressPayload

func DecompressPayload(in []byte, opts CompressionOpts) ([]byte, error)

DecompressPayload takes a byte slice that has been compressed and undoes it according to the options passed

func ExtractErrorFromServerResponse

func ExtractErrorFromServerResponse(doc bsoncore.Document) error

ExtractErrorFromServerResponse extracts an error from a server response bsoncore.Document if there is one. Also used in testing for SDAM.

func MarshalBSONReadConcern

func MarshalBSONReadConcern(rc *readconcern.ReadConcern) (bson.Type, []byte, error)

MarshalBSONReadConcern marshals a ReadConcern.

func MarshalBSONWriteConcern

func MarshalBSONWriteConcern(wc *writeconcern.WriteConcern, wtimeout time.Duration) (bson.Type, []byte, error)

MarshalBSONWriteConcern marshals a WriteConcern.

Types

type AuthConfig

type AuthConfig struct {
	Description   description.Server
	Connection    *mnet.Connection
	ClusterClock  *session.ClusterClock
	HandshakeInfo HandshakeInformation
	ServerAPI     *ServerAPIOptions
}

AuthConfig holds the information necessary to perform an authentication attempt. this was moved from the auth package to avoid a circular dependency. The auth package reexports this under the old name to avoid breaking the public api.

type Authenticator

type Authenticator interface {
	// Auth authenticates the connection.
	Auth(context.Context, *AuthConfig) error
	Reauth(context.Context, *AuthConfig) error
}

Authenticator handles authenticating a connection. The implementers of this interface are all in the auth package. Most authentication mechanisms do not allow for Reauth, but this is included in the interface so that whenever a new mechanism is added, it must be explicitly considered.

type BatchCursor

type BatchCursor struct {
	// contains filtered or unexported fields
}

BatchCursor is a batch implementation of a cursor. It returns documents in entire batches instead of one at a time. An individual document cursor can be built on top of this batch cursor.

func NewBatchCursor

func NewBatchCursor(
	cr CursorResponse,
	clientSession *session.Client,
	clock *session.ClusterClock,
	opts CursorOptions,
) (*BatchCursor, error)

NewBatchCursor creates a new BatchCursor from the provided parameters.

func NewBatchCursorFromList

func NewBatchCursorFromList(array []byte) *BatchCursor

NewBatchCursorFromList returns a batch cursor with current batch set to an itertor that can traverse the BSON data contained within the array.

func NewEmptyBatchCursor

func NewEmptyBatchCursor() *BatchCursor

NewEmptyBatchCursor returns a batch cursor that is empty.

func (*BatchCursor) Batch

func (bc *BatchCursor) Batch() *bsoncore.Iterator

Batch will return a DocumentSequence for the current batch of documents. The returned DocumentSequence is only valid until the next call to Next or Close.

func (*BatchCursor) Close

func (bc *BatchCursor) Close(ctx context.Context) error

Close closes this batch cursor.

func (*BatchCursor) Err

func (bc *BatchCursor) Err() error

Err returns the latest error encountered.

func (*BatchCursor) ID

func (bc *BatchCursor) ID() int64

ID returns the cursor ID for this batch cursor.

func (*BatchCursor) KillCursor

func (bc *BatchCursor) KillCursor(ctx context.Context) error

KillCursor kills cursor on server without closing batch cursor

func (*BatchCursor) Next

func (bc *BatchCursor) Next(ctx context.Context) bool

Next indicates if there is another batch available. Returning false does not necessarily indicate that the cursor is closed. This method will return false when an empty batch is returned.

If Next returns true, there is a valid batch of documents available. If Next returns false, there is not a valid batch of documents available.

func (*BatchCursor) PostBatchResumeToken

func (bc *BatchCursor) PostBatchResumeToken() bsoncore.Document

PostBatchResumeToken returns the latest seen post batch resume token.

func (*BatchCursor) Server

func (bc *BatchCursor) Server() Server

Server returns the server for this cursor.

func (*BatchCursor) SetBatchSize

func (bc *BatchCursor) SetBatchSize(size int32)

SetBatchSize sets the batchSize for future getMore operations.

func (*BatchCursor) SetComment

func (bc *BatchCursor) SetComment(comment interface{})

SetComment sets the comment for future getMore operations.

func (*BatchCursor) SetMaxAwaitTime

func (bc *BatchCursor) SetMaxAwaitTime(dur time.Duration)

SetMaxAwaitTime will set the maximum amount of time the server will allow the operations to execute. The server will error if this field is set but the cursor is not configured with awaitData=true.

The time.Duration value passed by this setter will be converted and rounded down to the nearest millisecond.

type Batches

type Batches struct {
	Identifier string
	Documents  []bsoncore.Document
	Current    []bsoncore.Document
	Ordered    *bool
}

Batches contains the necessary information to batch split an operation. This is only used for write operations.

func (*Batches) AdvanceBatch

func (b *Batches) AdvanceBatch(maxCount, targetBatchSize, maxDocSize int) error

AdvanceBatch splits the next batch using maxCount and targetBatchSize. This method will do nothing if the current batch has not been cleared. We do this so that when this is called during execute we can call it without first needing to check if we already have a batch, which makes the code simpler and makes retrying easier. The maxDocSize parameter is used to check that any one document is not too large. If the first document is bigger than targetBatchSize but smaller than maxDocSize, a batch of size 1 containing that document will be created.

func (*Batches) ClearBatch

func (b *Batches) ClearBatch()

ClearBatch clears the Current batch. This must be called before AdvanceBatch will advance to the next batch.

func (*Batches) Valid

func (b *Batches) Valid() bool

Valid returns true if Batches contains both an identifier and the length of Documents is greater than zero.

type CollectionInfoFn

type CollectionInfoFn func(ctx context.Context, db string, filter bsoncore.Document) (bsoncore.Document, error)

CollectionInfoFn is a callback used to retrieve collection information.

type CompressionOpts

type CompressionOpts struct {
	Compressor       wiremessage.CompressorID
	ZlibLevel        int
	ZstdLevel        int
	UncompressedSize int32
}

CompressionOpts holds settings for how to compress a payload

type Connector

type Connector interface {
	Connect() error
}

Connector represents a type that can connect to a server.

type Cred

type Cred struct {
	Source              string
	Username            string
	Password            string
	PasswordSet         bool
	Props               map[string]string
	OIDCMachineCallback OIDCCallback
	OIDCHumanCallback   OIDCCallback
}

Cred is a user's credential.

type Crypt

type Crypt interface {
	// Encrypt encrypts the given command.
	Encrypt(ctx context.Context, db string, cmd bsoncore.Document) (bsoncore.Document, error)
	// Decrypt decrypts the given command response.
	Decrypt(ctx context.Context, cmdResponse bsoncore.Document) (bsoncore.Document, error)
	// CreateDataKey creates a data key using the given KMS provider and options.
	CreateDataKey(ctx context.Context, kmsProvider string, opts *options.DataKeyOptions) (bsoncore.Document, error)
	// EncryptExplicit encrypts the given value with the given options.
	EncryptExplicit(ctx context.Context, val bsoncore.Value, opts *options.ExplicitEncryptionOptions) (byte, []byte, error)
	// EncryptExplicitExpression encrypts the given expression with the given options.
	EncryptExplicitExpression(ctx context.Context, val bsoncore.Document, opts *options.ExplicitEncryptionOptions) (bsoncore.Document, error)
	// DecryptExplicit decrypts the given encrypted value.
	DecryptExplicit(ctx context.Context, subtype byte, data []byte) (bsoncore.Value, error)
	// Close cleans up any resources associated with the Crypt instance.
	Close()
	// BypassAutoEncryption returns true if auto-encryption should be bypassed.
	BypassAutoEncryption() bool
	// RewrapDataKey attempts to rewrap the document data keys matching the filter, preparing the re-wrapped documents
	// to be returned as a slice of bsoncore.Document.
	RewrapDataKey(ctx context.Context, filter []byte, opts *options.RewrapManyDataKeyOptions) ([]bsoncore.Document, error)
}

Crypt is an interface implemented by types that can encrypt and decrypt instances of bsoncore.Document.

Users should rely on the driver's crypt type (used by default) for encryption and decryption unless they are perfectly confident in another implementation of Crypt.

func NewCrypt

func NewCrypt(opts *CryptOptions) Crypt

NewCrypt creates a new Crypt instance configured with the given AutoEncryptionOptions.

type CryptOptions

type CryptOptions struct {
	MongoCrypt           *mongocrypt.MongoCrypt
	CollInfoFn           CollectionInfoFn
	KeyFn                KeyRetrieverFn
	MarkFn               MarkCommandFn
	TLSConfig            map[string]*tls.Config
	BypassAutoEncryption bool
	BypassQueryAnalysis  bool
}

CryptOptions specifies options to configure a Crypt instance.

type CursorOptions

type CursorOptions struct {
	BatchSize             int32
	Comment               bsoncore.Value
	Limit                 int32
	CommandMonitor        *event.CommandMonitor
	Crypt                 Crypt
	ServerAPI             *ServerAPIOptions
	MarshalValueEncoderFn func(io.Writer) *bson.Encoder

	// MaxAwaitTime is only valid for tailable awaitData cursors. If this option
	// is set, it will be used as the "maxTimeMS" field on getMore commands.
	MaxAwaitTime *time.Duration
}

CursorOptions are extra options that are required to construct a BatchCursor.

func (*CursorOptions) SetMaxAwaitTime

func (cursorOptions *CursorOptions) SetMaxAwaitTime(dur time.Duration)

SetMaxAwaitTime will set the maxTimeMS value on getMore commands for tailable awaitData cursors.

type CursorResponse

type CursorResponse struct {
	Server         Server
	ErrorProcessor ErrorProcessor // This will only be set when pinning to a connection.
	Connection     *mnet.Connection
	Desc           description.Server
	FirstBatch     *bsoncore.Iterator
	Database       string
	Collection     string
	ID             int64
	// contains filtered or unexported fields
}

CursorResponse represents the response from a command the results in a cursor. A BatchCursor can be constructed from a CursorResponse.

func NewCursorResponse

func NewCursorResponse(info ResponseInfo) (CursorResponse, error)

NewCursorResponse constructs a cursor response from the given response and server. If the provided database response does not contain a cursor, it returns ErrNoCursor.

NewCursorResponse can be used within the ProcessResponse method for an operation.

type Deployment

type Deployment interface {
	SelectServer(context.Context, description.ServerSelector) (Server, error)
	Kind() description.TopologyKind

	// GetServerSelectionTimeout returns a timeout that should be used to set a
	// deadline for server selection. This logic is not handleded internally by
	// the ServerSelector, as a resulting deadline may be applicable by follow-up
	// operations such as checking out a connection.
	GetServerSelectionTimeout() time.Duration
}

Deployment is implemented by types that can select a server from a deployment.

type Disconnector

type Disconnector interface {
	Disconnect(context.Context) error
}

Disconnector represents a type that can disconnect from a server.

type Error

type Error struct {
	Code            int32
	Message         string
	Labels          []string
	Name            string
	Wrapped         error
	TopologyVersion *description.TopologyVersion
	Raw             bsoncore.Document
}

Error is a command execution error from the database.

func (Error) Error

func (e Error) Error() string

Error implements the error interface.

func (Error) HasErrorLabel

func (e Error) HasErrorLabel(label string) bool

HasErrorLabel returns true if the error contains the specified label.

func (Error) NamespaceNotFound

func (e Error) NamespaceNotFound() bool

NamespaceNotFound returns true if this errors is a NamespaceNotFound error.

func (Error) NetworkError

func (e Error) NetworkError() bool

NetworkError returns true if the error is a network error.

func (Error) NodeIsRecovering

func (e Error) NodeIsRecovering() bool

NodeIsRecovering returns true if this error is a node is recovering error.

func (Error) NodeIsShuttingDown

func (e Error) NodeIsShuttingDown() bool

NodeIsShuttingDown returns true if this error is a node is shutting down error.

func (Error) NotPrimary

func (e Error) NotPrimary() bool

NotPrimary returns true if this error is a not primary error.

func (Error) RetryableRead

func (e Error) RetryableRead() bool

RetryableRead returns true if the error is retryable for a read operation

func (Error) RetryableWrite

func (e Error) RetryableWrite(wireVersion *description.VersionRange) bool

RetryableWrite returns true if the error is retryable for a write operation

func (Error) UnsupportedStorageEngine

func (e Error) UnsupportedStorageEngine() bool

UnsupportedStorageEngine returns whether e came as a result of an unsupported storage engine

func (Error) Unwrap

func (e Error) Unwrap() error

Unwrap returns the underlying error.

type ErrorProcessor

type ErrorProcessor interface {
	ProcessError(err error, desc mnet.Describer) ProcessErrorResult
}

ErrorProcessor implementations can handle processing errors, which may modify their internal state. If this type is implemented by a Server, then Operation.Execute will call it's ProcessError method after it decodes a wire message.

type Expirable

type Expirable interface {
	Expire() error
	Alive() bool
}

Expirable represents an expirable object.

type HandshakeInformation

type HandshakeInformation struct {
	Description             description.Server
	SpeculativeAuthenticate bsoncore.Document
	ServerConnectionID      *int64
	SaslSupportedMechs      []string
}

HandshakeInformation contains information extracted from a MongoDB connection handshake. This is a helper type that augments description.Server by also tracking server connection ID and authentication-related fields. We use this type rather than adding authentication-related fields to description.Server to avoid retaining sensitive information in a user-facing type. The server connection ID is stored in this type because unlike description.Server, all handshakes are correlated with a single network connection.

type Handshaker

type Handshaker interface {
	GetHandshakeInformation(context.Context, address.Address, *mnet.Connection) (HandshakeInformation, error)
	FinishHandshake(context.Context, *mnet.Connection) error
}

Handshaker is the interface implemented by types that can perform a MongoDB handshake over a provided driver.Connection. This is used during connection initialization. Implementations must be goroutine safe.

type IDPInfo

type IDPInfo struct {
	Issuer        string   `bson:"issuer"`
	ClientID      string   `bson:"clientId"`
	RequestScopes []string `bson:"requestScopes"`
}

IDPInfo contains the information needed to perform OIDC authentication with an Identity Provider.

type InvalidOperationError

type InvalidOperationError struct{ MissingField string }

InvalidOperationError is returned from Validate and indicates that a required field is missing from an instance of Operation.

func (InvalidOperationError) Error

func (err InvalidOperationError) Error() string

type KeyRetrieverFn

type KeyRetrieverFn func(ctx context.Context, filter bsoncore.Document) ([]bsoncore.Document, error)

KeyRetrieverFn is a callback used to retrieve keys from the key vault.

type LegacyOperationKind

type LegacyOperationKind uint

LegacyOperationKind indicates if an operation is a legacy find, getMore, or killCursors. This is used in Operation.Execute, which will create legacy OP_QUERY, OP_GET_MORE, or OP_KILL_CURSORS instead of sending them as a command.

const (
	LegacyNone LegacyOperationKind = iota
	LegacyFind
	LegacyGetMore
	LegacyKillCursors
	LegacyListCollections
	LegacyListIndexes
	LegacyHandshake
)

These constants represent the three different kinds of legacy operations.

type LocalAddresser

type LocalAddresser interface {
	LocalAddress() address.Address
}

LocalAddresser is a type that is able to supply its local address

type MarkCommandFn

type MarkCommandFn func(ctx context.Context, db string, cmd bsoncore.Document) (bsoncore.Document, error)

MarkCommandFn is a callback used to add encryption markings to a command.

type OIDCArgs

type OIDCArgs struct {
	Version      int
	IDPInfo      *IDPInfo
	RefreshToken *string
}

OIDCArgs contains the arguments for the OIDC callback.

type OIDCCallback

type OIDCCallback func(context.Context, *OIDCArgs) (*OIDCCredential, error)

OIDCCallback is the type for both Human and Machine Callback flows. RefreshToken will always be nil in the OIDCArgs for the Machine flow.

type OIDCCredential

type OIDCCredential struct {
	AccessToken  string
	ExpiresAt    *time.Time
	RefreshToken *string
}

OIDCCredential contains the access token and refresh token.

type Operation

type Operation struct {
	// CommandFn is used to create the command that will be wrapped in a wire message and sent to
	// the server. This function should only add the elements of the command and not start or end
	// the enclosing BSON document. Per the command API, the first element must be the name of the
	// command to run. This field is required.
	CommandFn func(dst []byte, desc description.SelectedServer) ([]byte, error)

	// Database is the database that the command will be run against. This field is required.
	Database string

	// Deployment is the MongoDB Deployment to use. While most of the time this will be multiple
	// servers, commands that need to run against a single, preselected server can use the
	// SingleServerDeployment type. Commands that need to run on a preselected connection can use
	// the SingleConnectionDeployment type.
	Deployment Deployment

	// ProcessResponseFn is called after a response to the command is returned. The server is
	// provided for types like Cursor that are required to run subsequent commands using the same
	// server.
	ProcessResponseFn func(ResponseInfo) error

	// Selector is the server selector that's used during both initial server selection and
	// subsequent selection for retries. Depending on the Deployment implementation, the
	// SelectServer method may not actually be called.
	Selector description.ServerSelector

	// ReadPreference is the read preference that will be attached to the command. If this field is
	// not specified a default read preference of primary will be used.
	ReadPreference *readpref.ReadPref

	// ReadConcern is the read concern used when running read commands. This field should not be set
	// for write operations. If this field is set, it will be encoded onto the commands sent to the
	// server.
	ReadConcern *readconcern.ReadConcern

	// MinimumReadConcernWireVersion specifies the minimum wire version to add the read concern to
	// the command being executed.
	MinimumReadConcernWireVersion int32

	// WriteConcern is the write concern used when running write commands. This field should not be
	// set for read operations. If this field is set, it will be encoded onto the commands sent to
	// the server.
	WriteConcern *writeconcern.WriteConcern

	// MinimumWriteConcernWireVersion specifies the minimum wire version to add the write concern to
	// the command being executed.
	MinimumWriteConcernWireVersion int32

	// Client is the session used with this operation. This can be either an implicit or explicit
	// session. If the server selected does not support sessions and Client is specified the
	// behavior depends on the session type. If the session is implicit, the session fields will not
	// be encoded onto the command. If the session is explicit, an error will be returned. The
	// caller is responsible for ensuring that this field is nil if the Deployment does not support
	// sessions.
	Client *session.Client

	// Clock is a cluster clock, different from the one contained within a session.Client. This
	// allows updating cluster times for a global cluster clock while allowing individual session's
	// cluster clocks to be only updated as far as the last command that's been run.
	Clock *session.ClusterClock

	// RetryMode specifies how to retry. There are three modes that enable retry: RetryOnce,
	// RetryOncePerCommand, and RetryContext. For more information about what these modes do, please
	// refer to their definitions. Both RetryMode and Type must be set for retryability to be enabled.
	// If Timeout is set on the Client, the operation will automatically retry as many times as
	// possible unless RetryNone is used.
	RetryMode *RetryMode

	// Type specifies the kind of operation this is. There is only one mode that enables retry: Write.
	// For more information about what this mode does, please refer to it's definition. Both Type and
	// RetryMode must be set for retryability to be enabled.
	Type Type

	// Batches contains the documents that are split when executing a write command that potentially
	// has more documents than can fit in a single command. This should only be specified for
	// commands that are batch compatible. For more information, please refer to the definition of
	// Batches.
	Batches *Batches

	// Legacy sets the legacy type for this operation. There are only 3 types that require legacy
	// support: find, getMore, and killCursors. For more information about LegacyOperationKind,
	// please refer to it's definition.
	Legacy LegacyOperationKind

	// CommandMonitor specifies the monitor to use for APM events. If this field is not set,
	// no events will be reported.
	CommandMonitor *event.CommandMonitor

	// Crypt specifies a Crypt object to use for automatic client side encryption and decryption.
	Crypt Crypt

	// ServerAPI specifies options used to configure the API version sent to the server.
	ServerAPI *ServerAPIOptions

	// IsOutputAggregate specifies whether this operation is an aggregate with an output stage. If true,
	// read preference will not be added to the command on wire versions < 13.
	IsOutputAggregate bool

	// Timeout is the amount of time that this operation can execute before returning an error. The default value
	// nil, which means that the timeout of the operation's caller will be used.
	Timeout *time.Duration

	Logger *logger.Logger

	// Name is the name of the operation. This is used when serializing
	// OP_MSG as well as for logging server selection data.
	Name string

	// OmitMaxTimeMS will ensure that wire messages sent to the server in service
	// of the operation do not contain a maxTimeMS field.
	OmitMaxTimeMS bool

	// Authenticator is the authenticator to use for this operation when a reauthentication is
	// required.
	Authenticator Authenticator
	// contains filtered or unexported fields
}

Operation is used to execute an operation. It contains all of the common code required to select a server, transform an operation into a command, write the command to a connection from the selected server, read a response from that connection, process the response, and potentially retry.

The required fields are Database, CommandFn, and Deployment. All other fields are optional.

While an Operation can be constructed manually, drivergen should be used to generate an implementation of an operation instead. This will ensure that there are helpers for constructing the operation and that this type isn't configured incorrectly.

func (Operation) Execute

func (op Operation) Execute(ctx context.Context) error

Execute runs this operation.

func (Operation) ExecuteExhaust

func (op Operation) ExecuteExhaust(ctx context.Context, conn *mnet.Connection) error

ExecuteExhaust reads a response from the provided StreamerConnection. This will error if the connection's CurrentlyStreaming function returns false.

func (Operation) Validate

func (op Operation) Validate() error

Validate validates this operation, ensuring the fields are set properly.

type ProcessErrorResult

type ProcessErrorResult int

ProcessErrorResult represents the result of a ErrorProcessor.ProcessError() call. Exact values for this type can be checked directly (e.g. res == ServerMarkedUnknown), but it is recommended that applications use the ServerChanged() function instead.

const (
	// NoChange indicates that the error did not affect the state of the server.
	NoChange ProcessErrorResult = iota
	// ServerMarkedUnknown indicates that the error only resulted in the server being marked as Unknown.
	ServerMarkedUnknown
	// ConnectionPoolCleared indicates that the error resulted in the server being marked as Unknown and its connection
	// pool being cleared.
	ConnectionPoolCleared
)

type QueryFailureError

type QueryFailureError struct {
	Message  string
	Response bsoncore.Document
	Wrapped  error
}

QueryFailureError is an error representing a command failure as a document.

func (QueryFailureError) Error

func (e QueryFailureError) Error() string

Error implements the error interface.

func (QueryFailureError) Unwrap

func (e QueryFailureError) Unwrap() error

Unwrap returns the underlying error.

type RTTMonitor

type RTTMonitor interface {
	// EWMA returns the exponentially weighted moving average observed round-trip time.
	EWMA() time.Duration

	// Min returns the minimum observed round-trip time over the window period.
	Min() time.Duration

	// Stats returns stringified stats of the current state of the monitor.
	Stats() string
}

RTTMonitor represents a round-trip-time monitor.

type ResponseError

type ResponseError struct {
	Message string
	Wrapped error
}

ResponseError is an error parsing the response to a command.

func NewCommandResponseError

func NewCommandResponseError(msg string, err error) ResponseError

NewCommandResponseError creates a CommandResponseError.

func (ResponseError) Error

func (e ResponseError) Error() string

Error implements the error interface.

type ResponseInfo

type ResponseInfo struct {
	ServerResponse        bsoncore.Document
	Server                Server
	Connection            *mnet.Connection
	ConnectionDescription description.Server
	CurrentIndex          int
}

ResponseInfo contains the context required to parse a server response.

type RetryMode

type RetryMode uint

RetryMode specifies the way that retries are handled for retryable operations.

const (
	// RetryNone disables retrying.
	RetryNone RetryMode = iota
	// RetryOnce will enable retrying the entire operation once if Timeout is not specified.
	RetryOnce
	// RetryOncePerCommand will enable retrying each command associated with an operation if Timeout
	// is not specified. For example, if an insert is batch split into 4 commands then each of
	// those commands is eligible for one retry.
	RetryOncePerCommand
	// RetryContext will enable retrying until the context.Context's deadline is exceeded or it is
	// cancelled.
	RetryContext
)

These are the modes available for retrying. Note that if Timeout is specified on the Client, the operation will automatically retry as many times as possible within the context's deadline unless RetryNone is used.

func (RetryMode) Enabled

func (rm RetryMode) Enabled() bool

Enabled returns if this RetryMode enables retrying.

type RetryablePoolError

type RetryablePoolError interface {
	Retryable() bool
}

RetryablePoolError is a connection pool error that can be retried while executing an operation.

type Server

type Server interface {
	Connection(context.Context) (*mnet.Connection, error)

	// RTTMonitor returns the round-trip time monitor associated with this server.
	RTTMonitor() RTTMonitor
}

Server represents a MongoDB server. Implementations should pool connections and handle the retrieving and returning of connections.

type ServerAPIOptions

type ServerAPIOptions struct {
	ServerAPIVersion  string
	Strict            *bool
	DeprecationErrors *bool
}

ServerAPIOptions represents arguments used to configure the API version sent to the server when running commands.

func NewServerAPIOptions

func NewServerAPIOptions(serverAPIVersion string) *ServerAPIOptions

NewServerAPIOptions creates a new ServerAPIOptions configured with the provided serverAPIVersion.

func (*ServerAPIOptions) SetDeprecationErrors

func (s *ServerAPIOptions) SetDeprecationErrors(deprecationErrors bool) *ServerAPIOptions

SetDeprecationErrors specifies whether the server should return errors for deprecated features.

func (*ServerAPIOptions) SetStrict

func (s *ServerAPIOptions) SetStrict(strict bool) *ServerAPIOptions

SetStrict specifies whether the server should return errors for features that are not part of the API version.

type SingleConnectionDeployment

type SingleConnectionDeployment struct{ C *mnet.Connection }

SingleConnectionDeployment is an implementation of Deployment that always returns the same Connection. This implementation should only be used for connection handshakes and server heartbeats as it does not implement ErrorProcessor, which is necessary for application operations.

func (SingleConnectionDeployment) Connection

Connection implements the Server interface. It always returns the embedded connection.

func (SingleConnectionDeployment) GetServerSelectionTimeout

func (SingleConnectionDeployment) GetServerSelectionTimeout() time.Duration

GetServerSelectionTimeout returns zero as a server selection timeout is not applicable for single connection deployment.

func (SingleConnectionDeployment) Kind

Kind implements the Deployment interface. It always returns description.TopologyKindSingle.

func (SingleConnectionDeployment) RTTMonitor

func (scd SingleConnectionDeployment) RTTMonitor() RTTMonitor

RTTMonitor implements the driver.Server interface.

func (SingleConnectionDeployment) SelectServer

SelectServer implements the Deployment interface. This method does not use the description.SelectedServer provided and instead returns itself. The Connections returned from the Connection method have a no-op Close method.

type SingleServerDeployment

type SingleServerDeployment struct{ Server }

SingleServerDeployment is an implementation of Deployment that always returns a single server.

func (SingleServerDeployment) GetServerSelectionTimeout

func (SingleServerDeployment) GetServerSelectionTimeout() time.Duration

GetServerSelectionTimeout returns zero as a server selection timeout is not applicable for single server deployments.

func (SingleServerDeployment) Kind

Kind implements the Deployment interface. It always returns description.TopologyKindSingle.

func (SingleServerDeployment) SelectServer

SelectServer implements the Deployment interface. This method does not use the description.SelectedServer provided and instead returns the embedded Server.

type Subscriber

type Subscriber interface {
	Subscribe() (*Subscription, error)
	Unsubscribe(*Subscription) error
}

Subscriber represents a type to which another type can subscribe. A subscription contains a channel that is updated with topology descriptions.

type Subscription

type Subscription struct {
	Updates <-chan description.Topology
	ID      uint64
}

Subscription represents a subscription to topology updates. A subscriber can receive updates through the Updates field.

type Type

type Type uint

Type specifies whether an operation is a read, write, or unknown.

const (
	Write Type
	Read
)

THese are the availables types of Type.

type WriteCommandError

type WriteCommandError struct {
	WriteConcernError *WriteConcernError
	WriteErrors       WriteErrors
	Labels            []string
	Raw               bsoncore.Document
}

WriteCommandError is an error for a write command.

func (WriteCommandError) Error

func (wce WriteCommandError) Error() string

func (WriteCommandError) HasErrorLabel

func (wce WriteCommandError) HasErrorLabel(label string) bool

HasErrorLabel returns true if the error contains the specified label.

func (WriteCommandError) Retryable

func (wce WriteCommandError) Retryable(wireVersion *description.VersionRange) bool

Retryable returns true if the error is retryable

func (WriteCommandError) UnsupportedStorageEngine

func (wce WriteCommandError) UnsupportedStorageEngine() bool

UnsupportedStorageEngine returns whether or not the WriteCommandError comes from a retryable write being attempted against a server that has a storage engine where they are not supported

type WriteConcernError

type WriteConcernError struct {
	Name            string
	Code            int64
	Message         string
	Details         bsoncore.Document
	Labels          []string
	TopologyVersion *description.TopologyVersion
	Raw             bsoncore.Document
}

WriteConcernError is a write concern failure that occurred as a result of a write operation.

func (WriteConcernError) Error

func (wce WriteConcernError) Error() string

func (WriteConcernError) NodeIsRecovering

func (wce WriteConcernError) NodeIsRecovering() bool

NodeIsRecovering returns true if this error is a node is recovering error.

func (WriteConcernError) NodeIsShuttingDown

func (wce WriteConcernError) NodeIsShuttingDown() bool

NodeIsShuttingDown returns true if this error is a node is shutting down error.

func (WriteConcernError) NotPrimary

func (wce WriteConcernError) NotPrimary() bool

NotPrimary returns true if this error is a not primary error.

func (WriteConcernError) Retryable

func (wce WriteConcernError) Retryable() bool

Retryable returns true if the error is retryable

type WriteError

type WriteError struct {
	Index   int64
	Code    int64
	Message string
	Details bsoncore.Document
	Raw     bsoncore.Document
}

WriteError is a non-write concern failure that occurred as a result of a write operation.

func (WriteError) Error

func (we WriteError) Error() string

type WriteErrors

type WriteErrors []WriteError

WriteErrors is a group of non-write concern failures that occurred as a result of a write operation.

func (WriteErrors) Error

func (we WriteErrors) Error() string

Directories

Path Synopsis
Package auth is intended for internal use only.
Package auth is intended for internal use only.
creds
Package creds is intended for internal use only.
Package creds is intended for internal use only.
Package connstring is intended for internal use only.
Package connstring is intended for internal use only.
Package dns is intended for internal use only.
Package dns is intended for internal use only.
Package drivertest is intended for internal use only.
Package drivertest is intended for internal use only.
Package integration is intended for internal use only.
Package integration is intended for internal use only.
Package mongocrypt is intended for internal use only.
Package mongocrypt is intended for internal use only.
options
Package options is intended for internal use only.
Package options is intended for internal use only.
Package ocsp is intended for internal use only.
Package ocsp is intended for internal use only.
Package operation is intended for internal use only.
Package operation is intended for internal use only.
Package session is intended for internal use only.
Package session is intended for internal use only.
Package topology is intended for internal use only.
Package topology is intended for internal use only.
Package wiremessage is intended for internal use only.
Package wiremessage is intended for internal use only.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL