gocbcore

package module
v10.4.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2024 License: Apache-2.0 Imports: 41 Imported by: 28

README

Couchbase Go Core

This package provides the underlying Couchbase IO for the gocb project. If you are looking for the Couchbase Go SDK, you are probably looking for gocb.

Branching Strategy

The gocbcore library maintains a branch for each previous major revision of its API. These branches are introduced just prior to any API breaking changes. Active work is performed on the master branch, with releases being performed as tags. Work made on master which are not yet part of a tagged released should be considered liable to change.

License

Copyright 2017 Couchbase Inc.

Licensed under the Apache License, Version 2.0.

See LICENSE for further details.

Documentation

Overview

Package gocbcore implements methods for low-level communication with a Couchbase Server cluster.

nolint: unused

Index

Constants

View Source
const (
	// PlainAuthMechanism represents that PLAIN auth should be performed.
	PlainAuthMechanism = AuthMechanism("PLAIN")

	// ScramSha1AuthMechanism represents that SCRAM SHA1 auth should be performed.
	ScramSha1AuthMechanism = AuthMechanism("SCRAM-SHA1")

	// ScramSha256AuthMechanism represents that SCRAM SHA256 auth should be performed.
	ScramSha256AuthMechanism = AuthMechanism("SCRAM-SHA256")

	// ScramSha512AuthMechanism represents that SCRAM SHA512 auth should be performed.
	ScramSha512AuthMechanism = AuthMechanism("SCRAM-SHA512")
)
View Source
const (
	// UnknownType indicates the values type is unknown.
	UnknownType = DataType(0)

	// JSONType indicates the value is JSON data.
	JSONType = DataType(1)

	// BinaryType indicates the value is binary data.
	BinaryType = DataType(2)

	// StringType indicates the value is string data.
	StringType = DataType(3)
)
View Source
const (
	// UnknownCompression indicates that the compression type is unknown.
	UnknownCompression = CompressionType(0)

	// NoCompression indicates that no compression is being used.
	NoCompression = CompressionType(1)
)
View Source
const (
	// MemdService represents a memcached service.
	MemdService = ServiceType(1)

	// MgmtService represents a management service (typically ns_server).
	MgmtService = ServiceType(2)

	// CapiService represents a CouchAPI service (typically for views).
	CapiService = ServiceType(3)

	// N1qlService represents a N1QL service (typically for query).
	N1qlService = ServiceType(4)

	// FtsService represents a full-text-search service.
	FtsService = ServiceType(5)

	// CbasService represents an analytics service.
	CbasService = ServiceType(6)

	// EventingService represents the eventing service.
	EventingService = ServiceType(7)

	// GSIService represents the indexing service.
	GSIService = ServiceType(8)

	// BackupService represents the backup service.
	BackupService = ServiceType(9)
)
View Source
const (
	// DcpAgentPriorityLow sets the priority for the dcp stream to low
	DcpAgentPriorityLow = DcpAgentPriority(0)

	// DcpAgentPriorityMed sets the priority for the dcp stream to medium
	DcpAgentPriorityMed = DcpAgentPriority(1)

	// DcpAgentPriorityHigh sets the priority for the dcp stream to high
	DcpAgentPriorityHigh = DcpAgentPriority(2)
)
View Source
const (
	// Deprecated: Use CapabilityStatusUnknown instead
	BucketCapabilityStatusUnknown = CapabilityStatusUnknown

	// Deprecated: Use CapabilityStatusSupported instead
	BucketCapabilityStatusSupported = CapabilityStatusSupported

	// Deprecated: Use CapabilityStatusUnsupported instead
	BucketCapabilityStatusUnsupported = CapabilityStatusUnsupported
)
View Source
const (
	// ClusterStateOnline specifies that all nodes and their sockets are reachable.
	ClusterStateOnline = ClusterState(1)

	// ClusterStateDegraded specifies that at least one socket per service is reachable.
	ClusterStateDegraded = ClusterState(2)

	// ClusterStateOffline is used to specify that not even one socker per service is reachable.
	ClusterStateOffline = ClusterState(3)
)
View Source
const (
	// TransactionDurabilityLevelUnknown indicates to use the default level.
	TransactionDurabilityLevelUnknown = TransactionDurabilityLevel(0)

	// TransactionDurabilityLevelNone indicates that no durability is needed.
	TransactionDurabilityLevelNone = TransactionDurabilityLevel(1)

	// TransactionDurabilityLevelMajority indicates the operation must be replicated to the majority.
	TransactionDurabilityLevelMajority = TransactionDurabilityLevel(2)

	// TransactionDurabilityLevelMajorityAndPersistToActive indicates the operation must be replicated
	// to the majority and persisted to the active server.
	TransactionDurabilityLevelMajorityAndPersistToActive = TransactionDurabilityLevel(3)

	// TransactionDurabilityLevelPersistToMajority indicates the operation must be persisted to the active server.
	TransactionDurabilityLevelPersistToMajority = TransactionDurabilityLevel(4)
)
View Source
const (
	// TransactionAttemptStateNothingWritten indicates that nothing has been written yet.
	TransactionAttemptStateNothingWritten = TransactionAttemptState(1)

	// TransactionAttemptStatePending indicates that the transaction ATR has been written and
	// the transaction is currently pending.
	TransactionAttemptStatePending = TransactionAttemptState(2)

	// TransactionAttemptStateCommitting indicates that the transaction is now trying to become
	// committed, if we stay in this state, it implies ambiguity.
	TransactionAttemptStateCommitting = TransactionAttemptState(3)

	// TransactionAttemptStateCommitted indicates that the transaction is now logically committed
	// but the unstaging of documents is still underway.
	TransactionAttemptStateCommitted = TransactionAttemptState(4)

	// TransactionAttemptStateCompleted indicates that the transaction has been fully completed
	// and no longer has work to perform.
	TransactionAttemptStateCompleted = TransactionAttemptState(5)

	// TransactionAttemptStateAborted indicates that the transaction was aborted.
	TransactionAttemptStateAborted = TransactionAttemptState(6)

	// TransactionAttemptStateRolledBack indicates that the transaction was not committed and instead
	// was rolled back in its entirety.
	TransactionAttemptStateRolledBack = TransactionAttemptState(7)
)
View Source
const (
	// TransactionStagedMutationUnknown indicates an error has occured.
	TransactionStagedMutationUnknown = TransactionStagedMutationType(0)

	// TransactionStagedMutationInsert indicates the staged mutation was an insert operation.
	TransactionStagedMutationInsert = TransactionStagedMutationType(1)

	// TransactionStagedMutationReplace indicates the staged mutation was an replace operation.
	TransactionStagedMutationReplace = TransactionStagedMutationType(2)

	// TransactionStagedMutationRemove indicates the staged mutation was an remove operation.
	TransactionStagedMutationRemove = TransactionStagedMutationType(3)
)

Variables

View Source
var (
	// ErrNoSupportedMechanisms occurs when the server does not support any of the
	// authentication methods that the client finds suitable.
	ErrNoSupportedMechanisms = errors.New("no supported authentication mechanisms")

	// ErrBadHosts occurs when the list of hosts specified cannot be contacted.
	ErrBadHosts = errors.New("failed to connect to any of the specified hosts")

	// ErrProtocol occurs when the server responds with unexpected or unparseable data.
	ErrProtocol = errors.New("failed to parse server response")

	// ErrNoReplicas occurs when no replicas respond in time
	ErrNoReplicas = errors.New("no replicas responded in time")

	// ErrCliInternalError indicates an internal error occurred within the client.
	ErrCliInternalError = errors.New("client internal error")

	// ErrInvalidCredentials is returned when an invalid set of credentials is provided for a service.
	ErrInvalidCredentials = errors.New("an invalid set of credentials was provided")

	// ErrInvalidServer occurs when an explicit, but invalid server is specified.
	ErrInvalidServer = errors.New("specific server is invalid")

	// ErrInvalidVBucket occurs when an explicit, but invalid vbucket index is specified.
	ErrInvalidVBucket = errors.New("specific vbucket index is invalid")

	// ErrInvalidReplica occurs when an explicit, but invalid replica index is specified.
	ErrInvalidReplica = errors.New("specific server index is invalid")

	// ErrInvalidService occurs when an explicit but invalid service type is specified
	ErrInvalidService = errors.New("invalid service")

	// ErrInvalidCertificate occurs when a certificate that is not useable is passed to an Agent.
	ErrInvalidCertificate = errors.New("certificate is invalid")

	// ErrCollectionsUnsupported occurs when collections are used but either server does not support them or the agent
	// was created without them enabled.
	ErrCollectionsUnsupported = errors.New("collections are not enabled")

	// ErrBucketAlreadySelected occurs when SelectBucket is called when a bucket is already selected..
	ErrBucketAlreadySelected = errors.New("bucket already selected")

	// ErrShutdown occurs when operations are performed on a previously closed Agent.
	ErrShutdown = errors.New("connection shut down")

	// ErrOverload occurs when too many operations are dispatched and all queues are full.
	ErrOverload = errors.New("queue overflowed")

	// ErrSocketClosed occurs when a socket closes while an operation is in flight.
	ErrSocketClosed = io.EOF

	// ErrGCCCPInUse occurs when an operation dis performed whilst the client is connect via GCCCP.
	ErrGCCCPInUse = errors.New("connected via gcccp, kv operations are not supported, open a bucket first")

	// ErrNotMyVBucket occurs when an operation is sent to a node which does not own the vbucket.
	ErrNotMyVBucket = errors.New("not my vbucket")

	// ErrForcedReconnect occurs when an operation is in flight during a forced reconnect.
	ErrForcedReconnect = errors.New("forced reconnect")

	// ErrNotStored occurs when the server could not store the document.
	// Per GOCBC-1356, it can also be returned on some paths when inserting a document, and in that context indicates
	// that the document already exists.
	ErrNotStored = errors.New("document was not stored")
)
View Source
var (
	// ErrTimeout occurs when an operation does not receive a response in a timely manner.
	ErrTimeout = errors.New("operation has timed out")

	ErrRequestCanceled          = errors.New("request canceled")
	ErrInvalidArgument          = errors.New("invalid argument")
	ErrServiceNotAvailable      = errors.New("service not available")
	ErrInternalServerFailure    = errors.New("internal server failure")
	ErrAuthenticationFailure    = errors.New("authentication failure - possible reasons - incorrect authentication configuration, bucket doesn’t exist or bucket may be hibernated")
	ErrTemporaryFailure         = errors.New("temporary failure")
	ErrParsingFailure           = errors.New("parsing failure")
	ErrMemdClientClosed         = errors.New("memdclient closed")
	ErrRequestAlreadyDispatched = errors.New("request already dispatched")
	ErrBusy                     = errors.New("busy")

	ErrCasMismatch          = errors.New("cas mismatch")
	ErrBucketNotFound       = errors.New("bucket not found")
	ErrCollectionNotFound   = errors.New("collection not found")
	ErrEncodingFailure      = errors.New("encoding failure")
	ErrDecodingFailure      = errors.New("decoding failure")
	ErrUnsupportedOperation = errors.New("unsupported operation")
	ErrAmbiguousTimeout     = &dwError{ErrTimeout, "ambiguous timeout"}

	ErrUnambiguousTimeout = &dwError{ErrTimeout, "unambiguous timeout"}

	// ErrFeatureNotAvailable occurs when an operation is performed on a bucket which does not support it.
	ErrFeatureNotAvailable = errors.New("feature is not available")
	ErrScopeNotFound       = errors.New("scope not found")
	ErrIndexNotFound       = errors.New("index not found")

	ErrIndexExists = errors.New("index exists")

	// Uncommitted: This API may change in the future.
	ErrRateLimitedFailure = errors.New("rate limited failure")
	// Uncommitted: This API may change in the future.
	ErrQuotaLimitedFailure = errors.New("quota limited failure")
)

Shared Error Definitions RFC#58@15

View Source
var (
	ErrDocumentNotFound                  = errors.New("document not found")
	ErrDocumentUnretrievable             = errors.New("document unretrievable")
	ErrDocumentLocked                    = errors.New("document locked")
	ErrDocumentNotLocked                 = errors.New("document not locked")
	ErrValueTooLarge                     = errors.New("value too large")
	ErrDocumentExists                    = errors.New("document exists")
	ErrValueNotJSON                      = errors.New("value not json")
	ErrDurabilityLevelNotAvailable       = errors.New("durability level not available")
	ErrDurabilityImpossible              = errors.New("durability impossible")
	ErrDurabilityAmbiguous               = errors.New("durability ambiguous")
	ErrDurableWriteInProgress            = errors.New("durable write in progress")
	ErrDurableWriteReCommitInProgress    = errors.New("durable write recommit in progress")
	ErrMutationLost                      = errors.New("mutation lost")
	ErrPathNotFound                      = errors.New("path not found")
	ErrPathMismatch                      = errors.New("path mismatch")
	ErrPathInvalid                       = errors.New("path invalid")
	ErrPathTooBig                        = errors.New("path too big")
	ErrPathTooDeep                       = errors.New("path too deep")
	ErrValueTooDeep                      = errors.New("value too deep")
	ErrValueInvalid                      = errors.New("value invalid")
	ErrDocumentNotJSON                   = errors.New("document not json")
	ErrNumberTooBig                      = errors.New("number too big")
	ErrDeltaInvalid                      = errors.New("delta invalid")
	ErrPathExists                        = errors.New("path exists")
	ErrXattrUnknownMacro                 = errors.New("xattr unknown macro")
	ErrXattrInvalidFlagCombo             = errors.New("xattr invalid flag combination")
	ErrXattrInvalidKeyCombo              = errors.New("xattr invalid key combination")
	ErrXattrUnknownVirtualAttribute      = errors.New("xattr unknown virtual attribute")
	ErrXattrCannotModifyVirtualAttribute = errors.New("xattr cannot modify virtual attribute")
	ErrXattrInvalidOrder                 = errors.New("xattr invalid order")

	ErrRangeScanCancelled      = errors.New("range scan cancelled")
	ErrRangeScanMore           = errors.New("range scan more")
	ErrRangeScanComplete       = errors.New("range scan complete")
	ErrRangeScanVbUUIDNotEqual = errors.New("range scan vb-uuid mismatch")

	// Uncommitted: This API may change in the future.
	ErrConnectionIDInvalid = errors.New("connection id unknown")

	// Uncommitted: This API may change in the future
	// Signals that an operation was cancelled due to the circuit breaker being open
	ErrCircuitBreakerOpen = errors.New("circuit breaker open")
)

Key Value Error Definitions RFC#58@15

View Source
var (
	ErrPlanningFailure = errors.New("planning failure")

	ErrIndexFailure = errors.New("index failure")

	ErrPreparedStatementFailure = errors.New("prepared statement failure")

	ErrDMLFailure = errors.New("data service returned an error during execution of DML statement")
)

Query Error Definitions RFC#58@15

View Source
var (
	ErrCompilationFailure = errors.New("compilation failure")

	ErrJobQueueFull = errors.New("job queue full")

	ErrDatasetNotFound = errors.New("dataset not found")

	ErrDataverseNotFound = errors.New("dataverse not found")

	ErrDatasetExists = errors.New("dataset exists")

	ErrDataverseExists = errors.New("dataverse exists")

	ErrLinkNotFound = errors.New("link not found")
)

Analytics Error Definitions RFC#58@15

View Source
var (
	ErrViewNotFound = errors.New("view not found")

	ErrDesignDocumentNotFound = errors.New("design document not found")
)

View Error Definitions RFC#58@15

View Source
var (
	ErrCollectionExists                   = errors.New("collection exists")
	ErrScopeExists                        = errors.New("scope exists")
	ErrUserNotFound                       = errors.New("user not found")
	ErrGroupNotFound                      = errors.New("group not found")
	ErrBucketExists                       = errors.New("bucket exists")
	ErrUserExists                         = errors.New("user exists")
	ErrBucketNotFlushable                 = errors.New("bucket not flushable")
	ErrEventingFunctionNotFound           = errors.New("eventing function not found")
	ErrEventingFunctionNotDeployed        = errors.New("eventing function not deployed")
	ErrEventingFunctionCompilationFailure = errors.New("eventing function compilation failure")
	ErrEventingFunctionIdenticalKeyspace  = errors.New("eventing function identical keyspace")
	ErrEventingFunctionNotBootstrapped    = errors.New("eventing function not bootstrapped")
	ErrEventingFunctionNotUndeployed      = errors.New("eventing function not undeployed")
)

Management Error Definitions RFC#58@15

View Source
var (
	// ErrDCPStreamClosed occurs when a DCP stream is closed gracefully.
	ErrDCPStreamClosed = makeStreamEndStatusError(memd.StreamEndClosed)

	// ErrDCPStreamStateChanged occurs when a DCP stream is interrupted by failover.
	ErrDCPStreamStateChanged = makeStreamEndStatusError(memd.StreamEndStateChanged)

	// ErrDCPStreamDisconnected occurs when a DCP stream is disconnected.
	ErrDCPStreamDisconnected = makeStreamEndStatusError(memd.StreamEndDisconnected)

	// ErrDCPStreamTooSlow occurs when a DCP stream is cancelled due to the application
	// not keeping up with the rate of flow of DCP events sent by the server.
	ErrDCPStreamTooSlow = makeStreamEndStatusError(memd.StreamEndTooSlow)

	// ErrDCPBackfillFailed occurs when there was an issue starting the backfill on
	// the server e.g. the requested start seqno was behind the purge seqno.
	ErrDCPBackfillFailed = makeStreamEndStatusError(memd.StreamEndBackfillFailed)

	// ErrDCPStreamFilterEmpty occurs when all of the collections for a DCP stream are
	// dropped.
	ErrDCPStreamFilterEmpty = makeStreamEndStatusError(memd.StreamEndFilterEmpty)

	// ErrStreamIDNotEnabled occurs when dcp operations are performed using a stream ID when stream IDs are not enabled.
	ErrStreamIDNotEnabled = errors.New("stream IDs have not been enabled on this stream")

	// ErrDCPStreamIDInvalid occurs when a dcp stream ID is invalid.
	ErrDCPStreamIDInvalid = errors.New("stream ID invalid")
)
View Source
var (
	// ErrMemdKeyNotFound occurs when an operation is performed on a key that does not exist.
	ErrMemdKeyNotFound = makeKvStatusError(memd.StatusKeyNotFound)

	// ErrMemdKeyExists occurs when an operation is performed on a key that could not be found.
	ErrMemdKeyExists = makeKvStatusError(memd.StatusKeyExists)

	// ErrMemdTooBig occurs when an operation attempts to store more data in a single document
	// than the server is capable of storing (by default, this is a 20MB limit).
	ErrMemdTooBig = makeKvStatusError(memd.StatusTooBig)

	// ErrMemdInvalidArgs occurs when the server receives invalid arguments for an operation.
	ErrMemdInvalidArgs = makeKvStatusError(memd.StatusInvalidArgs)

	// ErrMemdNotStored occurs when the server fails to store a key.
	ErrMemdNotStored = makeKvStatusError(memd.StatusNotStored)

	// ErrMemdBadDelta occurs when an invalid delta value is specified to a counter operation.
	ErrMemdBadDelta = makeKvStatusError(memd.StatusBadDelta)

	// ErrMemdNotMyVBucket occurs when an operation is dispatched to a server which is
	// non-authoritative for a specific vbucket.
	ErrMemdNotMyVBucket = makeKvStatusError(memd.StatusNotMyVBucket)

	// ErrMemdNoBucket occurs when no bucket was selected on a connection.
	ErrMemdNoBucket = makeKvStatusError(memd.StatusNoBucket)

	// ErrMemdLocked occurs when a document is already locked.
	ErrMemdLocked = makeKvStatusError(memd.StatusLocked)

	// ErrMemdConfigOnly occurs when an operation cannot be executed against a node because the bucket is in config-only
	// mode.
	ErrMemdConfigOnly = makeKvStatusError(memd.StatusConfigOnly)

	// ErrMemdNotLocked occurs when an operation attempts to unlock a document which is not locked.
	ErrMemdNotLocked = makeKvStatusError(memd.StatusNotLocked)

	// ErrMemdAuthStale occurs when authentication credentials have become invalidated.
	ErrMemdAuthStale = makeKvStatusError(memd.StatusAuthStale)

	// ErrMemdAuthError occurs when the authentication information provided was not valid.
	ErrMemdAuthError = makeKvStatusError(memd.StatusAuthError)

	// ErrMemdAuthContinue occurs in multi-step authentication when more authentication
	// work needs to be performed in order to complete the authentication process.
	ErrMemdAuthContinue = makeKvStatusError(memd.StatusAuthContinue)

	// ErrMemdRangeError occurs when the range specified to the server is not valid.
	ErrMemdRangeError = makeKvStatusError(memd.StatusRangeError)

	// ErrMemdRollback occurs when a DCP stream fails to open due to a rollback having
	// previously occurred since the last time the stream was opened.
	ErrMemdRollback = makeKvStatusError(memd.StatusRollback)

	// ErrMemdAccessError occurs when an access error occurs.
	ErrMemdAccessError = makeKvStatusError(memd.StatusAccessError)

	// ErrMemdNotInitialized is sent by servers which are still initializing, and are not
	// yet ready to accept operations on behalf of a particular bucket.
	ErrMemdNotInitialized = makeKvStatusError(memd.StatusNotInitialized)

	// ErrMemdUnknownCommand occurs when an unknown operation is sent to a server.
	ErrMemdUnknownCommand = makeKvStatusError(memd.StatusUnknownCommand)

	// ErrMemdOutOfMemory occurs when the server cannot service a request due to memory
	// limitations.
	ErrMemdOutOfMemory = makeKvStatusError(memd.StatusOutOfMemory)

	// ErrMemdNotSupported occurs when an operation is understood by the server, but that
	// operation is not supported on this server (occurs for a variety of reasons).
	ErrMemdNotSupported = makeKvStatusError(memd.StatusNotSupported)

	// ErrMemdInternalError occurs when internal errors prevent the server from processing
	// your request.
	ErrMemdInternalError = makeKvStatusError(memd.StatusInternalError)

	// ErrMemdBusy occurs when the server is too busy to process your request right away.
	// Attempting the operation at a later time will likely succeed.
	ErrMemdBusy = makeKvStatusError(memd.StatusBusy)

	// ErrMemdTmpFail occurs when a temporary failure is preventing the server from
	// processing your request.
	ErrMemdTmpFail = makeKvStatusError(memd.StatusTmpFail)

	// ErrMemdCollectionNotFound occurs when a Collection cannot be found.
	ErrMemdCollectionNotFound = makeKvStatusError(memd.StatusCollectionUnknown)

	// ErrMemdScopeNotFound occurs when a Scope cannot be found.
	ErrMemdScopeNotFound = makeKvStatusError(memd.StatusScopeUnknown)

	// ErrMemdDCPStreamIDInvalid occurs when a dcp stream ID is invalid.
	ErrMemdDCPStreamIDInvalid = makeKvStatusError(memd.StatusDCPStreamIDInvalid)

	// ErrMemdDurabilityInvalidLevel occurs when an invalid durability level was requested.
	ErrMemdDurabilityInvalidLevel = makeKvStatusError(memd.StatusDurabilityInvalidLevel)

	// ErrMemdDurabilityImpossible occurs when a request is performed with impossible
	//  durability level requirements.
	ErrMemdDurabilityImpossible = makeKvStatusError(memd.StatusDurabilityImpossible)

	// ErrMemdSyncWriteInProgess occurs when an attempt is made to write to a key that has
	//  a SyncWrite pending.
	ErrMemdSyncWriteInProgess = makeKvStatusError(memd.StatusSyncWriteInProgress)

	// ErrMemdSyncWriteAmbiguous occurs when an SyncWrite does not complete in the specified
	// time and the result is ambiguous.
	ErrMemdSyncWriteAmbiguous = makeKvStatusError(memd.StatusSyncWriteAmbiguous)

	// ErrMemdSyncWriteReCommitInProgress occurs when an SyncWrite is being recommitted.
	ErrMemdSyncWriteReCommitInProgress = makeKvStatusError(memd.StatusSyncWriteReCommitInProgress)

	// ErrMemdSubDocPathNotFound occurs when a sub-document operation targets a path
	// which does not exist in the specifie document.
	ErrMemdSubDocPathNotFound = makeKvStatusError(memd.StatusSubDocPathNotFound)

	// ErrMemdSubDocPathMismatch occurs when a sub-document operation specifies a path
	// which does not match the document structure (field access on an array).
	ErrMemdSubDocPathMismatch = makeKvStatusError(memd.StatusSubDocPathMismatch)

	// ErrMemdSubDocPathInvalid occurs when a sub-document path could not be parsed.
	ErrMemdSubDocPathInvalid = makeKvStatusError(memd.StatusSubDocPathInvalid)

	// ErrMemdSubDocPathTooBig occurs when a sub-document path is too big.
	ErrMemdSubDocPathTooBig = makeKvStatusError(memd.StatusSubDocPathTooBig)

	// ErrMemdSubDocDocTooDeep occurs when an operation would cause a document to be
	// nested beyond the depth limits allowed by the sub-document specification.
	ErrMemdSubDocDocTooDeep = makeKvStatusError(memd.StatusSubDocDocTooDeep)

	// ErrMemdSubDocCantInsert occurs when a sub-document operation could not insert.
	ErrMemdSubDocCantInsert = makeKvStatusError(memd.StatusSubDocCantInsert)

	// ErrMemdSubDocNotJSON occurs when a sub-document operation is performed on a
	// document which is not JSON.
	ErrMemdSubDocNotJSON = makeKvStatusError(memd.StatusSubDocNotJSON)

	// ErrMemdSubDocBadRange occurs when a sub-document operation is performed with
	// a bad range.
	ErrMemdSubDocBadRange = makeKvStatusError(memd.StatusSubDocBadRange)

	// ErrMemdSubDocBadDelta occurs when a sub-document counter operation is performed
	// and the specified delta is not valid.
	ErrMemdSubDocBadDelta = makeKvStatusError(memd.StatusSubDocBadDelta)

	// ErrMemdSubDocPathExists occurs when a sub-document operation expects a path not
	// to exists, but the path was found in the document.
	ErrMemdSubDocPathExists = makeKvStatusError(memd.StatusSubDocPathExists)

	// ErrMemdSubDocValueTooDeep occurs when a sub-document operation specifies a value
	// which is deeper than the depth limits of the sub-document specification.
	ErrMemdSubDocValueTooDeep = makeKvStatusError(memd.StatusSubDocValueTooDeep)

	// ErrMemdSubDocBadCombo occurs when a multi-operation sub-document operation is
	// performed and operations within the package of ops conflict with each other.
	ErrMemdSubDocBadCombo = makeKvStatusError(memd.StatusSubDocBadCombo)

	// ErrMemdSubDocBadMulti occurs when a multi-operation sub-document operation is
	// performed and operations within the package of ops conflict with each other.
	ErrMemdSubDocBadMulti = makeKvStatusError(memd.StatusSubDocBadMulti)

	// ErrMemdSubDocSuccessDeleted occurs when a multi-operation sub-document operation
	// is performed on a soft-deleted document.
	ErrMemdSubDocSuccessDeleted = makeKvStatusError(memd.StatusSubDocSuccessDeleted)

	// ErrMemdSubDocXattrInvalidFlagCombo occurs when an invalid set of
	// extended-attribute flags is passed to a sub-document operation.
	ErrMemdSubDocXattrInvalidFlagCombo = makeKvStatusError(memd.StatusSubDocXattrInvalidFlagCombo)

	// ErrMemdSubDocXattrInvalidKeyCombo occurs when an invalid set of key operations
	// are specified for a extended-attribute sub-document operation.
	ErrMemdSubDocXattrInvalidKeyCombo = makeKvStatusError(memd.StatusSubDocXattrInvalidKeyCombo)

	// ErrMemdSubDocXattrUnknownMacro occurs when an invalid macro value is specified.
	ErrMemdSubDocXattrUnknownMacro = makeKvStatusError(memd.StatusSubDocXattrUnknownMacro)

	// ErrMemdSubDocXattrUnknownVAttr occurs when an invalid virtual attribute is specified.
	ErrMemdSubDocXattrUnknownVAttr = makeKvStatusError(memd.StatusSubDocXattrUnknownVAttr)

	// ErrMemdSubDocXattrCannotModifyVAttr occurs when a mutation is attempted upon
	// a virtual attribute (which are immutable by definition).
	ErrMemdSubDocXattrCannotModifyVAttr = makeKvStatusError(memd.StatusSubDocXattrCannotModifyVAttr)

	// ErrMemdSubDocMultiPathFailureDeleted occurs when a Multi Path Failure occurs on
	// a soft-deleted document.
	ErrMemdSubDocMultiPathFailureDeleted = makeKvStatusError(memd.StatusSubDocMultiPathFailureDeleted)

	// ErrMemdRateLimitedNetworkIngress occurs when the server rate limits due to network ingress.
	ErrMemdRateLimitedNetworkIngress = makeKvStatusError(memd.StatusRateLimitedNetworkIngress)

	// ErrMemdRateLimitedNetworkEgress occurs when the server rate limits due to network egress.
	ErrMemdRateLimitedNetworkEgress = makeKvStatusError(memd.StatusRateLimitedNetworkEgress)

	// ErrMemdRateLimitedMaxConnections occurs when the server rate limits due to the application reaching the maximum
	// number of allowed connections.
	ErrMemdRateLimitedMaxConnections = makeKvStatusError(memd.StatusRateLimitedMaxConnections)

	// ErrMemdRateLimitedMaxCommands occurs when the server rate limits due to the application reaching the maximum
	// number of allowed operations.
	ErrMemdRateLimitedMaxCommands = makeKvStatusError(memd.StatusRateLimitedMaxCommands)

	// ErrMemdRateLimitedScopeSizeLimitExceeded occurs when the server rate limits due to the application reaching the maximum
	// data size allowed for the scope.
	ErrMemdRateLimitedScopeSizeLimitExceeded = makeKvStatusError(memd.StatusRateLimitedScopeSizeLimitExceeded)

	// ErrMemdRangeScanCancelled occurs during a range scan to indicate that the range scan was cancelled.
	ErrMemdRangeScanCancelled = makeKvStatusError(memd.StatusRangeScanCancelled)

	// ErrMemdRangeScanMore occurs during a range scan to indicate that a range scan has more results.
	ErrMemdRangeScanMore = makeKvStatusError(memd.StatusRangeScanMore)

	// ErrMemdRangeScanComplete occurs during a range scan to indicate that a range scan has completed.
	ErrMemdRangeScanComplete = makeKvStatusError(memd.StatusRangeScanComplete)

	// ErrMemdRangeScanVbUUIDNotEqual occurs during a range scan to indicate that a vb-uuid mismatch has occurred.
	ErrMemdRangeScanVbUUIDNotEqual = makeKvStatusError(memd.StatusRangeScanVbUUIDNotEqual)
)
View Source
var (
	// ErrNoAttempt indicates no attempt was started before an operation was performed.
	ErrNoAttempt = errors.New("attempt was not started")

	// ErrOther indicates an non-specific error has occured.
	ErrOther = errors.New("other error")

	// ErrTransient indicates a transient error occured which may succeed at a later point in time.
	ErrTransient = errors.New("transient error")

	// ErrWriteWriteConflict indicates that another transaction conflicted with this one.
	ErrWriteWriteConflict = errors.New("write write conflict")

	// ErrHard indicates that an unrecoverable error occured.
	ErrHard = errors.New("hard")

	// ErrAmbiguous indicates that a failure occured but the outcome was not known.
	ErrAmbiguous = errors.New("ambiguous error")

	// ErrAtrFull indicates that the ATR record was too full to accept a new mutation.
	ErrAtrFull = errors.New("atr full")

	// ErrAttemptExpired indicates an attempt expired.
	ErrAttemptExpired = errors.New("attempt expired")

	// ErrAtrNotFound indicates that an expected ATR document was missing.
	ErrAtrNotFound = errors.New("atr not found")

	// ErrAtrEntryNotFound indicates that an expected ATR entry was missing.
	ErrAtrEntryNotFound = errors.New("atr entry not found")

	// ErrDocAlreadyInTransaction indicates that a document is already in a transaction.
	ErrDocAlreadyInTransaction = errors.New("doc already in transaction")

	// ErrIllegalState is used for when a transaction enters an illegal State.
	ErrIllegalState = errors.New("illegal State")

	// ErrTransactionAbortedExternally indicates the transaction was aborted externally.
	ErrTransactionAbortedExternally = errors.New("transaction aborted externally")

	// ErrPreviousOperationFailed indicates a previous operation in the transaction failed.
	ErrPreviousOperationFailed = errors.New("previous operation failed")

	// ErrForwardCompatibilityFailure indicates an operation failed due to involving a document in another transaction
	// which contains features this transaction does not support.
	ErrForwardCompatibilityFailure = errors.New("forward compatibility error")
)
View Source
var (
	// UnknownRetryReason indicates that the operation failed for an unknown reason.
	UnknownRetryReason = retryReason{/* contains filtered or unexported fields */}

	// SocketNotAvailableRetryReason indicates that the operation failed because the underlying socket was not available.
	SocketNotAvailableRetryReason = retryReason{/* contains filtered or unexported fields */}

	// ServiceNotAvailableRetryReason indicates that the operation failed because the requested service was not available.
	ServiceNotAvailableRetryReason = retryReason{/* contains filtered or unexported fields */}

	// NodeNotAvailableRetryReason indicates that the operation failed because the requested node was not available.
	NodeNotAvailableRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVNotMyVBucketRetryReason indicates that the operation failed because it was sent to the wrong node for the vbucket.
	KVNotMyVBucketRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVCollectionOutdatedRetryReason indicates that the operation failed because the collection ID on the request is outdated.
	KVCollectionOutdatedRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVErrMapRetryReason indicates that the operation failed for an unsupported reason but the KV error map indicated
	// that the operation can be retried.
	KVErrMapRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVLockedRetryReason indicates that the operation failed because the document was locked.
	KVLockedRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVTemporaryFailureRetryReason indicates that the operation failed because of a temporary failure.
	KVTemporaryFailureRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVSyncWriteInProgressRetryReason indicates that the operation failed because a sync write is in progress.
	KVSyncWriteInProgressRetryReason = retryReason{/* contains filtered or unexported fields */}

	// KVSyncWriteRecommitInProgressRetryReason indicates that the operation failed because a sync write recommit is in progress.
	KVSyncWriteRecommitInProgressRetryReason = retryReason{/* contains filtered or unexported fields */}

	// ServiceResponseCodeIndicatedRetryReason indicates that the operation failed and the service responded stating that
	// the request should be retried.
	ServiceResponseCodeIndicatedRetryReason = retryReason{/* contains filtered or unexported fields */}

	// SocketCloseInFlightRetryReason indicates that the operation failed because the socket was closed whilst the operation
	// was in flight.
	SocketCloseInFlightRetryReason = retryReason{/* contains filtered or unexported fields */}

	// PipelineOverloadedRetryReason indicates that the operation failed because the pipeline queue was full.
	PipelineOverloadedRetryReason = retryReason{/* contains filtered or unexported fields */}

	// CircuitBreakerOpenRetryReason indicates that the operation failed because the circuit breaker for the underlying socket was open.
	CircuitBreakerOpenRetryReason = retryReason{/* contains filtered or unexported fields */}

	// QueryIndexNotFoundRetryReason indicates that the operation failed to to a missing query index
	QueryIndexNotFoundRetryReason = retryReason{/* contains filtered or unexported fields */}

	// QueryPreparedStatementFailureRetryReason indicates that the operation failed due to a prepared statement failure
	QueryPreparedStatementFailureRetryReason = retryReason{/* contains filtered or unexported fields */}

	// QueryErrorRetryable indicates that the operation is retryable as indicated by the query engine.
	QueryErrorRetryable = retryReason{/* contains filtered or unexported fields */}

	// AnalyticsTemporaryFailureRetryReason indicates that an analytics operation failed due to a temporary failure
	AnalyticsTemporaryFailureRetryReason = retryReason{/* contains filtered or unexported fields */}

	// SearchTooManyRequestsRetryReason indicates that a search operation failed due to too many requests
	SearchTooManyRequestsRetryReason = retryReason{/* contains filtered or unexported fields */}

	// NotReadyRetryReason indicates that the WaitUntilReady operation is not ready
	NotReadyRetryReason = retryReason{/* contains filtered or unexported fields */}

	// NoPipelineSnapshotRetryReason indicates that there was no pipeline snapshot available
	NoPipelineSnapshotRetryReason = retryReason{/* contains filtered or unexported fields */}

	// BucketNotReadyReason indicates that the user has priviledges to access the bucket but the bucket doesn't exist
	// or is in warm up.
	// Uncommitted: This API may change in the future.
	BucketNotReadyReason = retryReason{/* contains filtered or unexported fields */}

	// ConnectionErrorRetryReason indicates that there were errors reported by underlying connections.
	// Check server ports and cluster encryption setting.
	ConnectionErrorRetryReason = retryReason{/* contains filtered or unexported fields */}

	// MemdWriteFailure indicates that the operation failed because the write failed on the connection.
	MemdWriteFailure = retryReason{/* contains filtered or unexported fields */}

	// CredentialsFetchFailedRetryReason indicates that the operation failed because the AuthProvider return an error for credentials.
	// Uncommitted: This API may change in the future.
	CredentialsFetchFailedRetryReason = retryReason{/* contains filtered or unexported fields */}
)

Functions

func AcquireTimer

func AcquireTimer(d time.Duration) *time.Timer

AcquireTimer acquires a time from a global pool of timers maintained by the library.

func ControlledBackoff

func ControlledBackoff(retryAttempts uint32) time.Duration

ControlledBackoff calculates a backoff time duration from the retry attempts on a given request.

func DecodeCommonFlags

func DecodeCommonFlags(flags uint32) (DataType, CompressionType)

DecodeCommonFlags decodes a flags value into a data type and compression type using the common flags specification.

func EnableHttpResponseTracking added in v10.3.0

func EnableHttpResponseTracking()

EnableHttpResponseTracking enables tracking response bodies to ensure that they are eventually closed.

VOLATILE

This API is VOLATILE is subject to change at any time.

func EncodeCommonFlags

func EncodeCommonFlags(valueType DataType, compression CompressionType) uint32

EncodeCommonFlags encodes a data type and compression type into a flags value using the common flags specification.

func ReleaseTimer

func ReleaseTimer(t *time.Timer, wasRead bool)

ReleaseTimer returns a timer to the global pool of timers maintained by the library.

func ReportLeakedHttpResponses added in v10.3.0

func ReportLeakedHttpResponses() bool

ReportLeakedHttpResponses prints the stack traces of any response bodies that have not been closed. Returns true if all bodies have been closed, false otherwise.

VOLATILE

This API is VOLATILE is subject to change at any time.

func SaslAuthPlain

func SaslAuthPlain(username, password string, client AuthClient, deadline time.Time, cb func(err error)) error

SaslAuthPlain performs PLAIN SASL authentication against an AuthClient.

func SaslAuthScramSha1

func SaslAuthScramSha1(username, password string, client AuthClient, deadline time.Time, continueCb func(), completedCb func(err error)) error

SaslAuthScramSha1 performs SCRAM-SHA1 SASL authentication against an AuthClient.

func SaslAuthScramSha256

func SaslAuthScramSha256(username, password string, client AuthClient, deadline time.Time, continueCb func(), completedCb func(err error)) error

SaslAuthScramSha256 performs SCRAM-SHA256 SASL authentication against an AuthClient.

func SaslAuthScramSha512

func SaslAuthScramSha512(username, password string, client AuthClient, deadline time.Time, continueCb func(), completedCb func(err error)) error

SaslAuthScramSha512 performs SCRAM-SHA512 SASL authentication against an AuthClient.

func SetLogRedactionLevel

func SetLogRedactionLevel(level LogRedactLevel)

SetLogRedactionLevel specifies the level with which logs should be redacted.

func SetLogger

func SetLogger(logger Logger)

SetLogger sets a logger to be used by the library. A logger can be obtained via the DefaultStdioLogger() or VerboseStdioLogger() functions. You can also implement your own logger using the Logger interface.

func TransactionsProtocolExtensions added in v10.1.0

func TransactionsProtocolExtensions() []string

TransactionsProtocolExtensions returns a list strings representing the various features that this specific version of the library supports within its protocol version.

func TransactionsProtocolVersion added in v10.1.0

func TransactionsProtocolVersion() string

TransactionsProtocolVersion returns the protocol version that this library supports.

func Version

func Version() string

Version returns a string representation of the current SDK version.

Types

type AddOptions

type AddOptions struct {
	Key                    []byte
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	Value                  []byte
	Flags                  uint32
	Datatype               uint8
	Expiry                 uint32
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

AddOptions encapsulates the parameters for a AddEx operation.

type AdjoinCallback

type AdjoinCallback func(*AdjoinResult, error)

AdjoinCallback is invoked upon completion of a Append or Prepend operation.

type AdjoinOptions

type AdjoinOptions struct {
	Key                    []byte
	Value                  []byte
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	Cas                    Cas
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time
	PreserveExpiry         bool

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

AdjoinOptions encapsulates the parameters for a AppendEx or PrependEx operation.

type AdjoinResult

type AdjoinResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

AdjoinResult encapsulates the result of a AppendEx or PrependEx operation.

type Agent

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

Agent represents the base client handling connections to a Couchbase Server. This is used internally by the higher level classes for communicating with the cluster, it can also be used to perform more advanced operations with a cluster.

func CreateAgent

func CreateAgent(config *AgentConfig) (*Agent, error)

CreateAgent creates an agent for performing normal operations.

func (*Agent) Add

func (agent *Agent) Add(opts AddOptions, cb StoreCallback) (PendingOp, error)

Add stores a document as long as it does not already exist.

func (*Agent) AnalyticsQuery

func (agent *Agent) AnalyticsQuery(opts AnalyticsQueryOptions, cb AnalyticsQueryCallback) (PendingOp, error)

AnalyticsQuery executes an analytics query

func (*Agent) Append

func (agent *Agent) Append(opts AdjoinOptions, cb AdjoinCallback) (PendingOp, error)

Append appends some bytes to a document.

func (*Agent) BackupEps

func (agent *Agent) BackupEps() []string

BackupEps returns all the available endpoints for managing/interacting with the Backup Service.

func (*Agent) BucketName

func (agent *Agent) BucketName() string

BucketName returns the name of the bucket that the agent is using, if any. Uncommitted: This API may change in the future.

func (*Agent) CapiEps

func (agent *Agent) CapiEps() []string

CapiEps returns all the available endpoints for performing map-reduce queries.

func (*Agent) CbasEps

func (agent *Agent) CbasEps() []string

CbasEps returns all the available endpoints for performing CBAS queries.

func (*Agent) ClientID

func (agent *Agent) ClientID() string

ClientID returns the unique id for this agent

func (*Agent) Close

func (agent *Agent) Close() error

Close shuts down the agent, disconnecting from all servers and failing any outstanding operations with ErrShutdown.

func (*Agent) ConfigSnapshot

func (agent *Agent) ConfigSnapshot() (*ConfigSnapshot, error)

ConfigSnapshot returns a snapshot of the underlying configuration currently in use.

func (*Agent) Decrement

func (agent *Agent) Decrement(opts CounterOptions, cb CounterCallback) (PendingOp, error)

Decrement decrements the unsigned integer value in a document.

func (*Agent) Delete

func (agent *Agent) Delete(opts DeleteOptions, cb DeleteCallback) (PendingOp, error)

Delete removes a document.

func (*Agent) DeleteMeta

func (agent *Agent) DeleteMeta(opts DeleteMetaOptions, cb DeleteMetaCallback) (PendingOp, error)

DeleteMeta deletes a document along with setting some internal Couchbase meta-data.

func (*Agent) Diagnostics

func (agent *Agent) Diagnostics(opts DiagnosticsOptions) (*DiagnosticInfo, error)

Diagnostics returns diagnostics information about the client. Mainly containing a list of open connections and their current states.

func (*Agent) DoHTTPRequest

func (agent *Agent) DoHTTPRequest(req *HTTPRequest, cb DoHTTPRequestCallback) (PendingOp, error)

DoHTTPRequest will perform an HTTP request against one of the HTTP services which are available within the SDK.

func (*Agent) EventingEps

func (agent *Agent) EventingEps() []string

EventingEps returns all the available endpoints for managing/interacting with the Eventing Service.

func (*Agent) ForceReconnect added in v10.0.2

func (agent *Agent) ForceReconnect()

ForceReconnect gracefully rebuilds all connections being used by the agent. Any persistent in flight requests (e.g. DCP) will be terminated with ErrForcedReconnect.

Internal: This should never be used and is not supported.

func (*Agent) FtsEps

func (agent *Agent) FtsEps() []string

FtsEps returns all the available endpoints for performing FTS queries.

func (*Agent) GSIEps

func (agent *Agent) GSIEps() []string

GSIEps returns all the available endpoints for managing/interacting with the GSI Service.

func (*Agent) Get

func (agent *Agent) Get(opts GetOptions, cb GetCallback) (PendingOp, error)

Get retrieves a document.

func (*Agent) GetAllCollectionManifests

func (agent *Agent) GetAllCollectionManifests(opts GetAllCollectionManifestsOptions,
	cb GetAllCollectionManifestsCallback) (PendingOp, error)

GetAllCollectionManifests fetches the collection manifest from each server in the cluster, note that it's possible for one or mode nodes to be slightly behind when creating scopes/collections. This function will not update the client's collection id cache.

func (*Agent) GetAndLock

func (agent *Agent) GetAndLock(opts GetAndLockOptions, cb GetAndLockCallback) (PendingOp, error)

GetAndLock retrieves a document and locks it.

func (*Agent) GetAndTouch

func (agent *Agent) GetAndTouch(opts GetAndTouchOptions, cb GetAndTouchCallback) (PendingOp, error)

GetAndTouch retrieves a document and updates its expiry.

func (*Agent) GetCollectionID

func (agent *Agent) GetCollectionID(scopeName string, collectionName string, opts GetCollectionIDOptions, cb GetCollectionIDCallback) (PendingOp, error)

GetCollectionID fetches the collection id and manifest id that the collection belongs to, given a scope name and collection name. This function will also prime the client's collection id cache.

func (*Agent) GetCollectionManifest

func (agent *Agent) GetCollectionManifest(opts GetCollectionManifestOptions, cb GetCollectionManifestCallback) (PendingOp, error)

GetCollectionManifest fetches the current server manifest. This function will not update the client's collection id cache.

func (*Agent) GetMeta

func (agent *Agent) GetMeta(opts GetMetaOptions, cb GetMetaCallback) (PendingOp, error)

GetMeta retrieves a document along with some internal Couchbase meta-data.

func (*Agent) GetOneReplica

func (agent *Agent) GetOneReplica(opts GetOneReplicaOptions, cb GetReplicaCallback) (PendingOp, error)

GetOneReplica retrieves a document from a replica server.

func (*Agent) GetRandom

func (agent *Agent) GetRandom(opts GetRandomOptions, cb GetRandomCallback) (PendingOp, error)

GetRandom retrieves the key and value of a random document stored within Couchbase Server.

func (*Agent) HTTPClient

func (agent *Agent) HTTPClient() *http.Client

HTTPClient returns a pre-configured HTTP Client for communicating with Couchbase Server. You must still specify authentication information for any dispatched requests.

func (*Agent) HasCollectionsSupport

func (agent *Agent) HasCollectionsSupport() bool

HasCollectionsSupport verifies whether or not collections are available on the agent.

func (*Agent) HasSeenConfig

func (agent *Agent) HasSeenConfig() (bool, error)

HasSeenConfig returns whether or not the Agent has seen a valid cluster config. This does not mean that the agent currently has active connections. Volatile: This API is subject to change at any time.

func (*Agent) Increment

func (agent *Agent) Increment(opts CounterOptions, cb CounterCallback) (PendingOp, error)

Increment increments the unsigned integer value in a document.

func (*Agent) Internal

func (agent *Agent) Internal() *AgentInternal

Internal creates a new AgentInternal. Internal: This should never be used and is not supported.

func (*Agent) IsSecure

func (agent *Agent) IsSecure() bool

IsSecure returns whether this client is connected via SSL.

func (*Agent) LookupIn

func (agent *Agent) LookupIn(opts LookupInOptions, cb LookupInCallback) (PendingOp, error)

LookupIn performs a multiple-lookup sub-document operation on a document.

func (*Agent) MaybeRetryRequest

func (agent *Agent) MaybeRetryRequest(req RetryRequest, reason RetryReason) (bool, time.Time)

MaybeRetryRequest will possibly retry a request according to the strategy belonging to the request. It will use the reason to determine whether or not the failure reason is one that can be retried.

func (*Agent) MemdEps

func (agent *Agent) MemdEps() []string

MemdEps returns all the available endpoints for performing KV/DCP operations (using the memcached binary protocol). As apposed to other endpoints, these will have the 'couchbase(s)://' scheme prefix.

func (*Agent) MgmtEps

func (agent *Agent) MgmtEps() []string

MgmtEps returns all the available endpoints for performing management queries.

func (*Agent) MutateIn

func (agent *Agent) MutateIn(opts MutateInOptions, cb MutateInCallback) (PendingOp, error)

MutateIn performs a multiple-mutation sub-document operation on a document.

func (*Agent) N1QLQuery

func (agent *Agent) N1QLQuery(opts N1QLQueryOptions, cb N1QLQueryCallback) (PendingOp, error)

N1QLQuery executes a N1QL query

func (*Agent) N1qlEps

func (agent *Agent) N1qlEps() []string

N1qlEps returns all the available endpoints for performing N1QL queries.

func (*Agent) Observe

func (agent *Agent) Observe(opts ObserveOptions, cb ObserveCallback) (PendingOp, error)

Observe retrieves the current CAS and persistence state for a document.

func (*Agent) ObserveVb

func (agent *Agent) ObserveVb(opts ObserveVbOptions, cb ObserveVbCallback) (PendingOp, error)

ObserveVb retrieves the persistence state sequence numbers for a particular VBucket and includes additional details not included by the basic version.

func (*Agent) Ping

func (agent *Agent) Ping(opts PingOptions, cb PingCallback) (PendingOp, error)

Ping pings all of the servers we are connected to and returns a report regarding the pings that were performed.

func (*Agent) PreparedN1QLQuery

func (agent *Agent) PreparedN1QLQuery(opts N1QLQueryOptions, cb N1QLQueryCallback) (PendingOp, error)

PreparedN1QLQuery executes a prepared N1QL query

func (*Agent) Prepend

func (agent *Agent) Prepend(opts AdjoinOptions, cb AdjoinCallback) (PendingOp, error)

Prepend prepends some bytes to a document.

func (*Agent) RangeScanCreate added in v10.2.1

func (agent *Agent) RangeScanCreate(vbID uint16, opts RangeScanCreateOptions, cb RangeScanCreateCallback) (PendingOp, error)

RangeScanCreate creates a new range scan against a vbucket.

func (*Agent) ReconfigureSecurity added in v10.0.5

func (agent *Agent) ReconfigureSecurity(opts ReconfigureSecurityOptions) error

ReconfigureSecurity updates the security configuration being used by the agent. This includes the ability to toggle TLS on and off.

Calling this function will cause all underlying connections to be reconnected. The exception to this is the connection to the seed node (usually localhost), which will only be reconnected if the AuthProvider is provided on the options.

This function can only be called when the seed poller is in use i.e. when the ns_server scheme is used. Internal: This should never be used and is not supported.

func (*Agent) Replace

func (agent *Agent) Replace(opts ReplaceOptions, cb StoreCallback) (PendingOp, error)

Replace replaces the value of a Couchbase document with another value.

func (*Agent) SearchQuery

func (agent *Agent) SearchQuery(opts SearchQueryOptions, cb SearchQueryCallback) (PendingOp, error)

SearchQuery executes a Search query

func (*Agent) Set

func (agent *Agent) Set(opts SetOptions, cb StoreCallback) (PendingOp, error)

Set stores a document.

func (*Agent) SetMeta

func (agent *Agent) SetMeta(opts SetMetaOptions, cb SetMetaCallback) (PendingOp, error)

SetMeta stores a document along with setting some internal Couchbase meta-data.

func (*Agent) Stats

func (agent *Agent) Stats(opts StatsOptions, cb StatsCallback) (PendingOp, error)

Stats retrieves statistics information from the server. Note that as this function is an aggregator across numerous servers, there are no guarantees about the consistency of the results. Occasionally, some nodes may not be represented in the results, or there may be conflicting information between multiple nodes (a vbucket active on two separate nodes at once).

func (*Agent) Touch

func (agent *Agent) Touch(opts TouchOptions, cb TouchCallback) (PendingOp, error)

Touch updates the expiry for a document.

func (*Agent) Unlock

func (agent *Agent) Unlock(opts UnlockOptions, cb UnlockCallback) (PendingOp, error)

Unlock unlocks a locked document.

func (*Agent) UsingGCCCP

func (agent *Agent) UsingGCCCP() bool

UsingGCCCP returns whether or not the Agent is currently using GCCCP polling.

func (*Agent) ViewQuery

func (agent *Agent) ViewQuery(opts ViewQueryOptions, cb ViewQueryCallback) (PendingOp, error)

ViewQuery executes a view query

func (*Agent) WaitForConfigSnapshot added in v10.2.1

func (agent *Agent) WaitForConfigSnapshot(deadline time.Time, opts WaitForConfigSnapshotOptions, cb WaitForConfigSnapshotCallback) (PendingOp, error)

WaitForConfigSnapshot returns a snapshot of the underlying configuration currently in use, once one is available. Volatile: This API is subject to change at any time.

func (*Agent) WaitUntilReady

func (agent *Agent) WaitUntilReady(deadline time.Time, opts WaitUntilReadyOptions, cb WaitUntilReadyCallback) (PendingOp, error)

WaitUntilReady is used to verify that the SDK has been able to establish connections to the cluster. If no strategy is set then a fast fail retry strategy will be applied - only RetryReason that are set to always retry will be retried. This includes for WaitUntilReady, that is the SDK will wait until connections succeed or report a connection error - as soon as a connection error is reported WaitUntilReady will fail and return that error. Connection time errors are also be subject to KvConfig.ServerWaitBackoff. This is the period of time that the SDK will wait before attempting to reconnect to a node.

type AgentConfig

type AgentConfig struct {
	BucketName string
	UserAgent  string

	SeedConfig SeedConfig

	SecurityConfig SecurityConfig

	CompressionConfig CompressionConfig

	ConfigPollerConfig ConfigPollerConfig

	IoConfig IoConfig

	KVConfig KVConfig

	HTTPConfig HTTPConfig

	DefaultRetryStrategy RetryStrategy

	CircuitBreakerConfig CircuitBreakerConfig

	OrphanReporterConfig OrphanReporterConfig

	TracerConfig TracerConfig

	MeterConfig MeterConfig

	InternalConfig InternalConfig
}

AgentConfig specifies the configuration options for creation of an Agent.

func (*AgentConfig) FromConnStr

func (config *AgentConfig) FromConnStr(connStr string) error

FromConnStr populates the AgentConfig with information from a Couchbase Connection String. Supported options are:

	bootstrap_on (bool) - Specifies what protocol to bootstrap on (cccp, http).
	ca_cert_path (string) - Specifies the path to a CA certificate.
	network (string) - The network type to use.
	kv_connect_timeout (duration) - Maximum period to attempt to connect to cluster in ms.
	config_poll_interval (duration) - Period to wait between CCCP config polling in ms.
	config_poll_timeout (duration) - Maximum period of time to wait for a CCCP request.
	compression (bool) - Whether to enable network-wise compression of documents.
	compression_min_size (int) - The minimal size of the document in bytes to consider compression.
	compression_min_ratio (float64) - The minimal compress ratio (compressed / original) for the document to be sent compressed.
	enable_server_durations (bool) - Whether to enable fetching server operation durations.
	max_idle_http_connections (int) - Maximum number of idle http connections in the pool.
	max_perhost_idle_http_connections (int) - Maximum number of idle http connections in the pool per host.
	idle_http_connection_timeout (duration) - Maximum length of time for an idle connection to stay in the pool in ms.
	orphaned_response_logging (bool) - Whether to enable orphaned response logging.
	orphaned_response_logging_interval (duration) - How often to print the orphan log records.
	orphaned_response_logging_sample_size (int) - The maximum number of orphan log records to track.
	dcp_priority (int) - Specifies the priority to request from the Cluster when connecting for DCP.
	enable_dcp_expiry (bool) - Whether to enable the feature to distinguish between explicit delete and expired delete on DCP.
	http_redial_period (duration) - The maximum length of time for the HTTP poller to stay connected before reconnecting.
	http_retry_delay (duration) - The length of time to wait between HTTP poller retries if connecting fails.
	kv_pool_size (int) - The number of connections to create to each kv node.
	max_queue_size (int) - The maximum number of requests that can be queued for sending per connection.
	unordered_execution_enabled (bool) - Whether to enabled the "out of order responses" feature.
 server_wait_backoff (duration) -The period of time waited between kv reconnect attmepts to a node after connection failure

type AgentGroup

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

AgentGroup represents a collection of agents that can be used for performing operations against a cluster. It holds an internal special agent type which does not create its own memcached connections but registers itself for cluster config updates on all agents that are created through it.

func CreateAgentGroup

func CreateAgentGroup(config *AgentGroupConfig) (*AgentGroup, error)

CreateAgentGroup will return a new AgentGroup with a base config of the config provided. Volatile: AgentGroup is subject to change or removal.

func (*AgentGroup) AnalyticsQuery

func (ag *AgentGroup) AnalyticsQuery(opts AnalyticsQueryOptions, cb AnalyticsQueryCallback) (PendingOp, error)

AnalyticsQuery executes an analytics query against a random connected agent. If no agent is connected then this will block until one is available or the deadline is reached.

func (*AgentGroup) Close

func (ag *AgentGroup) Close() error

Close will close all underlying agents.

func (*AgentGroup) Diagnostics

func (ag *AgentGroup) Diagnostics(opts DiagnosticsOptions) (*DiagnosticInfo, error)

Diagnostics returns diagnostics information about the client. Mainly containing a list of open connections and their current states.

func (*AgentGroup) DoHTTPRequest

func (ag *AgentGroup) DoHTTPRequest(req *HTTPRequest, cb DoHTTPRequestCallback) (PendingOp, error)

DoHTTPRequest will perform an HTTP request against one of the HTTP services which are available within the SDK, using a random connected agent. If no agent is connected then this will block until one is available or the deadline is reached.

func (*AgentGroup) GetAgent

func (ag *AgentGroup) GetAgent(bucketName string) *Agent

GetAgent will return the agent, if any, corresponding to the bucket name specified.

func (*AgentGroup) Internal added in v10.4.0

func (ag *AgentGroup) Internal() *AgentGroupInternal

Internal creates a new AgentGroupInternal. Internal: This should never be used and is not supported.

func (*AgentGroup) N1QLQuery

func (ag *AgentGroup) N1QLQuery(opts N1QLQueryOptions, cb N1QLQueryCallback) (PendingOp, error)

N1QLQuery executes a N1QL query against a random connected agent. If no agent is connected then this will block until one is available or the deadline is reached.

func (*AgentGroup) OpenBucket

func (ag *AgentGroup) OpenBucket(bucketName string) error

OpenBucket will attempt to open a new bucket against the cluster. If an agent using the specified bucket name already exists then this will not open a new connection.

func (*AgentGroup) Ping

func (ag *AgentGroup) Ping(opts PingOptions, cb PingCallback) (PendingOp, error)

Ping pings all of the servers we are connected to and returns a report regarding the pings that were performed.

func (*AgentGroup) PreparedN1QLQuery

func (ag *AgentGroup) PreparedN1QLQuery(opts N1QLQueryOptions, cb N1QLQueryCallback) (PendingOp, error)

PreparedN1QLQuery executes a prepared N1QL query against a random connected agent. If no agent is connected then this will block until one is available or the deadline is reached.

func (*AgentGroup) SearchQuery

func (ag *AgentGroup) SearchQuery(opts SearchQueryOptions, cb SearchQueryCallback) (PendingOp, error)

SearchQuery executes a Search query against a random connected agent. If no agent is connected then this will block until one is available or the deadline is reached.

func (*AgentGroup) WaitUntilReady

func (ag *AgentGroup) WaitUntilReady(deadline time.Time, opts WaitUntilReadyOptions,
	cb WaitUntilReadyCallback) (PendingOp, error)

WaitUntilReady returns whether or not the AgentGroup can ping the requested services. This can only be used when no bucket has been opened, if a bucket has been opened then you *must* use the agent belonging to that bucket.

type AgentGroupConfig

type AgentGroupConfig struct {
	AgentConfig
}

AgentGroupConfig specifies the configuration options for creation of an AgentGroup.

func (*AgentGroupConfig) FromConnStr

func (config *AgentGroupConfig) FromConnStr(connStr string) error

FromConnStr populates the AgentGroupConfig with information from a Couchbase Connection String. See AgentConfig for supported options.

type AgentGroupInternal added in v10.4.0

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

AgentGroupInternal is a set of internal-only functionality. Internal: This should never be used and is not supported.

func (*AgentGroupInternal) SearchCapabilityStatus added in v10.4.0

func (agi *AgentGroupInternal) SearchCapabilityStatus(cap SearchCapability) CapabilityStatus

SearchCapabilityStatus returns the current status for a given search capability. Internal: This should never be used and is not supported.

type AgentInternal

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

AgentInternal is a set of internal only functionality. Internal: This should never be used and is not supported.

func (*AgentInternal) BucketCapabilityStatus

func (ai *AgentInternal) BucketCapabilityStatus(cap BucketCapability) CapabilityStatus

BucketCapabilityStatus returns the current status for a given bucket capability.

type AnalyticsError

type AnalyticsError struct {
	InnerError      error
	Statement       string
	ClientContextID string
	Errors          []AnalyticsErrorDesc
	Endpoint        string
	RetryReasons    []RetryReason
	RetryAttempts   uint32
	// Uncommitted: This API may change in the future.
	ErrorText string
	// Uncommitted: This API may change in the future.
	HTTPResponseCode int
}

AnalyticsError represents an error returned from an analytics query.

func (AnalyticsError) Error

func (e AnalyticsError) Error() string

Error returns the string representation of this error.

func (AnalyticsError) MarshalJSON

func (e AnalyticsError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (AnalyticsError) Unwrap

func (e AnalyticsError) Unwrap() error

Unwrap returns the underlying reason for the error

type AnalyticsErrorDesc

type AnalyticsErrorDesc struct {
	Code    uint32
	Message string
}

AnalyticsErrorDesc represents specific analytics error data.

type AnalyticsQueryCallback

type AnalyticsQueryCallback func(*AnalyticsRowReader, error)

AnalyticsQueryCallback is invoked upon completion of a AnalyticsQuery operation.

type AnalyticsQueryOptions

type AnalyticsQueryOptions struct {
	Payload       []byte
	Priority      int
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

AnalyticsQueryOptions represents the various options available for an analytics query.

type AnalyticsRowReader

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

AnalyticsRowReader providers access to the rows of a analytics query

func (*AnalyticsRowReader) Close

func (q *AnalyticsRowReader) Close() error

Close immediately shuts down the connection

func (AnalyticsRowReader) Err

func (q AnalyticsRowReader) Err() error

Err returns any errors that occurred during streaming.

func (*AnalyticsRowReader) MetaData

func (q *AnalyticsRowReader) MetaData() ([]byte, error)

MetaData fetches the non-row bytes streamed in the response.

func (*AnalyticsRowReader) NextRow

func (q *AnalyticsRowReader) NextRow() []byte

NextRow reads the next rows bytes from the stream

type AuthCertRequest

type AuthCertRequest struct {
	Service  ServiceType
	Endpoint string
}

AuthCertRequest represents a certificate details request from the agent.

type AuthClient

type AuthClient interface {
	Address() string
	SupportsFeature(feature memd.HelloFeature) bool

	SaslListMechs(deadline time.Time, cb func(mechs []AuthMechanism, err error)) error
	SaslAuth(k, v []byte, deadline time.Time, cb func(b []byte, err error)) error
	SaslStep(k, v []byte, deadline time.Time, cb func(err error)) error
}

AuthClient exposes an interface for performing authentication on a connected Couchbase K/V client.

type AuthCredsRequest

type AuthCredsRequest struct {
	Service  ServiceType
	Endpoint string
}

AuthCredsRequest represents an authentication details request from the agent.

type AuthMechanism

type AuthMechanism string

AuthMechanism represents a type of auth that can be performed.

type AuthProvider

type AuthProvider interface {
	SupportsTLS() bool
	SupportsNonTLS() bool
	Certificate(req AuthCertRequest) (*tls.Certificate, error)
	Credentials(req AuthCredsRequest) ([]UserPassPair, error)
}

AuthProvider is an interface to allow the agent to fetch authentication credentials on-demand from the application.

type BackoffCalculator

type BackoffCalculator func(retryAttempts uint32) time.Duration

BackoffCalculator is used by retry strategies to calculate backoff durations.

func ExponentialBackoff

func ExponentialBackoff(min, max time.Duration, backoffFactor float64) BackoffCalculator

ExponentialBackoff calculates a backoff time duration from the retry attempts on a given request.

type BestEffortRetryStrategy

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

BestEffortRetryStrategy represents a strategy that will keep retrying until it succeeds (or the caller times out the request).

func NewBestEffortRetryStrategy

func NewBestEffortRetryStrategy(calculator BackoffCalculator) *BestEffortRetryStrategy

NewBestEffortRetryStrategy returns a new BestEffortRetryStrategy which will use the supplied calculator function to calculate retry durations. If calculator is nil then ControlledBackoff will be used.

func (*BestEffortRetryStrategy) RetryAfter

func (rs *BestEffortRetryStrategy) RetryAfter(req RetryRequest, reason RetryReason) RetryAction

RetryAfter calculates and returns a RetryAction describing how long to wait before retrying an operation.

type BucketCapability

type BucketCapability uint32
const (
	BucketCapabilityDurableWrites        BucketCapability = 0x00
	BucketCapabilityCreateAsDeleted      BucketCapability = 0x01
	BucketCapabilityReplaceBodyWithXattr BucketCapability = 0x02
	BucketCapabilityRangeScan            BucketCapability = 0x03
	BucketCapabilityReplicaRead          BucketCapability = 0x04
	BucketCapabilityNonDedupedHistory    BucketCapability = 0x05
)

type BucketCapabilityStatus deprecated

type BucketCapabilityStatus = CapabilityStatus

Deprecated: Use CapabilityStatus instead

type CapabilityStatus added in v10.4.0

type CapabilityStatus uint32
const (
	CapabilityStatusUnknown CapabilityStatus = iota
	CapabilityStatusSupported
	CapabilityStatusUnsupported
)

type Cas

type Cas uint64

Cas represents a unique revision of a document. This can be used to perform optimistic locking.

type CircuitBreakerCallback

type CircuitBreakerCallback func(error) bool

CircuitBreakerCallback is the callback used by the circuit breaker to determine if an error should count toward the circuit breaker failure count.

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Enabled bool
	// VolumeThreshold is the minimum amount of operations to measure before the threshold percentage kicks in.
	VolumeThreshold int64
	// ErrorThresholdPercentage is the percentage of operations that need to fail in a window until the circuit opens.
	ErrorThresholdPercentage float64
	// SleepWindow is the initial sleep time after which a canary is sent as a probe.
	SleepWindow time.Duration
	// RollingWindow is the rolling timeframe which is used to calculate the error threshold percentage.
	RollingWindow time.Duration
	// CompletionCallback is called on every response to determine if it is successful or not.
	CompletionCallback CircuitBreakerCallback
	// CanaryTimeout is the timeout for the canary request until it is deemed failed.
	CanaryTimeout time.Duration
}

CircuitBreakerConfig is the set of configuration settings for configuring circuit breakers. If Disabled is set to true then a noop circuit breaker will be used, otherwise a lazy circuit breaker.

type CloseStreamCallback

type CloseStreamCallback func(error)

CloseStreamCallback is invoked with the results of `CloseStream` operations.

type CloseStreamOptions

type CloseStreamOptions struct {
	StreamOptions *CloseStreamStreamOptions
}

CloseStreamOptions are the options available to the CloseStream operation.

type CloseStreamStreamOptions

type CloseStreamStreamOptions struct {
	StreamID uint16
}

CloseStreamStreamOptions are the stream options available to the CloseStream operation.

type ClusterState

type ClusterState uint32

ClusterState is used to describe the state of a cluster.

type CompressionConfig

type CompressionConfig struct {
	Enabled              bool
	DisableDecompression bool
	MinSize              int
	MinRatio             float64
}

CompressionConfig specifies options for controlling compression applied to documents using KV.

type CompressionType

type CompressionType uint32

CompressionType indicates the type of compression for a value

type ConfigPollerConfig

type ConfigPollerConfig struct {
	HTTPRedialPeriod time.Duration
	HTTPRetryDelay   time.Duration
	HTTPMaxWait      time.Duration
	CccpMaxWait      time.Duration
	CccpPollPeriod   time.Duration
}

ConfigPollerConfig specifies options for controlling the cluster configuration pollers.

type ConfigSnapshot

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

ConfigSnapshot is a snapshot of the underlying configuration currently in use.

func (ConfigSnapshot) BucketUUID

func (pi ConfigSnapshot) BucketUUID() string

BucketUUID returns the UUID of the bucket we are connected to.

func (ConfigSnapshot) KeyToServer

func (pi ConfigSnapshot) KeyToServer(key []byte, replicaIdx uint32) (int, error)

KeyToServer translates a particular key to its assigned server index.

func (ConfigSnapshot) KeyToVbucket

func (pi ConfigSnapshot) KeyToVbucket(key []byte) (uint16, error)

KeyToVbucket translates a particular key to its assigned vbucket.

func (ConfigSnapshot) NumReplicas

func (pi ConfigSnapshot) NumReplicas() (int, error)

NumReplicas returns the number of replicas configured on the connected cluster.

func (ConfigSnapshot) NumServers

func (pi ConfigSnapshot) NumServers() (int, error)

NumServers returns the number of servers accessible for K/V.

func (ConfigSnapshot) NumVbuckets

func (pi ConfigSnapshot) NumVbuckets() (int, error)

NumVbuckets returns the number of VBuckets configured on the connected cluster.

func (ConfigSnapshot) RevID

func (pi ConfigSnapshot) RevID() int64

RevID returns the config revision for this snapshot.

func (ConfigSnapshot) VbucketToServer

func (pi ConfigSnapshot) VbucketToServer(vbID uint16, replicaIdx uint32) (int, error)

VbucketToServer returns the server index for a particular vbucket.

func (ConfigSnapshot) VbucketsOnServer

func (pi ConfigSnapshot) VbucketsOnServer(index int) ([]uint16, error)

VbucketsOnServer returns the list of VBuckets for a server.

type Counter

type Counter interface {
	IncrementBy(num uint64)
}

Counter is used for incrementing a synchronous count metric.

type CounterCallback

type CounterCallback func(*CounterResult, error)

CounterCallback is invoked upon completion of a Increment or Decrement operation.

type CounterOptions

type CounterOptions struct {
	Key                    []byte
	Delta                  uint64
	Initial                uint64
	Expiry                 uint32
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	Cas                    Cas
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time
	PreserveExpiry         bool

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

CounterOptions encapsulates the parameters for a IncrementEx or DecrementEx operation.

type CounterResult

type CounterResult struct {
	Value         uint64
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

CounterResult encapsulates the result of a IncrementEx or DecrementEx operation.

type DCPAgent

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

DCPAgent represents the base client handling DCP connections to a Couchbase Server.

func CreateDcpAgent

func CreateDcpAgent(config *DCPAgentConfig, dcpStreamName string, openFlags memd.DcpOpenFlag) (*DCPAgent, error)

CreateDcpAgent creates an agent for performing DCP operations.

func (*DCPAgent) Close

func (agent *DCPAgent) Close() error

Close shuts down the agent, disconnecting from all servers and failing any outstanding operations with ErrShutdown.

func (*DCPAgent) CloseStream

func (agent *DCPAgent) CloseStream(vbID uint16, opts CloseStreamOptions, cb CloseStreamCallback) (PendingOp, error)

CloseStream shuts down an open stream for the specified VBucket.

func (*DCPAgent) ConfigSnapshot

func (agent *DCPAgent) ConfigSnapshot() (*ConfigSnapshot, error)

ConfigSnapshot returns a snapshot of the underlying configuration currently in use.

func (*DCPAgent) ForceReconnect added in v10.0.2

func (agent *DCPAgent) ForceReconnect()

ForceReconnect gracefully rebuilds all connections being used by the agent. Any persistent in flight requests (e.g. DCP) will be terminated with ErrForcedReconnect.

Internal: This should never be used and is not supported.

func (*DCPAgent) GetFailoverLog

func (agent *DCPAgent) GetFailoverLog(vbID uint16, cb GetFailoverLogCallback) (PendingOp, error)

GetFailoverLog retrieves the fail-over log for a particular VBucket. This is used to resume an interrupted stream after a node fail-over has occurred.

func (*DCPAgent) GetVbucketSeqnos

func (agent *DCPAgent) GetVbucketSeqnos(serverIdx int, state memd.VbucketState, opts GetVbucketSeqnoOptions,
	cb GetVBucketSeqnosCallback) (PendingOp, error)

GetVbucketSeqnos returns the last checkpoint for a particular VBucket. This is useful for starting a DCP stream from wherever the server currently is.

func (*DCPAgent) HasCollectionsSupport

func (agent *DCPAgent) HasCollectionsSupport() bool

HasCollectionsSupport verifies whether or not collections are available on the agent.

func (*DCPAgent) IsSecure

func (agent *DCPAgent) IsSecure() bool

IsSecure returns whether this client is connected via SSL.

func (*DCPAgent) OpenStream

func (agent *DCPAgent) OpenStream(vbID uint16, flags memd.DcpStreamAddFlag, vbUUID VbUUID, startSeqNo,
	endSeqNo, snapStartSeqNo, snapEndSeqNo SeqNo, evtHandler StreamObserver, opts OpenStreamOptions,
	cb OpenStreamCallback) (PendingOp, error)

OpenStream opens a DCP stream for a particular VBucket and, optionally, filter.

func (*DCPAgent) ReconfigureSecurity added in v10.0.5

func (agent *DCPAgent) ReconfigureSecurity(opts ReconfigureSecurityOptions) error

ReconfigureSecurity updates the security configuration being used by the agent. This includes the ability to toggle TLS on and off.

Calling this function will cause all underlying connections to be reconnected. The exception to this is the connection to the seed node (usually localhost), which will only be reconnected if the AuthProvider is provided on the options.

This function can only be called when the seed poller is in use i.e. when the ns_server scheme is used. Internal: This should never be used and is not supported.

func (*DCPAgent) WaitUntilReady

func (agent *DCPAgent) WaitUntilReady(deadline time.Time, opts WaitUntilReadyOptions,
	cb WaitUntilReadyCallback) (PendingOp, error)

WaitUntilReady is used to verify that the SDK has been able to establish connections to the cluster. If no strategy is set then a fast fail retry strategy will be applied - only RetryReason that are set to always retry will be retried. This is includes for WaitUntilReady, that is the SDK will wait until connections succeed or report a connection error - as soon as a connection error is reported WaitUntilReady will fail and return that error. Connection time errors are also be subject to KvConfig.ServerWaitBackoff. This is the period of time that the SDK will wait before attempting to reconnect to a node.

type DCPAgentConfig

type DCPAgentConfig struct {
	UserAgent  string
	BucketName string

	SeedConfig SeedConfig

	SecurityConfig SecurityConfig

	CompressionConfig CompressionConfig

	ConfigPollerConfig ConfigPollerConfig

	// EnableCCCPPoller will enable the use of the CCCP poller for the SDK.
	// By default, only HTTP polling is used and CCCP polling during a DCP stream is discouraged.
	EnableCCCPPoller bool

	IoConfig IoConfig

	KVConfig KVConfig

	HTTPConfig HTTPConfig

	DCPConfig DCPConfig
}

DCPAgentConfig specifies the configuration options for creation of a DCPAgent.

func (*DCPAgentConfig) FromConnStr

func (config *DCPAgentConfig) FromConnStr(connStr string) error

FromConnStr populates the AgentConfig with information from a Couchbase Connection String. Supported options are:

ca_cert_path (string) - Specifies the path to a CA certificate.
network (string) - The network type to use.
kv_connect_timeout (duration) - Maximum period to attempt to connect to cluster in ms.
config_poll_interval (duration) - Period to wait between CCCP config polling in ms.
config_poll_timeout (duration) - Maximum period of time to wait for a CCCP request.
compression (bool) - Whether to enable network-wise compression of documents.
compression_min_size (int) - The minimal size of the document in bytes to consider compression.
compression_min_ratio (float64) - The minimal compress ratio (compressed / original) for the document to be sent compressed.
orphaned_response_logging (bool) - Whether to enable orphaned response logging.
orphaned_response_logging_interval (duration) - How often to print the orphan log records.
orphaned_response_logging_sample_size (int) - The maximum number of orphan log records to track.
dcp_priority (int) - Specifies the priority to request from the Cluster when connecting for DCP.
enable_dcp_change_streams (bool) - Enables the DCP connection to allow history snapshots in DCP streams.
enable_dcp_expiry (bool) - Whether to enable the feature to distinguish between explicit delete and expired delete on DCP.
kv_pool_size (int) - The number of connections to create to each kv node.
max_queue_size (int) - The maximum number of requests that can be queued for sending per connection.
max_idle_http_connections (int) - Maximum number of idle http connections in the pool.
max_perhost_idle_http_connections (int) - Maximum number of idle http connections in the pool per host.
idle_http_connection_timeout (duration) - Maximum length of time for an idle connection to stay in the pool in ms.
http_redial_period (duration) - The maximum length of time for the HTTP poller to stay connected before reconnecting.
http_retry_delay (duration) - The length of time to wait between HTTP poller retries if connecting fails.

type DCPBackfillOrder

type DCPBackfillOrder uint8

DCPBackfillOrder represents the order in which vBuckets will be backfilled by the cluster.

const (
	// DCPBackfillOrderRoundRobin means that all the requested vBuckets will be backfilled together where each vBucket
	// has some data backfilled before moving on to the next. This is the default behaviour.
	DCPBackfillOrderRoundRobin DCPBackfillOrder = iota + 1

	// DCPBackfillOrderSequential means that all the data for the first vBucket will be streamed before advancing onto
	// the next vBucket.
	DCPBackfillOrderSequential
)

type DCPConfig

type DCPConfig struct {
	AgentPriority    DcpAgentPriority
	UseChangeStreams bool
	UseExpiryOpcode  bool
	UseStreamID      bool
	UseOSOBackfill   bool
	BackfillOrder    DCPBackfillOrder

	BufferSize                   int
	DisableBufferAcknowledgement bool
}

DCPConfig specifies DCP specific configuration options.

type DCPRollbackError added in v10.0.10

type DCPRollbackError struct {
	InnerError error
	SeqNo      SeqNo
}

func (DCPRollbackError) Error added in v10.0.10

func (e DCPRollbackError) Error() string

Error returns the string representation of this error.

func (DCPRollbackError) MarshalJSON added in v10.0.10

func (e DCPRollbackError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (DCPRollbackError) Unwrap added in v10.0.10

func (err DCPRollbackError) Unwrap() error

Unwrap returns the underlying reason for the error

type DataType

type DataType uint32

DataType represents the type of data for a value

type DcpAgentPriority

type DcpAgentPriority uint8

DcpAgentPriority specifies the priority level for a dcp stream

type DcpCollectionCreation

type DcpCollectionCreation struct {
	SeqNo        uint64
	Version      uint8
	VbID         uint16
	ManifestUID  uint64
	ScopeID      uint32
	CollectionID uint32
	Ttl          uint32
	StreamID     uint16
	Key          []byte
}

DcpCollectionCreation represents a collection create DCP event from the server

type DcpCollectionDeletion

type DcpCollectionDeletion struct {
	SeqNo        uint64
	ManifestUID  uint64
	ScopeID      uint32
	CollectionID uint32
	StreamID     uint16
	VbID         uint16
	Version      uint8
}

DcpCollectionDeleteion represents a collection delete DCP event from the server

type DcpCollectionFlush

type DcpCollectionFlush struct {
	SeqNo        uint64
	Version      uint8
	VbID         uint16
	ManifestUID  uint64
	CollectionID uint32
	StreamID     uint16
}

DcpCollectionFlush represents a collection flush DCP event from the server

type DcpCollectionModification

type DcpCollectionModification struct {
	SeqNo        uint64
	ManifestUID  uint64
	CollectionID uint32
	Ttl          uint32
	VbID         uint16
	StreamID     uint16
	Version      uint8
}

DcpCollectionModification represents a DCP collection modify event from the server

type DcpDeletion

type DcpDeletion struct {
	SeqNo, RevNo uint64
	Cas          uint64
	DeleteTime   uint32
	CollectionID uint32
	VbID         uint16
	StreamID     uint16
	Datatype     uint8
	Key, Value   []byte
}

DcpDeletion represents a single DCP deletion from the server

type DcpExpiration

type DcpExpiration struct {
	SeqNo, RevNo uint64
	Cas          uint64
	DeleteTime   uint32
	CollectionID uint32
	VbID         uint16
	StreamID     uint16
	Key          []byte
}

DcpExpiration represents a single DCP expiration from the server

type DcpMutation

type DcpMutation struct {
	SeqNo, RevNo            uint64
	Cas                     uint64
	Flags, Expiry, LockTime uint32
	CollectionID            uint32
	VbID                    uint16
	StreamID                uint16
	Datatype                uint8
	Key, Value              []byte
}

DcpMutation represents a single DCP mutation from the server

type DcpOSOSnapshot

type DcpOSOSnapshot struct {
	SnapshotType uint32
	VbID         uint16
	StreamID     uint16
}

DcpOSOSnapshot reprensents a DCP OSSSnapshot from the server

type DcpScopeCreation

type DcpScopeCreation struct {
	SeqNo       uint64
	Version     uint8
	VbID        uint16
	ManifestUID uint64
	ScopeID     uint32
	StreamID    uint16
	Key         []byte
}

DcpScopeCreation represents a scope creation DCP event from the server

type DcpScopeDeletion

type DcpScopeDeletion struct {
	SeqNo       uint64
	Version     uint8
	VbID        uint16
	ManifestUID uint64
	ScopeID     uint32
	StreamID    uint16
}

DcpScopeDeletion represents a scope Deletion DCP event from the server

type DcpSeqNoAdvanced

type DcpSeqNoAdvanced struct {
	SeqNo    uint64
	VbID     uint16
	StreamID uint16
}

DcpSeqNoAdvanced represents a DCP SeqNoAdvanced from the server

type DcpSnapshotMarker

type DcpSnapshotMarker struct {
	StartSeqNo, EndSeqNo                                   uint64
	VbID, StreamID                                         uint16
	SnapshotType                                           SnapshotState
	MaxVisibleSeqNo, HighCompletedSeqNo, SnapshotTimeStamp uint64
}

DcpSnapshotMarker represents a single response from the server

type DcpStreamEnd

type DcpStreamEnd struct {
	VbID     uint16
	StreamID uint16
}

DcpStreamEnd represnets a DCP stream end from the server

type DeleteCallback

type DeleteCallback func(*DeleteResult, error)

DeleteCallback is invoked upon completion of a Delete operation.

type DeleteMetaCallback

type DeleteMetaCallback func(*DeleteMetaResult, error)

DeleteMetaCallback is invoked upon completion of a DeleteMeta operation.

type DeleteMetaOptions

type DeleteMetaOptions struct {
	Key            []byte
	Value          []byte
	Extra          []byte
	Datatype       uint8
	Options        uint32
	Flags          uint32
	Expiry         uint32
	Cas            Cas
	RevNo          uint64
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

DeleteMetaOptions encapsulates the parameters for a DeleteMetaEx operation.

type DeleteMetaResult

type DeleteMetaResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

DeleteMetaResult encapsulates the result of a DeleteMetaEx operation.

type DeleteOptions

type DeleteOptions struct {
	Key                    []byte
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	Cas                    Cas
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

DeleteOptions encapsulates the parameters for a DeleteEx operation.

type DeleteResult

type DeleteResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

DeleteResult encapsulates the result of a DeleteEx operation.

type DiagnosticInfo

type DiagnosticInfo struct {
	ConfigRev int64
	MemdConns []MemdConnInfo
	State     ClusterState
}

DiagnosticInfo is returned by the Diagnostics method and includes information about the overall health of the clients connections.

type DiagnosticsOptions

type DiagnosticsOptions struct {
}

DiagnosticsOptions encapsulates the parameters for a Diagnostics operation.

type DoHTTPRequestCallback

type DoHTTPRequestCallback func(*HTTPResponse, error)

DoHTTPRequestCallback is invoked upon completion of a DoHTTPRequest operation.

type EndpointPingResult

type EndpointPingResult struct {
	Endpoint string
	Error    error
	Latency  time.Duration
	ID       string
	Scope    string
	State    PingState
}

EndpointPingResult contains the results of a ping to a single server.

type EndpointState

type EndpointState uint32

EndpointState is the current connection state of an endpoint.

const (
	// EndpointStateDisconnected indicates that the endpoint is disconnected.
	EndpointStateDisconnected EndpointState = 1

	// EndpointStateConnecting indicates that the endpoint is connecting.
	EndpointStateConnecting EndpointState = 2

	// EndpointStateConnected indicates that the endpoint is connected.
	EndpointStateConnected EndpointState = 3

	// EndpointStateDisconnecting indicates that the endpoint is disconnecting.
	EndpointStateDisconnecting EndpointState = 4
)

type ExecHelloResponse

type ExecHelloResponse struct {
	SrvFeatures []memd.HelloFeature
	Err         error
}

ExecHelloResponse contains the features and/or error from an ExecHello operation.

type FailoverEntry

type FailoverEntry struct {
	VbUUID VbUUID
	SeqNo  SeqNo
}

FailoverEntry represents a single entry in the server fail-over log.

type GetAllCollectionManifestsCallback

type GetAllCollectionManifestsCallback func(*GetAllCollectionManifestsResult, error)

GetAllCollectionManifestsCallback is invoked upon completion of a GetAllCollectionManifests operation.

type GetAllCollectionManifestsOptions

type GetAllCollectionManifestsOptions struct {
	TraceContext  RequestSpanContext
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string
}

GetAllCollectionManifestsOptions are the options available to the GetAllCollectionManifests command.

type GetAllCollectionManifestsResult

type GetAllCollectionManifestsResult struct {
	Manifests map[string]SingleServerManifestResult
}

GetAllCollectionManifestsResult encapsulates the result of a GetAllCollectionManifests operation.

type GetAndLockCallback

type GetAndLockCallback func(*GetAndLockResult, error)

GetAndLockCallback is invoked upon completion of a GetAndLock operation.

type GetAndLockOptions

type GetAndLockOptions struct {
	Key            []byte
	LockTime       uint32
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetAndLockOptions encapsulates the parameters for a GetAndLockEx operation.

type GetAndLockResult

type GetAndLockResult struct {
	Value    []byte
	Flags    uint32
	Datatype uint8
	Cas      Cas

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetAndLockResult encapsulates the result of a GetAndLockEx operation.

type GetAndTouchCallback

type GetAndTouchCallback func(*GetAndTouchResult, error)

GetAndTouchCallback is invoked upon completion of a GetAndTouch operation.

type GetAndTouchOptions

type GetAndTouchOptions struct {
	Key            []byte
	Expiry         uint32
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetAndTouchOptions encapsulates the parameters for a GetAndTouchEx operation.

type GetAndTouchResult

type GetAndTouchResult struct {
	Value    []byte
	Flags    uint32
	Datatype uint8
	Cas      Cas

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetAndTouchResult encapsulates the result of a GetAndTouchEx operation.

type GetAnyReplicaOptions

type GetAnyReplicaOptions struct {
	Key            []byte
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetAnyReplicaOptions encapsulates the parameters for a GetAnyReplicaEx operation.

type GetCallback

type GetCallback func(*GetResult, error)

GetCallback is invoked upon completion of a Get operation.

type GetCollectionIDCallback

type GetCollectionIDCallback func(*GetCollectionIDResult, error)

GetCollectionIDCallback is invoked upon completion of a GetCollectionID operation.

type GetCollectionIDOptions

type GetCollectionIDOptions struct {
	RetryStrategy RetryStrategy
	TraceContext  RequestSpanContext
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string
}

GetCollectionIDOptions are the options available to the GetCollectionID command.

type GetCollectionIDResult

type GetCollectionIDResult struct {
	ManifestID   uint64
	CollectionID uint32

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetCollectionIDResult encapsulates the result of a GetCollectionID operation.

type GetCollectionManifestCallback

type GetCollectionManifestCallback func(*GetCollectionManifestResult, error)

GetCollectionManifestCallback is invoked upon completion of a GetCollectionManifest operation.

type GetCollectionManifestOptions

type GetCollectionManifestOptions struct {
	TraceContext  RequestSpanContext
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string
}

GetCollectionManifestOptions are the options available to the GetCollectionManifest command.

type GetCollectionManifestResult

type GetCollectionManifestResult struct {
	Manifest []byte

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetCollectionManifestResult encapsulates the result of a GetCollectionManifest operation.

type GetFailoverLogCallback

type GetFailoverLogCallback func([]FailoverEntry, error)

GetFailoverLogCallback is invoked with the results of `GetFailoverLog` operations.

type GetMetaCallback

type GetMetaCallback func(*GetMetaResult, error)

GetMetaCallback is invoked upon completion of a GetMeta operation.

type GetMetaOptions

type GetMetaOptions struct {
	Key            []byte
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetMetaOptions encapsulates the parameters for a GetMetaEx operation.

type GetMetaResult

type GetMetaResult struct {
	Value    []byte
	Flags    uint32
	Cas      Cas
	Expiry   uint32
	SeqNo    SeqNo
	Datatype uint8
	Deleted  uint32

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetMetaResult encapsulates the result of a GetMetaEx operation.

type GetOneReplicaOptions

type GetOneReplicaOptions struct {
	Key            []byte
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	ReplicaIdx     int
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetOneReplicaOptions encapsulates the parameters for a GetOneReplicaEx operation.

type GetOptions

type GetOptions struct {
	Key            []byte
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetOptions encapsulates the parameters for a GetEx operation.

type GetRandomCallback

type GetRandomCallback func(*GetRandomResult, error)

GetRandomCallback is invoked upon completion of a GetRandom operation.

type GetRandomOptions

type GetRandomOptions struct {
	RetryStrategy RetryStrategy
	Deadline      time.Time

	CollectionName string
	ScopeName      string
	CollectionID   uint32

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

GetRandomOptions encapsulates the parameters for a GetRandomEx operation.

type GetRandomResult

type GetRandomResult struct {
	Key      []byte
	Value    []byte
	Flags    uint32
	Datatype uint8
	Cas      Cas

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetRandomResult encapsulates the result of a GetRandomEx operation.

type GetReplicaCallback

type GetReplicaCallback func(*GetReplicaResult, error)

GetReplicaCallback is invoked upon completion of a GetReplica operation.

type GetReplicaResult

type GetReplicaResult struct {
	Value    []byte
	Flags    uint32
	Datatype uint8
	Cas      Cas

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetReplicaResult encapsulates the result of a GetReplica operation.

type GetResult

type GetResult struct {
	Value    []byte
	Flags    uint32
	Datatype uint8
	Cas      Cas

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

GetResult encapsulates the result of a GetEx operation.

type GetVBucketSeqnosCallback

type GetVBucketSeqnosCallback func([]VbSeqNoEntry, error)

GetVBucketSeqnosCallback is invoked with the results of `GetVBucketSeqnos` operations.

type GetVbucketSeqnoFilterOptions

type GetVbucketSeqnoFilterOptions struct {
	CollectionID uint32
}

GetVbucketSeqnoFilterOptions are the filter options available to the GetVbucketSeqno operation.

type GetVbucketSeqnoOptions

type GetVbucketSeqnoOptions struct {
	FilterOptions *GetVbucketSeqnoFilterOptions
}

GetVbucketSeqnoOptions are the options available to the GetVbucketSeqno operation.

type HTTPConfig

type HTTPConfig struct {
	// MaxIdleConns controls the maximum number of idle (keep-alive) connections across all hosts.
	MaxIdleConns int
	// MaxIdleConnsPerHost controls the maximum idle (keep-alive) connections to keep per-host.
	MaxIdleConnsPerHost int
	ConnectTimeout      time.Duration
	// IdleConnTimeout is the maximum amount of time an idle (keep-alive) connection will remain idle before closing
	// itself.
	IdleConnectionTimeout time.Duration
}

HTTPConfig specifies http related configuration options.

type HTTPError

type HTTPError struct {
	InnerError    error
	UniqueID      string
	Endpoint      string
	RetryReasons  []RetryReason
	RetryAttempts uint32
}

HTTPError represents an error returned from an HTTP request.

func (HTTPError) Error

func (e HTTPError) Error() string

Error returns the string representation of this error.

func (HTTPError) MarshalJSON

func (e HTTPError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (HTTPError) Unwrap

func (e HTTPError) Unwrap() error

Unwrap returns the underlying reason for the error

type HTTPRequest

type HTTPRequest struct {
	Service       ServiceType
	Method        string
	Endpoint      string
	Path          string
	Username      string
	Password      string
	Body          []byte
	Headers       map[string]string
	ContentType   string
	IsIdempotent  bool
	UniqueID      string
	Deadline      time.Time
	RetryStrategy RetryStrategy

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

HTTPRequest contains the description of an HTTP request to perform.

type HTTPResponse

type HTTPResponse struct {
	Endpoint      string
	StatusCode    int
	ContentLength int64
	Body          io.ReadCloser
}

HTTPResponse encapsulates the response from an HTTP request.

type InMemoryTransactionLogger added in v10.1.4

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

InMemoryTransactionLogger logs to memory, also logging WARN and ERROR logs to the SDK logger. Uncommitted: This API may change in the future.

func NewInMemoryTransactionLogger added in v10.1.4

func NewInMemoryTransactionLogger() *InMemoryTransactionLogger

NewInMemoryTransactionLogger returns a new in memory transaction logger. Uncommitted: This API may change in the future.

func (*InMemoryTransactionLogger) Log added in v10.1.4

func (tl *InMemoryTransactionLogger) Log(level LogLevel, offset int, txnID, attemptID, fmt string, args ...interface{}) error

Log logs a new log entry to memory and logs to the SDK logs when the level is WARN or ERROR.

func (*InMemoryTransactionLogger) Logs added in v10.1.4

Logs returns the set of log items created during the transaction.

type InternalConfig added in v10.1.5

type InternalConfig struct {
	EnableResourceUnitsTrackingHello bool
}

InternalConfig specifies internal configs. Internal: This should never be used and is not supported.

type IoConfig

type IoConfig struct {
	// NetworkType defines which network to use from the cluster config.
	NetworkType string

	UseMutationTokens           bool
	UseDurations                bool
	UseOutOfOrderResponses      bool
	DisableXErrorHello          bool
	DisableJSONHello            bool
	DisableSyncReplicationHello bool
	EnablePITRHello             bool
	UseCollections              bool

	UseClusterMapNotifications bool
}

IoConfig specifies IO related configuration options such as HELLO flags and the network type to use.

type KVConfig

type KVConfig struct {
	// ConnectTimeout is the timeout value to apply when dialling tcp connections.
	ConnectTimeout time.Duration
	// ServerWaitBackoff is the period of time that the SDK will wait before reattempting connection to a node after
	// bootstrap fails against that node.
	ServerWaitBackoff time.Duration

	// The number of connections to create to each node.
	PoolSize int
	// The maximum number of requests that can be queued waiting to be sent to a node.
	MaxQueueSize int

	// Note: if you create multiple agents with different buffer sizes within the same environment then you will
	// get indeterminate behaviour, the connections may not even use the provided buffer size.
	ConnectionBufferSize uint
}

KVConfig specifies kv related configuration options.

type KeyValueError

type KeyValueError struct {
	InnerError         error
	StatusCode         memd.StatusCode
	DocumentKey        string
	BucketName         string
	ScopeName          string
	CollectionName     string
	CollectionID       uint32
	ErrorName          string
	ErrorDescription   string
	Opaque             uint32
	Context            string
	Ref                string
	RetryReasons       []RetryReason
	RetryAttempts      uint32
	LastDispatchedTo   string
	LastDispatchedFrom string
	LastConnectionID   string

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

KeyValueError wraps key-value errors that occur within the SDK.

func (KeyValueError) Error

func (e KeyValueError) Error() string

Error returns the string representation of this error.

func (KeyValueError) MarshalJSON

func (e KeyValueError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (KeyValueError) Unwrap

func (e KeyValueError) Unwrap() error

Unwrap returns the underlying reason for the error

type LogLevel

type LogLevel int

LogLevel specifies the severity of a log message.

const (
	LogError LogLevel = iota
	LogWarn
	LogInfo
	LogDebug
	LogTrace
	LogSched
	LogMaxVerbosity
)

Various logging levels (or subsystems) which can categorize the message. Currently these are ordered in decreasing severity.

type LogRedactLevel

type LogRedactLevel int

LogRedactLevel specifies the degree with which to redact the logs.

const (
	// RedactNone indicates to perform no redactions
	RedactNone LogRedactLevel = iota

	// RedactPartial indicates to redact all possible user-identifying information from logs.
	RedactPartial

	// RedactFull indicates to fully redact all possible identifying information from logs.
	RedactFull
)

type Logger

type Logger interface {
	// Outputs logging information:
	// level is the verbosity level
	// offset is the position within the calling stack from which the message
	// originated. This is useful for contextual loggers which retrieve file/line
	// information.
	Log(level LogLevel, offset int, format string, v ...interface{}) error
}

Logger defines a logging interface. You can either use one of the default loggers (DefaultStdioLogger(), VerboseStdioLogger()) or implement your own.

func DefaultStdioLogger

func DefaultStdioLogger() Logger

DefaultStdioLogger gets the default standard I/O logger.

gocbcore.SetLogger(gocbcore.DefaultStdioLogger())

func VerboseStdioLogger

func VerboseStdioLogger() Logger

VerboseStdioLogger is a more verbose level of DefaultStdioLogger(). Messages pertaining to the scheduling of ordinary commands (and their responses) will also be emitted.

gocbcore.SetLogger(gocbcore.VerboseStdioLogger())

type LookupInCallback

type LookupInCallback func(*LookupInResult, error)

LookupInCallback is invoked upon completion of a LookupIn operation.

type LookupInOptions

type LookupInOptions struct {
	Key            []byte
	Flags          memd.SubdocDocFlag
	Ops            []SubDocOp
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time
	ReplicaIdx     int

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

LookupInOptions encapsulates the parameters for a LookupInEx operation.

type LookupInResult

type LookupInResult struct {
	Cas Cas
	Ops []SubDocResult

	// Internal: This should never be used and is not supported.
	Internal struct {
		IsDeleted     bool
		ResourceUnits *ResourceUnitResult
	}
}

LookupInResult encapsulates the result of a LookupInEx operation.

type LostTransactionCleaner added in v10.1.0

type LostTransactionCleaner interface {
	ProcessClient(agent *Agent, oboUser string, collection, scope, uuid string, cb func(*TransactionClientRecordDetails, error))
	ProcessATR(agent *Agent, oboUser string, collection, scope, atrID string, cb func([]TransactionsCleanupAttempt, TransactionProcessATRStats, error))
	RemoveClientFromAllLocations(uuid string) error
	Close()
	GetAndResetResourceUnits() *TransactionResourceUnitResult
}

LostTransactionCleaner is responsible for cleaning up lost transactions. Internal: This should never be used and is not supported.

func NewLostTransactionCleaner added in v10.1.0

func NewLostTransactionCleaner(config *TransactionsConfig) LostTransactionCleaner

NewLostTransactionCleaner returns new lost transaction cleaner. Internal: This should never be used and is not supported.

type Manifest

type Manifest struct {
	UID    uint64
	Scopes []ManifestScope
}

Manifest is the representation of a collections manifest.

func (*Manifest) UnmarshalJSON

func (item *Manifest) UnmarshalJSON(data []byte) error

UnmarshalJSON is a custom implementation of json unmarshaling.

type ManifestCollection

type ManifestCollection struct {
	UID     uint32
	Name    string
	MaxTTL  int32
	History *bool
}

ManifestCollection is the representation of a collection within a manifest.

func (*ManifestCollection) UnmarshalJSON

func (item *ManifestCollection) UnmarshalJSON(data []byte) error

UnmarshalJSON is a custom implementation of json unmarshaling.

type ManifestScope

type ManifestScope struct {
	UID         uint32
	Name        string
	Collections []ManifestCollection
}

ManifestScope is the representation of a scope within a manifest.

func (*ManifestScope) UnmarshalJSON

func (item *ManifestScope) UnmarshalJSON(data []byte) error

UnmarshalJSON is a custom implementation of json unmarshaling.

type MemdConnInfo

type MemdConnInfo struct {
	LocalAddr    string
	RemoteAddr   string
	LastActivity time.Time
	Scope        string
	ID           string
	State        EndpointState
}

MemdConnInfo represents information we know about a particular memcached connection reported in a diagnostics report.

type Meter

type Meter interface {
	Counter(name string, tags map[string]string) (Counter, error)
	ValueRecorder(name string, tags map[string]string) (ValueRecorder, error)
}

Meter handles metrics information for SDK operations.

type MeterConfig

type MeterConfig struct {
	Meter Meter
}

MeterConfig specifies meter related configuration options.

type MutateInCallback

type MutateInCallback func(*MutateInResult, error)

MutateInCallback is invoked upon completion of a MutateIn operation.

type MutateInOptions

type MutateInOptions struct {
	Key                    []byte
	Flags                  memd.SubdocDocFlag
	Cas                    Cas
	Expiry                 uint32
	Ops                    []SubDocOp
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time
	PreserveExpiry         bool

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

MutateInOptions encapsulates the parameters for a MutateInEx operation.

type MutateInResult

type MutateInResult struct {
	Cas           Cas
	MutationToken MutationToken
	Ops           []SubDocResult

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

MutateInResult encapsulates the result of a MutateInEx operation.

type MutationToken

type MutationToken struct {
	VbID   uint16
	VbUUID VbUUID
	SeqNo  SeqNo
}

MutationToken represents a particular mutation within the cluster.

type N1QLError

type N1QLError struct {
	InnerError      error
	Statement       string
	ClientContextID string
	Errors          []N1QLErrorDesc
	Endpoint        string
	RetryReasons    []RetryReason
	RetryAttempts   uint32
	// Uncommitted: This API may change in the future.
	ErrorText string
	// Uncommitted: This API may change in the future.
	HTTPResponseCode int
}

N1QLError represents an error returned from a n1ql query.

func (N1QLError) Error

func (e N1QLError) Error() string

Error returns the string representation of this error.

func (N1QLError) MarshalJSON

func (e N1QLError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (N1QLError) Unwrap

func (e N1QLError) Unwrap() error

Unwrap returns the underlying reason for the error

type N1QLErrorDesc

type N1QLErrorDesc struct {
	Code    uint32
	Message string
	Retry   bool
	Reason  map[string]interface{}
}

N1QLErrorDesc represents specific n1ql error data.

func (N1QLErrorDesc) MarshalJSON added in v10.1.1

func (e N1QLErrorDesc) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

type N1QLQueryCallback

type N1QLQueryCallback func(*N1QLRowReader, error)

N1QLQueryCallback is invoked upon completion of a N1QLQuery operation.

type N1QLQueryOptions

type N1QLQueryOptions struct {
	Payload       []byte
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string
	// Internal: This should never be used and is not supported.
	Endpoint string

	TraceContext RequestSpanContext
}

N1QLQueryOptions represents the various options available for a n1ql query.

type N1QLRowReader

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

N1QLRowReader providers access to the rows of a n1ql query

func (*N1QLRowReader) Close

func (q *N1QLRowReader) Close() error

Close immediately shuts down the connection

func (*N1QLRowReader) Endpoint added in v10.0.6

func (q *N1QLRowReader) Endpoint() string

Endpoint returns the address that this query was run against. Internal: This should never be used and is not supported.

func (N1QLRowReader) Err

func (q N1QLRowReader) Err() error

Err returns any errors that occurred during streaming.

func (*N1QLRowReader) MetaData

func (q *N1QLRowReader) MetaData() ([]byte, error)

MetaData fetches the non-row bytes streamed in the response.

func (*N1QLRowReader) NextRow

func (q *N1QLRowReader) NextRow() []byte

NextRow reads the next rows bytes from the stream

func (N1QLRowReader) PreparedName

func (q N1QLRowReader) PreparedName() (string, error)

PreparedName returns the name of the prepared statement created when using enhanced prepared statements. If the prepared name has not been seen on the stream then this will return an error. Volatile: This API is subject to change.

type NoRetryRetryAction

type NoRetryRetryAction struct {
}

NoRetryRetryAction represents an action that indicates to not retry.

func (*NoRetryRetryAction) Duration

func (ra *NoRetryRetryAction) Duration() time.Duration

Duration is the length of time to wait before retrying an operation.

type NoopTransactionLogger added in v10.1.4

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

NoopTransactionLogger logs to the SDK logs when the level is WARN or ERROR. Uncommitted: This API may change in the future.

func NewNoopTransactionLogger added in v10.1.4

func NewNoopTransactionLogger() *NoopTransactionLogger

NewNoopTransactionLogger returns a new noop transaction logger. Uncommitted: This API may change in the future.

func (*NoopTransactionLogger) Log added in v10.1.4

func (n *NoopTransactionLogger) Log(level LogLevel, offset int, txnID, attemptID, fmt string, args ...interface{}) error

Log logs to the SDK logs when the level is WARN or ERROR.

func (*NoopTransactionLogger) Logs added in v10.1.4

Logs returns an empty slice.

type ObserveCallback

type ObserveCallback func(*ObserveResult, error)

ObserveCallback is invoked upon completion of a Observe operation.

type ObserveOptions

type ObserveOptions struct {
	Key            []byte
	ReplicaIdx     int
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

ObserveOptions encapsulates the parameters for a ObserveEx operation.

type ObserveResult

type ObserveResult struct {
	KeyState memd.KeyState
	Cas      Cas

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

ObserveResult encapsulates the result of a ObserveEx operation.

type ObserveVbCallback

type ObserveVbCallback func(*ObserveVbResult, error)

ObserveVbCallback is invoked upon completion of a ObserveVb operation.

type ObserveVbOptions

type ObserveVbOptions struct {
	VbID          uint16
	VbUUID        VbUUID
	ReplicaIdx    int
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

ObserveVbOptions encapsulates the parameters for a ObserveVbEx operation.

type ObserveVbResult

type ObserveVbResult struct {
	DidFailover  bool
	VbID         uint16
	VbUUID       VbUUID
	PersistSeqNo SeqNo
	CurrentSeqNo SeqNo
	OldVbUUID    VbUUID
	LastSeqNo    SeqNo

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

ObserveVbResult encapsulates the result of a ObserveVbEx operation.

type OpenStreamCallback

type OpenStreamCallback func([]FailoverEntry, error)

OpenStreamCallback is invoked with the results of `OpenStream` operations.

type OpenStreamFilterOptions

type OpenStreamFilterOptions struct {
	ScopeID       uint32
	CollectionIDs []uint32
}

OpenStreamFilterOptions are the filtering options available to the OpenStream operation.

type OpenStreamManifestOptions

type OpenStreamManifestOptions struct {
	ManifestUID uint64
}

OpenStreamManifestOptions are the manifest options available to the OpenStream operation.

type OpenStreamOptions

type OpenStreamOptions struct {
	FilterOptions   *OpenStreamFilterOptions
	StreamOptions   *OpenStreamStreamOptions
	ManifestOptions *OpenStreamManifestOptions
}

OpenStreamOptions are the options available to the OpenStream operation.

type OpenStreamStreamOptions

type OpenStreamStreamOptions struct {
	StreamID uint16
}

OpenStreamStreamOptions are the stream options available to the OpenStream operation.

type OrphanReporterConfig

type OrphanReporterConfig struct {
	Enabled bool
	// ReportInterval is the time period used for how often a report is logged.
	ReportInterval time.Duration
	// SampleSize is the number of requests which will be reported.
	SampleSize int
}

OrphanReporterConfig specifies options for controlling the orphan reporter which records when the SDK receives responses for requests that are no longer in the system (usually due to being timed out).

type PasswordAuthProvider

type PasswordAuthProvider struct {
	Username string
	Password string
}

PasswordAuthProvider provides a standard AuthProvider implementation for use with a standard username/password pair (for example, RBAC).

func (PasswordAuthProvider) Certificate

func (auth PasswordAuthProvider) Certificate(req AuthCertRequest) (*tls.Certificate, error)

Certificate directly returns a certificate chain to present for the connection.

func (PasswordAuthProvider) Credentials

func (auth PasswordAuthProvider) Credentials(req AuthCredsRequest) ([]UserPassPair, error)

Credentials directly returns the username/password from the provider.

func (PasswordAuthProvider) SupportsNonTLS

func (auth PasswordAuthProvider) SupportsNonTLS() bool

SupportsNonTLS specifies whether this authenticator supports non-TLS connections.

func (PasswordAuthProvider) SupportsTLS

func (auth PasswordAuthProvider) SupportsTLS() bool

SupportsTLS specifies whether this authenticator supports TLS connections.

type PendingOp

type PendingOp interface {
	Cancel()
}

PendingOp represents an outstanding operation within the client. This can be used to cancel an operation before it completes. This can also be used to Get information about the operation once it has completed (cancelled or successful).

type PingCallback

type PingCallback func(*PingResult, error)

PingCallback is invoked upon completion of a PingKv operation.

type PingOptions

type PingOptions struct {
	TraceContext RequestSpanContext
	KVDeadline   time.Time
	CbasDeadline time.Time
	N1QLDeadline time.Time
	FtsDeadline  time.Time
	CapiDeadline time.Time
	MgmtDeadline time.Time
	ServiceTypes []ServiceType

	// Internal: This should never be used and is not supported.
	User string
	// contains filtered or unexported fields
}

PingOptions encapsulates the parameters for a PingKv operation.

type PingResult

type PingResult struct {
	ConfigRev int64
	Services  map[ServiceType][]EndpointPingResult
}

PingResult encapsulates the result of a PingKv operation.

type PingState

type PingState uint32

PingState is the current state of a endpoint used in a PingResult.

const (
	// PingStateOK indicates that an endpoint is OK.
	PingStateOK PingState = 1

	// PingStateTimeout indicates that the ping request to an endpoint timed out.
	PingStateTimeout PingState = 2

	// PingStateError indicates that the ping request to an endpoint encountered an error.
	PingStateError PingState = 3
)

type RangeScanCancelCallback added in v10.2.1

type RangeScanCancelCallback func(*RangeScanCancelResult, error)

RangeScanCancelCallback is invoked upon completion of a RangeScanCancel operation.

type RangeScanCancelOptions added in v10.2.1

type RangeScanCancelOptions struct {
	Deadline time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

RangeScanCancelOptions encapsulates the parameters for a RangeScanCancel operation.

type RangeScanCancelResult added in v10.2.1

type RangeScanCancelResult struct{}

RangeScanCancelResult encapsulates the result of a RangeScanCancel operation.

type RangeScanContinueActionCallback added in v10.2.1

type RangeScanContinueActionCallback func(*RangeScanContinueResult, error)

RangeScanContinueActionCallback is invoked upon receipt of a RangeScanContinue response representing an action.

type RangeScanContinueDataCallback added in v10.2.1

type RangeScanContinueDataCallback func([]RangeScanItem)

RangeScanContinueDataCallback is invoked upon receipt of a RangeScanContinue response containing data.

type RangeScanContinueOptions added in v10.2.1

type RangeScanContinueOptions struct {
	// Deadline will also be sent as a part of the payload if not zero.
	Deadline time.Time

	MaxCount uint32
	MaxBytes uint32

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

RangeScanContinueOptions encapsulates the parameters for a RangeScanContinue operation.

type RangeScanContinueResult added in v10.2.1

type RangeScanContinueResult struct {
	More     bool
	Complete bool
}

RangeScanContinueResult encapsulates the result of a RangeScanContinue operation.

type RangeScanCreateCallback added in v10.2.1

type RangeScanCreateCallback func(RangeScanCreateResult, error)

RangeScanCreateCallback is invoked upon completion of a RangeScanCreate operation.

type RangeScanCreateOptions added in v10.2.1

type RangeScanCreateOptions struct {
	// Deadline will also be sent as a part of the payload if Snapshot is not nil.
	Deadline time.Time

	CollectionName string
	ScopeName      string

	CollectionID uint32
	// Note: if set then KeysOnly on RangeScanContinueOptions *must* also be set.
	KeysOnly bool
	Range    *RangeScanCreateRangeScanConfig
	Sampling *RangeScanCreateRandomSamplingConfig
	Snapshot *RangeScanCreateSnapshotRequirements

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

RangeScanCreateOptions encapsulates the parameters for a RangeScanCreate operation.

type RangeScanCreateRandomSamplingConfig added in v10.2.1

type RangeScanCreateRandomSamplingConfig struct {
	Seed    uint64
	Samples uint64
}

RangeScanCreateRandomSamplingConfig is the configuration available for performing a random sampling.

type RangeScanCreateRangeScanConfig added in v10.2.1

type RangeScanCreateRangeScanConfig struct {
	Start          []byte
	End            []byte
	ExclusiveStart []byte
	ExclusiveEnd   []byte
}

RangeScanCreateRangeScanConfig is the configuration available for performing a range scan.

type RangeScanCreateResult added in v10.2.1

type RangeScanCreateResult interface {
	ScanUUID() []byte
	KeysOnly() bool

	RangeScanContinue(opts RangeScanContinueOptions, dataCb RangeScanContinueDataCallback,
		actionCb RangeScanContinueActionCallback) (PendingOp, error)
	RangeScanCancel(opts RangeScanCancelOptions, cb RangeScanCancelCallback) (PendingOp, error)
}

RangeScanCreateResult encapsulates the result of a RangeScanCreate operation.

type RangeScanCreateSnapshotRequirements added in v10.2.1

type RangeScanCreateSnapshotRequirements struct {
	VbUUID      VbUUID
	SeqNo       SeqNo
	SeqNoExists bool
}

RangeScanCreateSnapshotRequirements is the set of requirements that the vbucket snapshot must meet in-order for the request to be successful.

type RangeScanItem added in v10.2.1

type RangeScanItem struct {
	Value    []byte
	Key      []byte
	Flags    uint32
	Cas      Cas
	Expiry   uint32
	SeqNo    SeqNo
	Datatype uint8
}

RangeScanItem encapsulates an iterm returned during a range scan.

type ReconfigureSecurityOptions added in v10.0.5

type ReconfigureSecurityOptions struct {
	UseTLS bool
	// If is nil will default to the TLSRootCAProvider already in use by the agent.
	TLSRootCAProvider func() *x509.CertPool

	Auth AuthProvider

	// AuthMechanisms is the list of mechanisms that the SDK can use to attempt authentication.
	// Note that if you add PLAIN to the list, this will cause credential leakage on the network
	// since PLAIN sends the credentials in cleartext. It is disabled by default to prevent downgrade attacks. We
	// recommend using a TLS connection if using PLAIN.
	// If is nil will default to the AuthMechanisms already in use by the Agent.
	AuthMechanisms []AuthMechanism
}

ReconfigureSecurityOptions are the options available to the ReconfigureSecurity function.

type ReplaceOptions

type ReplaceOptions struct {
	Key                    []byte
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	Value                  []byte
	Flags                  uint32
	Datatype               uint8
	Cas                    Cas
	Expiry                 uint32
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time
	PreserveExpiry         bool

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

ReplaceOptions encapsulates the parameters for a ReplaceEx operation.

type RequestSpan

type RequestSpan interface {
	End()
	Context() RequestSpanContext
	AddEvent(name string, timestamp time.Time)
	SetAttribute(key string, value interface{})
}

RequestSpan is the interface for spans that are created by a RequestTracer.

type RequestSpanContext

type RequestSpanContext interface {
}

RequestSpanContext is the interface for for external span contexts that can be passed in into the SDK option blocks.

type RequestTracer

type RequestTracer interface {
	RequestSpan(parentContext RequestSpanContext, operationName string) RequestSpan
}

RequestTracer describes the tracing abstraction in the SDK.

type ResourceUnitResult added in v10.1.5

type ResourceUnitResult struct {
	ReadUnits  uint16
	WriteUnits uint16
}

ResourceUnitResult describes the number of compute units used by an operation. Internal: This should never be used and is not supported.

type ResumeTransactionOptions added in v10.1.0

type ResumeTransactionOptions struct {
	// BucketAgentProvider provides a function which returns an agent for
	// a particular bucket by name.
	BucketAgentProvider TransactionsBucketAgentProviderFn

	// TransactionLogger is the logger to use with this transaction.
	TransactionLogger TransactionLogger

	// Internal specifies a set of options for internal use.
	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnitCallback func(result *ResourceUnitResult)
	}
}

ResumeTransactionOptions specifies options which can be overridden for the resumed transaction.

type RetryAction

type RetryAction interface {
	Duration() time.Duration
}

RetryAction is used by a RetryStrategy to calculate the duration to wait before retrying an operation. Returning a value of 0 indicates to not retry.

type RetryReason

type RetryReason interface {
	AllowsNonIdempotentRetry() bool
	AlwaysRetry() bool
	Description() string
}

RetryReason represents the reason for an operation possibly being retried.

type RetryRequest

type RetryRequest interface {
	RetryAttempts() uint32
	Identifier() string
	Idempotent() bool
	RetryReasons() []RetryReason
	// contains filtered or unexported methods
}

RetryRequest is a request that can possibly be retried.

type RetryStrategy

type RetryStrategy interface {
	RetryAfter(req RetryRequest, reason RetryReason) RetryAction
}

RetryStrategy is to determine if an operation should be retried, and if so how long to wait before retrying.

type SRVRecord added in v10.2.0

type SRVRecord struct {
	Proto  string
	Scheme string
	Host   string
}

SRVRecord describes the SRV record used to extract memd addresses in the SeedConfig.

type SaslListMechsCompleted

type SaslListMechsCompleted struct {
	Err   error
	Mechs []AuthMechanism
}

SaslListMechsCompleted is used to contain the result and/or error from a SaslListMechs operation.

type SearchCapability added in v10.4.0

type SearchCapability uint32
const (
	SearchCapabilityScopedIndexes SearchCapability = iota
	SearchCapabilityVectorSearch
)

type SearchError

type SearchError struct {
	InnerError       error
	IndexName        string
	Query            interface{}
	ErrorText        string
	HTTPResponseCode int
	Endpoint         string
	RetryReasons     []RetryReason
	RetryAttempts    uint32
}

SearchError represents an error returned from a search query.

func (SearchError) Error

func (e SearchError) Error() string

Error returns the string representation of this error.

func (SearchError) MarshalJSON

func (e SearchError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (SearchError) Unwrap

func (e SearchError) Unwrap() error

Unwrap returns the underlying reason for the error

type SearchQueryCallback

type SearchQueryCallback func(*SearchRowReader, error)

SearchQueryCallback is invoked upon completion of a SearchQuery operation.

type SearchQueryOptions

type SearchQueryOptions struct {
	BucketName    string
	ScopeName     string
	IndexName     string
	Payload       []byte
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

SearchQueryOptions represents the various options available for a search query.

type SearchRowReader

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

SearchRowReader providers access to the rows of a view query

func (*SearchRowReader) Close

func (q *SearchRowReader) Close() error

Close immediately shuts down the connection

func (SearchRowReader) Err

func (q SearchRowReader) Err() error

Err returns any errors that occurred during streaming.

func (*SearchRowReader) MetaData

func (q *SearchRowReader) MetaData() ([]byte, error)

MetaData fetches the non-row bytes streamed in the response.

func (*SearchRowReader) NextRow

func (q *SearchRowReader) NextRow() []byte

NextRow reads the next rows bytes from the stream

type SecurityConfig

type SecurityConfig struct {
	UseTLS            bool
	TLSRootCAProvider func() *x509.CertPool

	// NoTLSSeedNode indicates that, even with UseTLS set to true, the SDK should always connect to the seed node
	// over a non TLS connection. This means that the seed node should ALWAYS be localhost.
	// This option must be used with the ConfigPollerConfig UseSeedPoller set to true.
	// Internal: This should never be used and is not supported.
	NoTLSSeedNode bool

	Auth AuthProvider

	// AuthMechanisms is the list of mechanisms that the SDK can use to attempt authentication.
	// Note that if you add PLAIN to the list, this will cause credential leakage on the network
	// since PLAIN sends the credentials in cleartext. It is disabled by default to prevent downgrade attacks. We
	// recommend using a TLS connection if using PLAIN.
	AuthMechanisms []AuthMechanism
}

SecurityConfig specifies options for controlling security related items such as TLS root certificates and verification skipping.

type SeedConfig

type SeedConfig struct {
	HTTPAddrs []string
	MemdAddrs []string
	SRVRecord *SRVRecord
}

SeedConfig specifies initial seed configuration options such as addresses.

type SeqNo

type SeqNo uint64

SeqNo is a sequential mutation number indicating the order and precise position of a write that has occurred.

type ServiceType

type ServiceType int

ServiceType specifies a particular Couchbase service type.

type SetMetaCallback

type SetMetaCallback func(*SetMetaResult, error)

SetMetaCallback is invoked upon completion of a SetMeta operation.

type SetMetaOptions

type SetMetaOptions struct {
	Key            []byte
	Value          []byte
	Extra          []byte
	Datatype       uint8
	Options        uint32
	Flags          uint32
	Expiry         uint32
	Cas            Cas
	RevNo          uint64
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

SetMetaOptions encapsulates the parameters for a SetMetaEx operation.

type SetMetaResult

type SetMetaResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

SetMetaResult encapsulates the result of a SetMetaEx operation.

type SetOptions

type SetOptions struct {
	Key                    []byte
	CollectionName         string
	ScopeName              string
	RetryStrategy          RetryStrategy
	Value                  []byte
	Flags                  uint32
	Datatype               uint8
	Expiry                 uint32
	DurabilityLevel        memd.DurabilityLevel
	DurabilityLevelTimeout time.Duration
	CollectionID           uint32
	Deadline               time.Time
	PreserveExpiry         bool

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

SetOptions encapsulates the parameters for a SetEx operation.

type SingleServerManifestResult

type SingleServerManifestResult struct {
	Manifest []byte
	Error    error
}

SingleServerManifestResult encapsulates the result from a single server when using the GetAllCollectionManifests operation.

type SingleServerStats

type SingleServerStats struct {
	Stats map[string]string
	// StatsKeys and StatsChunks provide access to the raw keys and values returned on a per packet basis.
	// This is useful for stats keys such as connections which, unlike most stats keys, return us a complex object
	// per packet. Keys and chunks maintain the same ordering for indexes.
	StatsKeys   [][]byte
	StatsChunks [][]byte
	Error       error
}

SingleServerStats represents the stats returned from a single server.

type SnapshotState

type SnapshotState uint32

SnapshotState represents the state of a particular cluster snapshot.

func (SnapshotState) HasHistory added in v10.3.1

func (s SnapshotState) HasHistory() bool

HasHistory returns whether this snapshot represents a view of history.

func (SnapshotState) HasInMemory

func (s SnapshotState) HasInMemory() bool

HasInMemory returns whether this snapshot is available in memory.

func (SnapshotState) HasMayDuplicateKeys added in v10.3.1

func (s SnapshotState) HasMayDuplicateKeys() bool

HasMayDuplicateKeys returns whether this snapshot may contain duplicate keys.

func (SnapshotState) HasOnDisk

func (s SnapshotState) HasOnDisk() bool

HasOnDisk returns whether this snapshot is available on disk.

type SpanStatus

type SpanStatus string
const (
	SpanStatusOK    SpanStatus = "Ok"
	SpanStatusError SpanStatus = "Error"
)

type StatsCallback

type StatsCallback func(*StatsResult, error)

StatsCallback is invoked upon completion of a Stats operation.

type StatsOptions

type StatsOptions struct {
	Key string
	// Target indicates that something specific should be targeted by the operation. If left nil
	// then the stats command will be sent to all servers.
	Target        StatsTarget
	RetryStrategy RetryStrategy
	Deadline      time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

StatsOptions encapsulates the parameters for a Stats operation.

type StatsResult

type StatsResult struct {
	Servers map[string]SingleServerStats
}

StatsResult encapsulates the result of a Stats operation.

type StatsTarget

type StatsTarget interface {
}

StatsTarget is used for providing a specific target to the Stats operation.

type StoreCallback

type StoreCallback func(*StoreResult, error)

StoreCallback is invoked upon completion of a Add, Set or Replace operation.

type StoreResult

type StoreResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

StoreResult encapsulates the result of a AddEx, SetEx or ReplaceEx operation.

type StreamObserver

type StreamObserver interface {
	SnapshotMarker(snapshotMarker DcpSnapshotMarker)
	Mutation(mutation DcpMutation)
	Deletion(deletion DcpDeletion)
	Expiration(expiration DcpExpiration)
	End(end DcpStreamEnd, err error)
	CreateCollection(creation DcpCollectionCreation)
	DeleteCollection(deletion DcpCollectionDeletion)
	FlushCollection(flush DcpCollectionFlush)
	CreateScope(creation DcpScopeCreation)
	DeleteScope(deletion DcpScopeDeletion)
	ModifyCollection(modification DcpCollectionModification)
	OSOSnapshot(snapshot DcpOSOSnapshot)
	SeqNoAdvanced(seqNoAdvanced DcpSeqNoAdvanced)
}

StreamObserver provides an interface to receive events from a running DCP stream.

type SubDocOp

type SubDocOp struct {
	Op    memd.SubDocOpType
	Flags memd.SubdocFlag
	Path  string
	Value []byte
}

SubDocOp defines a per-operation structure to be passed to MutateIn or LookupIn for performing many sub-document operations.

type SubDocResult

type SubDocResult struct {
	Err   error
	Value []byte
}

SubDocResult encapsulates the results from a single sub-document operation.

type SubDocumentError

type SubDocumentError struct {
	InnerError error
	Index      int
}

SubDocumentError provides additional contextual information to sub-document specific errors. InnerError is always a KeyValueError.

func (SubDocumentError) Error

func (err SubDocumentError) Error() string

Error returns the string representation of this error.

func (SubDocumentError) Unwrap

func (err SubDocumentError) Unwrap() error

Unwrap returns the underlying error for the operation failing.

type TimeoutError

type TimeoutError struct {
	InnerError         error
	OperationID        string
	Opaque             string
	TimeObserved       time.Duration
	RetryReasons       []RetryReason
	RetryAttempts      uint32
	LastDispatchedTo   string
	LastDispatchedFrom string
	LastConnectionID   string

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

TimeoutError wraps timeout errors that occur within the SDK.

func (TimeoutError) Error

func (err TimeoutError) Error() string

func (*TimeoutError) MarshalJSON

func (err *TimeoutError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (*TimeoutError) UnmarshalJSON

func (err *TimeoutError) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the Unmarshaler interface.

func (TimeoutError) Unwrap

func (err TimeoutError) Unwrap() error

Unwrap returns the underlying reason for the error

type TouchCallback

type TouchCallback func(*TouchResult, error)

TouchCallback is invoked upon completion of a Touch operation.

type TouchOptions

type TouchOptions struct {
	Key            []byte
	Expiry         uint32
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

TouchOptions encapsulates the parameters for a TouchEx operation.

type TouchResult

type TouchResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

TouchResult encapsulates the result of a TouchEx operation.

type TracerConfig

type TracerConfig struct {
	Tracer           RequestTracer
	NoRootTraceSpans bool
}

TracerConfig specifies tracer related configuration options.

type Transaction added in v10.1.0

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

Transaction represents a single active transaction, it can be used to stage mutations and finally commit them.

func (*Transaction) Attempt added in v10.1.0

func (t *Transaction) Attempt() TransactionAttempt

Attempt returns meta-data about the current attempt to complete the transaction.

func (*Transaction) CanCommit added in v10.1.0

func (t *Transaction) CanCommit() bool

CanCommit indicates whether this attempt can still be committed.

func (*Transaction) Commit added in v10.1.0

Commit will attempt to commit the transaction, rolling it back and cancelling it if it is not capable of doing so.

func (*Transaction) Config added in v10.1.0

func (t *Transaction) Config() TransactionOptions

Config returns the configured parameters for this transaction. Note that the Expiration time is adjusted based on the time left. Note also that after a transaction is resumed, the custom atr location may no longer reflect the originally configured value.

func (*Transaction) FinalErrorToRaise added in v10.1.3

func (t *Transaction) FinalErrorToRaise() TransactionErrorReason

FinalErrorToRaise returns the TransactionErrorReason corresponding to the final state of the transaction.

func (*Transaction) Get added in v10.1.0

Get will attempt to fetch a document, and fail the transaction if it does not exist.

func (*Transaction) GetATRLocation added in v10.1.0

func (t *Transaction) GetATRLocation() TransactionATRLocation

GetATRLocation returns the ATR location for the current attempt, either by identifying where it was placed, or where it will be based on custom atr configurations.

func (*Transaction) GetMutations added in v10.1.0

func (t *Transaction) GetMutations() []TransactionStagedMutation

GetMutations returns a list of all the current mutations that have been performed under this transaction.

func (*Transaction) HasExpired added in v10.1.0

func (t *Transaction) HasExpired() bool

HasExpired indicates whether this attempt has expired.

func (*Transaction) ID added in v10.1.0

func (t *Transaction) ID() string

ID returns the transaction ID of this transaction.

func (*Transaction) Insert added in v10.1.0

Insert will attempt to insert a document.

func (*Transaction) Logger added in v10.1.4

func (t *Transaction) Logger() TransactionLogger

Logger returns the logger used by this transaction. Uncommitted: This API may change in the future.

func (*Transaction) NewAttempt added in v10.1.0

func (t *Transaction) NewAttempt() error

NewAttempt begins a new attempt with this transaction.

func (*Transaction) Remove added in v10.1.0

Remove will attempt to remove a previously fetched document.

func (*Transaction) Replace added in v10.1.0

Replace will attempt to replace an existing document.

func (*Transaction) Rollback added in v10.1.0

Rollback will attempt to rollback the transaction.

func (*Transaction) SerializeAttempt added in v10.1.0

func (t *Transaction) SerializeAttempt(cb func([]byte, error)) error

SerializeAttempt will serialize the current transaction attempt, allowing it to be resumed later, potentially under a different transactions client. It is no longer safe to use this attempt once this has occurred, a new attempt must be started to use this object following this call.

func (*Transaction) SetATRLocation added in v10.1.0

func (t *Transaction) SetATRLocation(location TransactionATRLocation) error

SetATRLocation forces the ATR location for the current attempt to a specific location. Note that this cannot be called if it has already been set. This is currently only safe to call before any mutations have occurred.

func (*Transaction) ShouldRetry added in v10.1.0

func (t *Transaction) ShouldRetry() bool

ShouldRetry indicates if this attempt thinks we can retry.

func (*Transaction) ShouldRollback added in v10.1.0

func (t *Transaction) ShouldRollback() bool

ShouldRollback indicates if this attempt should be rolled back.

func (*Transaction) TimeRemaining added in v10.1.0

func (t *Transaction) TimeRemaining() time.Duration

func (*Transaction) UpdateState added in v10.1.0

func (t *Transaction) UpdateState(opts TransactionUpdateStateOptions)

UpdateState will update the internal state of the current attempt. Internal: This should never be used and is not supported.

type TransactionATRLocation added in v10.1.0

type TransactionATRLocation struct {
	Agent          *Agent
	OboUser        string
	ScopeName      string
	CollectionName string
}

TransactionATRLocation specifies a specific location where ATR entries should be placed when performing transactions.

func (TransactionATRLocation) String added in v10.1.5

func (tlal TransactionATRLocation) String() string

type TransactionAttempt added in v10.1.0

type TransactionAttempt struct {
	State             TransactionAttemptState
	ID                string
	AtrID             []byte
	AtrBucketName     string
	AtrScopeName      string
	AtrCollectionName string

	// UnstagingComplete indicates whether the transaction was succesfully
	// unstaged, or if a later cleanup job will be responsible.
	UnstagingComplete bool

	// Expired indicates whether this attempt expired during execution.
	Expired bool

	// PreExpiryAutoRollback indicates whether an auto-rollback occured
	// before the transaction was expired.
	PreExpiryAutoRollback bool
}

TransactionAttempt represents a singular attempt at executing a transaction. A transaction may require multiple attempts before being successful.

type TransactionAttemptState added in v10.1.0

type TransactionAttemptState int

TransactionAttemptState represents the current State of a transaction

func (TransactionAttemptState) String added in v10.1.4

func (state TransactionAttemptState) String() string

type TransactionCleanUpHooks added in v10.1.0

type TransactionCleanUpHooks interface {
	BeforeATRGet(id []byte, cb func(error))
	BeforeDocGet(id []byte, cb func(error))
	BeforeRemoveLinks(id []byte, cb func(error))
	BeforeCommitDoc(id []byte, cb func(error))
	BeforeRemoveDocStagedForRemoval(id []byte, cb func(error))
	BeforeRemoveDoc(id []byte, cb func(error))
	BeforeATRRemove(id []byte, cb func(error))
}

TransactionCleanUpHooks provides a number of internal hooks used for testing. Internal: This should never be used and is not supported.

type TransactionClientRecordDetails added in v10.1.0

type TransactionClientRecordDetails struct {
	NumActiveClients     int
	IndexOfThisClient    int
	ClientIsNew          bool
	ExpiredClientIDs     []string
	NumExistingClients   int
	NumExpiredClients    int
	OverrideEnabled      bool
	OverrideActive       bool
	OverrideExpiresCas   int64
	CasNowNanos          int64
	AtrsHandledByClient  []string
	CheckAtrEveryNMillis int
	ClientUUID           string
}

TransactionClientRecordDetails is the result of processing a client record. Internal: This should never be used and is not supported.

type TransactionClientRecordHooks added in v10.1.0

type TransactionClientRecordHooks interface {
	BeforeCreateRecord(cb func(error))
	BeforeRemoveClient(cb func(error))
	BeforeUpdateCAS(cb func(error))
	BeforeGetRecord(cb func(error))
	BeforeUpdateRecord(cb func(error))
}

TransactionClientRecordHooks provides a number of internal hooks used for testing. Internal: This should never be used and is not supported.

type TransactionCommitCallback added in v10.1.0

type TransactionCommitCallback func(error)

TransactionCommitCallback describes a callback for a completed commit operation.

type TransactionCreateGetResultOptions added in v10.1.0

type TransactionCreateGetResultOptions struct {
	Agent          *Agent
	OboUser        string
	ScopeName      string
	CollectionName string
	Key            []byte
	Cas            Cas
	Meta           *TransactionMutableItemMeta
}

TransactionCreateGetResultOptions exposes options for the Internal CreateGetResult method.

type TransactionDefaultCleanupHooks added in v10.1.0

type TransactionDefaultCleanupHooks struct {
}

TransactionDefaultCleanupHooks is default set of noop hooks used within the library. Internal: This should never be used and is not supported.

func (*TransactionDefaultCleanupHooks) BeforeATRGet added in v10.1.0

func (dh *TransactionDefaultCleanupHooks) BeforeATRGet(id []byte, cb func(error))

BeforeATRGet happens before an ATR get.

func (*TransactionDefaultCleanupHooks) BeforeATRRemove added in v10.1.0

func (dh *TransactionDefaultCleanupHooks) BeforeATRRemove(id []byte, cb func(error))

BeforeATRRemove happens before we remove an ATR.

func (*TransactionDefaultCleanupHooks) BeforeCommitDoc added in v10.1.0

func (dh *TransactionDefaultCleanupHooks) BeforeCommitDoc(id []byte, cb func(error))

BeforeCommitDoc happens before we commit a document.

func (*TransactionDefaultCleanupHooks) BeforeDocGet added in v10.1.0

func (dh *TransactionDefaultCleanupHooks) BeforeDocGet(id []byte, cb func(error))

BeforeDocGet happens before an doc get.

func (*TransactionDefaultCleanupHooks) BeforeRemoveDoc added in v10.1.0

func (dh *TransactionDefaultCleanupHooks) BeforeRemoveDoc(id []byte, cb func(error))

BeforeRemoveDoc happens before we remove a document.

func (*TransactionDefaultCleanupHooks) BeforeRemoveDocStagedForRemoval added in v10.1.0

func (dh *TransactionDefaultCleanupHooks) BeforeRemoveDocStagedForRemoval(id []byte, cb func(error))

BeforeRemoveDocStagedForRemoval happens before we remove a staged document.

func (dh *TransactionDefaultCleanupHooks) BeforeRemoveLinks(id []byte, cb func(error))

BeforeRemoveLinks happens before we remove links.

type TransactionDefaultClientRecordHooks added in v10.1.0

type TransactionDefaultClientRecordHooks struct {
}

TransactionDefaultClientRecordHooks is default set of noop hooks used within the library. Internal: This should never be used and is not supported.

func (*TransactionDefaultClientRecordHooks) BeforeCreateRecord added in v10.1.0

func (dh *TransactionDefaultClientRecordHooks) BeforeCreateRecord(cb func(error))

BeforeCreateRecord happens before we create a cleanup client record.

func (*TransactionDefaultClientRecordHooks) BeforeGetRecord added in v10.1.0

func (dh *TransactionDefaultClientRecordHooks) BeforeGetRecord(cb func(error))

BeforeGetRecord happens before we get a cleanup client record.

func (*TransactionDefaultClientRecordHooks) BeforeRemoveClient added in v10.1.0

func (dh *TransactionDefaultClientRecordHooks) BeforeRemoveClient(cb func(error))

BeforeRemoveClient happens before we remove a cleanup client record.

func (*TransactionDefaultClientRecordHooks) BeforeUpdateCAS added in v10.1.0

func (dh *TransactionDefaultClientRecordHooks) BeforeUpdateCAS(cb func(error))

BeforeUpdateCAS happens before we update a CAS.

func (*TransactionDefaultClientRecordHooks) BeforeUpdateRecord added in v10.1.0

func (dh *TransactionDefaultClientRecordHooks) BeforeUpdateRecord(cb func(error))

BeforeUpdateRecord happens before we update a cleanup client record.

type TransactionDefaultHooks added in v10.1.0

type TransactionDefaultHooks struct {
}

TransactionDefaultHooks is default set of noop hooks used within the library. Internal: This should never be used and is not supported.

func (*TransactionDefaultHooks) AfterATRAborted added in v10.1.0

func (dh *TransactionDefaultHooks) AfterATRAborted(cb func(err error))

AfterATRAborted occurs after the ATR transitions to aborted.

func (*TransactionDefaultHooks) AfterATRCommit added in v10.1.0

func (dh *TransactionDefaultHooks) AfterATRCommit(cb func(err error))

AfterATRCommit occurs after an ATR is committed.

func (*TransactionDefaultHooks) AfterATRComplete added in v10.1.0

func (dh *TransactionDefaultHooks) AfterATRComplete(cb func(err error))

AfterATRComplete occurs after the ATR transitions to complete.

func (*TransactionDefaultHooks) AfterATRPending added in v10.1.0

func (dh *TransactionDefaultHooks) AfterATRPending(cb func(err error))

AfterATRPending occurs after the ATR transitions to pending.

func (*TransactionDefaultHooks) AfterATRRolledBack added in v10.1.0

func (dh *TransactionDefaultHooks) AfterATRRolledBack(cb func(err error))

AfterATRRolledBack occurs after the ATR transitions to rolled back.

func (*TransactionDefaultHooks) AfterDocCommitted added in v10.1.0

func (dh *TransactionDefaultHooks) AfterDocCommitted(docID []byte, cb func(err error))

AfterDocCommitted occurs after a document is committed.

func (*TransactionDefaultHooks) AfterDocCommittedBeforeSavingCAS added in v10.1.0

func (dh *TransactionDefaultHooks) AfterDocCommittedBeforeSavingCAS(docID []byte, cb func(err error))

AfterDocCommittedBeforeSavingCAS occurs after committed a document before saving the CAS.

func (*TransactionDefaultHooks) AfterDocRemovedPostRetry added in v10.1.0

func (dh *TransactionDefaultHooks) AfterDocRemovedPostRetry(docID []byte, cb func(err error))

AfterDocRemovedPostRetry occurs after removing a document after retry.

func (*TransactionDefaultHooks) AfterDocRemovedPreRetry added in v10.1.0

func (dh *TransactionDefaultHooks) AfterDocRemovedPreRetry(docID []byte, cb func(err error))

AfterDocRemovedPreRetry occurs after removing a document before retry.

func (*TransactionDefaultHooks) AfterDocsCommitted added in v10.1.0

func (dh *TransactionDefaultHooks) AfterDocsCommitted(cb func(err error))

AfterDocsCommitted occurs after all documents are committed.

func (*TransactionDefaultHooks) AfterDocsRemoved added in v10.1.0

func (dh *TransactionDefaultHooks) AfterDocsRemoved(cb func(err error))

AfterDocsRemoved occurs after all documents are removed.

func (*TransactionDefaultHooks) AfterGetComplete added in v10.1.0

func (dh *TransactionDefaultHooks) AfterGetComplete(docID []byte, cb func(err error))

AfterGetComplete occurs after a get completes.

func (*TransactionDefaultHooks) AfterRemoveStagedInsert added in v10.1.0

func (dh *TransactionDefaultHooks) AfterRemoveStagedInsert(docID []byte, cb func(err error))

AfterRemoveStagedInsert occurs after removing a staged insert.

func (*TransactionDefaultHooks) AfterRollbackDeleteInserted added in v10.1.0

func (dh *TransactionDefaultHooks) AfterRollbackDeleteInserted(docID []byte, cb func(err error))

AfterRollbackDeleteInserted occurs after rolling back a delete.

func (*TransactionDefaultHooks) AfterRollbackReplaceOrRemove added in v10.1.0

func (dh *TransactionDefaultHooks) AfterRollbackReplaceOrRemove(docID []byte, cb func(err error))

AfterRollbackReplaceOrRemove occurs after rolling back a replace or remove.

func (*TransactionDefaultHooks) AfterStagedInsertComplete added in v10.1.0

func (dh *TransactionDefaultHooks) AfterStagedInsertComplete(docID []byte, cb func(err error))

AfterStagedInsertComplete occurs after staging an insert is completed.

func (*TransactionDefaultHooks) AfterStagedRemoveComplete added in v10.1.0

func (dh *TransactionDefaultHooks) AfterStagedRemoveComplete(docID []byte, cb func(err error))

AfterStagedRemoveComplete occurs after staging a remove is completed.

func (*TransactionDefaultHooks) AfterStagedReplaceComplete added in v10.1.0

func (dh *TransactionDefaultHooks) AfterStagedReplaceComplete(docID []byte, cb func(err error))

AfterStagedReplaceComplete occurs after staging a replace is completed.

func (*TransactionDefaultHooks) BeforeATRAborted added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeATRAborted(cb func(err error))

BeforeATRAborted occurs before the ATR transitions to aborted.

func (*TransactionDefaultHooks) BeforeATRCommit added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeATRCommit(cb func(err error))

BeforeATRCommit occurs before an ATR is committed.

func (*TransactionDefaultHooks) BeforeATRCommitAmbiguityResolution added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeATRCommitAmbiguityResolution(cb func(err error))

BeforeATRCommitAmbiguityResolution occurs before ATR commit ambiguity resolution.

func (*TransactionDefaultHooks) BeforeATRComplete added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeATRComplete(cb func(err error))

BeforeATRComplete occurs before the ATR transitions to complete.

func (*TransactionDefaultHooks) BeforeATRPending added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeATRPending(cb func(err error))

BeforeATRPending occurs before the ATR transitions to pending.

func (*TransactionDefaultHooks) BeforeATRRolledBack added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeATRRolledBack(cb func(err error))

BeforeATRRolledBack occurs before the ATR transitions to rolled back.

func (*TransactionDefaultHooks) BeforeCheckATREntryForBlockingDoc added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeCheckATREntryForBlockingDoc(docID []byte, cb func(err error))

BeforeCheckATREntryForBlockingDoc occurs before checking the ATR of a blocking document.

func (*TransactionDefaultHooks) BeforeDocCommitted added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeDocCommitted(docID []byte, cb func(err error))

BeforeDocCommitted occurs before a document is committed.

func (*TransactionDefaultHooks) BeforeDocGet added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeDocGet(docID []byte, cb func(err error))

BeforeDocGet occurs before a document is fetched.

func (*TransactionDefaultHooks) BeforeDocRemoved added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeDocRemoved(docID []byte, cb func(err error))

BeforeDocRemoved occurs before removing a document.

func (*TransactionDefaultHooks) BeforeDocRolledBack added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeDocRolledBack(docID []byte, cb func(err error))

BeforeDocRolledBack occurs before a document is rolled back.

func (*TransactionDefaultHooks) BeforeGetDocInExistsDuringStagedInsert added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeGetDocInExistsDuringStagedInsert(docID []byte, cb func(err error))

BeforeGetDocInExistsDuringStagedInsert occurs before getting a document for an insert.

func (*TransactionDefaultHooks) BeforeRemoveStagedInsert added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeRemoveStagedInsert(docID []byte, cb func(err error))

BeforeRemoveStagedInsert occurs before removing a staged insert.

func (*TransactionDefaultHooks) BeforeRemovingDocDuringStagedInsert added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeRemovingDocDuringStagedInsert(docID []byte, cb func(err error))

BeforeRemovingDocDuringStagedInsert occurs before removing a document during staged insert.

func (*TransactionDefaultHooks) BeforeRollbackDeleteInserted added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeRollbackDeleteInserted(docID []byte, cb func(err error))

BeforeRollbackDeleteInserted occurs before rolling back a delete.

func (*TransactionDefaultHooks) BeforeStagedInsert added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeStagedInsert(docID []byte, cb func(err error))

BeforeStagedInsert occurs before staging an insert.

func (*TransactionDefaultHooks) BeforeStagedRemove added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeStagedRemove(docID []byte, cb func(err error))

BeforeStagedRemove occurs before staging a remove.

func (*TransactionDefaultHooks) BeforeStagedReplace added in v10.1.0

func (dh *TransactionDefaultHooks) BeforeStagedReplace(docID []byte, cb func(err error))

BeforeStagedReplace occurs before staging a replace.

func (*TransactionDefaultHooks) HasExpiredClientSideHook added in v10.1.0

func (dh *TransactionDefaultHooks) HasExpiredClientSideHook(stage string, docID []byte, cb func(bool, error))

HasExpiredClientSideHook checks if a transaction has expired.

func (*TransactionDefaultHooks) RandomATRIDForVbucket added in v10.1.0

func (dh *TransactionDefaultHooks) RandomATRIDForVbucket(cb func(string, error))

RandomATRIDForVbucket generates a random ATRID for a vbucket.

type TransactionDurabilityLevel added in v10.1.0

type TransactionDurabilityLevel int

TransactionDurabilityLevel specifies the durability level to use for a mutation.

type TransactionErrorClass added in v10.1.0

type TransactionErrorClass uint8

TransactionErrorClass describes the reason that a transaction error occurred. Internal: This should never be used and is not supported.

const (
	// TransactionErrorClassFailOther indicates an error occurred because it did not fit into any other reason.
	TransactionErrorClassFailOther TransactionErrorClass = iota

	// TransactionErrorClassFailTransient indicates an error occurred because of a transient reason.
	TransactionErrorClassFailTransient

	// TransactionErrorClassFailDocNotFound indicates an error occurred because of a document not found.
	TransactionErrorClassFailDocNotFound

	// TransactionErrorClassFailDocAlreadyExists indicates an error occurred because a document already exists.
	TransactionErrorClassFailDocAlreadyExists

	// TransactionErrorClassFailPathNotFound indicates an error occurred because a path was not found.
	TransactionErrorClassFailPathNotFound

	// TransactionErrorClassFailPathAlreadyExists indicates an error occurred because a path already exists.
	TransactionErrorClassFailPathAlreadyExists

	// TransactionErrorClassFailWriteWriteConflict indicates an error occurred because of a write write conflict.
	TransactionErrorClassFailWriteWriteConflict

	// TransactionErrorClassFailCasMismatch indicates an error occurred because of a cas mismatch.
	TransactionErrorClassFailCasMismatch

	// TransactionErrorClassFailHard indicates an error occurred because of a hard error.
	TransactionErrorClassFailHard

	// TransactionErrorClassFailAmbiguous indicates an error occurred leaving the transaction in an ambiguous way.
	TransactionErrorClassFailAmbiguous

	// TransactionErrorClassFailExpiry indicates an error occurred because the transaction expired.
	TransactionErrorClassFailExpiry

	// TransactionErrorClassFailOutOfSpace indicates an error occurred because the ATR is full.
	TransactionErrorClassFailOutOfSpace
)

type TransactionErrorReason added in v10.1.0

type TransactionErrorReason uint8

TransactionErrorReason is the reason why a transaction should be failed. Internal: This should never be used and is not supported.

const (
	// TransactionErrorReasonSuccess indicates the transaction succeeded and did not fail.
	TransactionErrorReasonSuccess TransactionErrorReason = iota

	// TransactionErrorReasonTransactionFailed indicates the transaction should be failed because it failed.
	TransactionErrorReasonTransactionFailed

	// TransactionErrorReasonTransactionExpired indicates the transaction should be failed because it expired.
	TransactionErrorReasonTransactionExpired

	// TransactionErrorReasonTransactionCommitAmbiguous indicates the transaction should be failed and the commit was ambiguous.
	TransactionErrorReasonTransactionCommitAmbiguous

	// TransactionErrorReasonTransactionFailedPostCommit indicates the transaction should be failed because it failed post commit.
	TransactionErrorReasonTransactionFailedPostCommit
)

NOTE: The errors within this section are critically ordered, as the order of precedence used when merging errors together is based on this.

func (TransactionErrorReason) String added in v10.1.4

func (reason TransactionErrorReason) String() string

type TransactionForwardCompatibilityEntry added in v10.1.0

type TransactionForwardCompatibilityEntry struct {
	ProtocolVersion   string `json:"p,omitempty"`
	ProtocolExtension string `json:"e,omitempty"`
	Behaviour         string `json:"b,omitempty"`
	RetryInterval     int    `json:"ra,omitempty"`
}

TransactionForwardCompatibilityEntry represents a forward compatibility entry. Internal: This should never be used and is not supported.

type TransactionGetCallback added in v10.1.0

type TransactionGetCallback func(*TransactionGetResult, error)

TransactionGetCallback describes a callback for a completed Get or GetOptional operation.

type TransactionGetOptions added in v10.1.0

type TransactionGetOptions struct {
	Agent          *Agent
	OboUser        string
	ScopeName      string
	CollectionName string
	Key            []byte

	// NoRYOW will disable the RYOW logic used to enable transactions
	// to naturally read any mutations they have performed.
	// VOLATILE: This parameter is subject to change.
	NoRYOW bool
}

TransactionGetOptions provides options for a Get operation.

type TransactionGetResult added in v10.1.0

type TransactionGetResult struct {
	Meta  *TransactionMutableItemMeta
	Value []byte
	Cas   Cas
	// contains filtered or unexported fields
}

TransactionGetResult represents the result of a Get or GetOptional operation.

type TransactionHooks added in v10.1.0

type TransactionHooks interface {
	BeforeATRCommit(func(err error))
	AfterATRCommit(func(err error))
	BeforeDocCommitted(docID []byte, cb func(err error))
	BeforeRemovingDocDuringStagedInsert(docID []byte, cb func(err error))
	BeforeRollbackDeleteInserted(docID []byte, cb func(err error))
	AfterDocCommittedBeforeSavingCAS(docID []byte, cb func(err error))
	AfterDocCommitted(docID []byte, cb func(err error))
	BeforeStagedInsert(docID []byte, cb func(err error))
	BeforeStagedRemove(docID []byte, cb func(err error))
	BeforeStagedReplace(docID []byte, cb func(err error))
	BeforeDocRemoved(docID []byte, cb func(err error))
	BeforeDocRolledBack(docID []byte, cb func(err error))
	AfterDocRemovedPreRetry(docID []byte, cb func(err error))
	AfterDocRemovedPostRetry(docID []byte, cb func(err error))
	AfterGetComplete(docID []byte, cb func(err error))
	AfterStagedReplaceComplete(docID []byte, cb func(err error))
	AfterStagedRemoveComplete(docID []byte, cb func(err error))
	AfterStagedInsertComplete(docID []byte, cb func(err error))
	AfterRollbackReplaceOrRemove(docID []byte, cb func(err error))
	AfterRollbackDeleteInserted(docID []byte, cb func(err error))
	BeforeCheckATREntryForBlockingDoc(docID []byte, cb func(err error))
	BeforeDocGet(docID []byte, cb func(err error))
	BeforeGetDocInExistsDuringStagedInsert(docID []byte, cb func(err error))
	BeforeRemoveStagedInsert(docID []byte, cb func(err error))
	AfterRemoveStagedInsert(docID []byte, cb func(err error))
	AfterDocsCommitted(func(err error))
	AfterDocsRemoved(func(err error))
	AfterATRPending(func(err error))
	BeforeATRPending(func(err error))
	BeforeATRComplete(func(err error))
	BeforeATRRolledBack(func(err error))
	AfterATRComplete(func(err error))
	BeforeATRAborted(func(err error))
	AfterATRAborted(func(err error))
	AfterATRRolledBack(func(err error))
	BeforeATRCommitAmbiguityResolution(func(err error))
	RandomATRIDForVbucket(cb func(string, error))
	HasExpiredClientSideHook(stage string, docID []byte, cb func(bool, error))
}

TransactionHooks provides a number of internal hooks used for testing. Internal: This should never be used and is not supported.

type TransactionInsertOptions added in v10.1.0

type TransactionInsertOptions struct {
	Agent          *Agent
	OboUser        string
	ScopeName      string
	CollectionName string
	Key            []byte
	Value          json.RawMessage
}

TransactionInsertOptions provides options for a Insert operation.

type TransactionLogItem added in v10.1.4

type TransactionLogItem struct {
	Level LogLevel
	// contains filtered or unexported fields
}

TransactionLogItem represents an entry in the transaction in memory logging.

func (TransactionLogItem) String added in v10.1.4

func (item TransactionLogItem) String() string

type TransactionLogger added in v10.1.4

type TransactionLogger interface {
	Log(level LogLevel, offset int, txnID, attemptID, format string, v ...interface{}) error
}

TransactionLogger is the logger used for logging in transactions. Uncommitted: This API may change in the future.

type TransactionLostATRLocation added in v10.1.0

type TransactionLostATRLocation struct {
	BucketName     string
	ScopeName      string
	CollectionName string
}

TransactionLostATRLocation specifies a specific location where lost transactions should attempt cleanup.

func (TransactionLostATRLocation) String added in v10.1.4

func (tlal TransactionLostATRLocation) String() string

type TransactionMutableItemMeta added in v10.1.0

type TransactionMutableItemMeta struct {
	TransactionID string                                            `json:"txn"`
	AttemptID     string                                            `json:"atmpt"`
	ATR           TransactionMutableItemMetaATR                     `json:"atr"`
	ForwardCompat map[string][]TransactionForwardCompatibilityEntry `json:"fc,omitempty"`
}

TransactionMutableItemMeta represents all the meta-data for a fetched item. Most of this is used for later mutation operations.

type TransactionMutableItemMetaATR added in v10.1.0

type TransactionMutableItemMetaATR struct {
	BucketName     string `json:"bkt"`
	ScopeName      string `json:"scp"`
	CollectionName string `json:"coll"`
	DocID          string `json:"key"`
}

TransactionMutableItemMetaATR represents the ATR for meta.

type TransactionOperationFailedError added in v10.1.0

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

TransactionOperationFailedError is used when a transaction operation fails. Internal: This should never be used and is not supported.

func (TransactionOperationFailedError) Error added in v10.1.0

func (TransactionOperationFailedError) ErrorClass added in v10.1.0

ErrorClass returns the class of error which caused this error.

func (TransactionOperationFailedError) InternalUnwrap added in v10.1.3

func (tfe TransactionOperationFailedError) InternalUnwrap() error

InternalUnwrap returns the underlying error for this error.

func (TransactionOperationFailedError) MarshalJSON added in v10.1.0

func (tfe TransactionOperationFailedError) MarshalJSON() ([]byte, error)

MarshalJSON will marshal this error for the wire.

func (TransactionOperationFailedError) Retry added in v10.1.0

Retry signals whether a new attempt should be made at rollback.

func (TransactionOperationFailedError) Rollback added in v10.1.0

func (tfe TransactionOperationFailedError) Rollback() bool

Rollback signals whether the attempt should be auto-rolled back.

func (TransactionOperationFailedError) ToRaise added in v10.1.0

ToRaise signals which error type should be raised to the application.

type TransactionOptions added in v10.1.0

type TransactionOptions struct {
	// CustomATRLocation specifies a specific location to place meta-data.
	CustomATRLocation TransactionATRLocation

	// ExpirationTime sets the maximum time that this transaction will
	// run for, before expiring.
	ExpirationTime time.Duration

	// DurabilityLevel specifies the durability level that should be used
	// for all write operations performed by this transaction.
	DurabilityLevel TransactionDurabilityLevel

	// KeyValueTimeout specifies the timeout used for all KV writes.
	KeyValueTimeout time.Duration

	// BucketAgentProvider provides a function which returns an agent for
	// a particular bucket by name.
	BucketAgentProvider TransactionsBucketAgentProviderFn

	// TransactionLogger is the logger to use with this transaction.
	// Uncommitted: This API may change in the future.
	TransactionLogger TransactionLogger

	// Internal specifies a set of options for internal use.
	// Internal: This should never be used and is not supported.
	Internal struct {
		Hooks                TransactionHooks
		ResourceUnitCallback func(result *ResourceUnitResult)
	}
}

TransactionOptions specifies options which can be overridden on a per transaction basis.

func (*TransactionOptions) String added in v10.1.5

func (opts *TransactionOptions) String() string

type TransactionProcessATRStats added in v10.1.0

type TransactionProcessATRStats struct {
	NumEntries        int
	NumEntriesExpired int
}

TransactionProcessATRStats is the stats recorded when running a ProcessATR request. Internal: This should never be used and is not supported.

type TransactionRemoveOptions added in v10.1.0

type TransactionRemoveOptions struct {
	Document *TransactionGetResult
}

TransactionRemoveOptions provides options for a Remove operation.

type TransactionReplaceOptions added in v10.1.0

type TransactionReplaceOptions struct {
	Document *TransactionGetResult
	Value    json.RawMessage
}

TransactionReplaceOptions provides options for a Replace operation.

type TransactionResourceUnitResult added in v10.1.5

type TransactionResourceUnitResult struct {
	NumOps     uint32
	ReadUnits  uint32
	WriteUnits uint32
}

TransactionResourceUnitResult describes the number of resource units used by a transaction attempt. Internal: This should never be used and is not supported.

type TransactionResult added in v10.1.0

type TransactionResult struct {
	// TransactionID represents the UUID assigned to this transaction
	TransactionID string

	// Attempts records all attempts that were performed when executing
	// this transaction.
	Attempts []TransactionAttempt

	// UnstagingComplete indicates whether the transaction was succesfully
	// unstaged, or if a later cleanup job will be responsible.
	UnstagingComplete bool
}

TransactionResult represents the result of a transaction which was executed.

type TransactionRollbackCallback added in v10.1.0

type TransactionRollbackCallback func(error)

TransactionRollbackCallback describes a callback for a completed rollback operation.

type TransactionStagedMutation added in v10.1.0

type TransactionStagedMutation struct {
	OpType         TransactionStagedMutationType
	BucketName     string
	ScopeName      string
	CollectionName string
	Key            []byte
	Cas            Cas
	Staged         json.RawMessage
}

TransactionStagedMutation wraps all of the information about a mutation which has been staged as part of the transaction and which should later be unstaged when the transaction has been committed.

type TransactionStagedMutationType added in v10.1.0

type TransactionStagedMutationType int

TransactionStagedMutationType represents the type of a mutation performed in a transaction.

type TransactionStoreCallback added in v10.1.0

type TransactionStoreCallback func(*TransactionGetResult, error)

TransactionStoreCallback describes a callback for a completed Replace operation.

type TransactionUpdateStateOptions added in v10.1.0

type TransactionUpdateStateOptions struct {
	ShouldNotCommit   bool
	ShouldNotRollback bool
	ShouldNotRetry    bool
	State             TransactionAttemptState
	Reason            TransactionErrorReason
}

TransactionUpdateStateOptions are the settings available to UpdateState. This function must only be called once the transaction has entered query mode. Internal: This should never be used and is not supported.

func (TransactionUpdateStateOptions) String added in v10.1.4

func (tuso TransactionUpdateStateOptions) String() string

type TransactionsBucketAgentProviderFn added in v10.1.0

type TransactionsBucketAgentProviderFn func(bucketName string) (*Agent, string, error)

TransactionsBucketAgentProviderFn is a function used to provide an agent for a particular bucket by name.

type TransactionsCleaner added in v10.1.0

type TransactionsCleaner interface {
	AddRequest(req *TransactionsCleanupRequest) bool
	PopRequest() *TransactionsCleanupRequest
	ForceCleanupQueue(cb func([]TransactionsCleanupAttempt))
	QueueLength() int32
	CleanupAttempt(atrAgent *Agent, atrOboUser string, req *TransactionsCleanupRequest, regular bool, cb func(attempt TransactionsCleanupAttempt))
	Close()
	GetAndResetResourceUnits() *TransactionResourceUnitResult
}

TransactionsCleaner is responsible for performing cleanup of completed transactions. Internal: This should never be used and is not supported.

func NewTransactionsCleaner added in v10.1.0

func NewTransactionsCleaner(config *TransactionsConfig) TransactionsCleaner

NewTransactionsCleaner returns a TransactionsCleaner implementation. Internal: This should never be used and is not supported.

type TransactionsCleanupAttempt added in v10.1.0

type TransactionsCleanupAttempt struct {
	Success           bool
	IsReqular         bool
	AttemptID         string
	AtrID             []byte
	AtrCollectionName string
	AtrScopeName      string
	AtrBucketName     string
	Request           *TransactionsCleanupRequest
}

TransactionsCleanupAttempt represents the result of running cleanup for a transaction attempt. Internal: This should never be used and is not supported.

func (TransactionsCleanupAttempt) String added in v10.1.0

func (ca TransactionsCleanupAttempt) String() string

type TransactionsCleanupRequest added in v10.1.0

type TransactionsCleanupRequest struct {
	AttemptID         string
	AtrID             []byte
	AtrCollectionName string
	AtrScopeName      string
	AtrBucketName     string
	Inserts           []TransactionsDocRecord
	Replaces          []TransactionsDocRecord
	Removes           []TransactionsDocRecord
	State             TransactionAttemptState
	ForwardCompat     map[string][]TransactionForwardCompatibilityEntry
	DurabilityLevel   TransactionDurabilityLevel
	Age               time.Duration
}

TransactionsCleanupRequest represents a complete transaction attempt that requires cleanup. Internal: This should never be used and is not supported.

func (*TransactionsCleanupRequest) String added in v10.1.0

func (cr *TransactionsCleanupRequest) String() string

type TransactionsConfig added in v10.1.0

type TransactionsConfig struct {
	// CustomATRLocation specifies a specific location to place meta-data.
	CustomATRLocation TransactionATRLocation

	// ExpirationTime sets the maximum time that transactions created
	// by this TransactionsManager object can run for, before expiring.
	ExpirationTime time.Duration

	// DurabilityLevel specifies the durability level that should be used
	// for all write operations performed by this TransactionsManager object.
	DurabilityLevel TransactionDurabilityLevel

	// KeyValueTimeout specifies the default timeout used for all KV writes.
	KeyValueTimeout time.Duration

	// CleanupWindow specifies how often to the cleanup process runs
	// attempting to garbage collection transactions that have failed but
	// were not cleaned up by the previous client.
	CleanupWindow time.Duration

	// CleanupClientAttempts controls where any transaction attempts made
	// by this client are automatically removed.
	CleanupClientAttempts bool

	// CleanupLostAttempts controls where a background process is created
	// to cleanup any ‘lost’ transaction attempts.
	CleanupLostAttempts bool

	// CleanupQueueSize controls the maximum queue size for the cleanup thread.
	CleanupQueueSize uint32

	// BucketAgentProvider provides a function which returns an agent for
	// a particular bucket by name.
	BucketAgentProvider TransactionsBucketAgentProviderFn

	// LostCleanupATRLocationProvider provides a function which returns a list of LostATRLocations
	// for use in lost transaction cleanup.
	LostCleanupATRLocationProvider TransactionsLostCleanupATRLocationProviderFn

	// CleanupWatchATRs is *NOT* used within the codebase, it is *only* here to provide API level backward
	// compatibility.
	// This should *never* be used.
	CleanupWatchATRs bool

	// Internal specifies a set of options for internal use.
	// Internal: This should never be used and is not supported.
	Internal struct {
		Hooks                   TransactionHooks
		CleanUpHooks            TransactionCleanUpHooks
		ClientRecordHooks       TransactionClientRecordHooks
		EnableNonFatalGets      bool
		EnableParallelUnstaging bool
		EnableExplicitATRs      bool
		EnableMutationCaching   bool
		NumATRs                 int
	}
}

TransactionsConfig specifies various tunable options related to transactions.

func (*TransactionsConfig) String added in v10.1.5

func (config *TransactionsConfig) String() string

type TransactionsDocRecord added in v10.1.0

type TransactionsDocRecord struct {
	CollectionName string
	ScopeName      string
	BucketName     string
	ID             []byte
}

TransactionsDocRecord represents an individual document operation requiring cleanup. Internal: This should never be used and is not supported.

type TransactionsLostCleanupATRLocationProviderFn added in v10.1.0

type TransactionsLostCleanupATRLocationProviderFn func() ([]TransactionLostATRLocation, error)

TransactionsLostCleanupATRLocationProviderFn is a function used to provide a list of ATRLocations for lost transactions cleanup.

type TransactionsManager added in v10.1.0

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

TransactionsManager is the top level wrapper object for all transactions handling. It also manages the cleanup process in the background.

func InitTransactions added in v10.1.0

func InitTransactions(config *TransactionsConfig) (*TransactionsManager, error)

InitTransactions will initialize the transactions library and return a TransactionsManager object which can be used to perform transactions.

func (*TransactionsManager) BeginTransaction added in v10.1.0

func (t *TransactionsManager) BeginTransaction(perConfig *TransactionOptions) (*Transaction, error)

BeginTransaction will begin a new transaction. The returned object can be used to begin a new attempt and subsequently perform operations before finally committing.

func (*TransactionsManager) Close added in v10.1.0

func (t *TransactionsManager) Close() error

Close will shut down this TransactionsManager object, shutting down all background tasks associated with it.

func (*TransactionsManager) Config added in v10.1.0

Config returns the config that was used during the initialization of this TransactionsManager object.

func (*TransactionsManager) Internal added in v10.1.0

Internal returns an TransactionsManagerInternal object which can be used for specialized internal use cases.

func (*TransactionsManager) ResumeTransactionAttempt added in v10.1.0

func (t *TransactionsManager) ResumeTransactionAttempt(txnBytes []byte, options *ResumeTransactionOptions) (*Transaction, error)

ResumeTransactionAttempt allows the resumption of an existing transaction attempt which was previously serialized, potentially by a different transaction client.

type TransactionsManagerInternal added in v10.1.0

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

TransactionsManagerInternal exposes internal methods that are useful for testing and/or other forms of internal use.

func (*TransactionsManagerInternal) CleanupLocations added in v10.1.2

CleanupLocations returns the set of locations currently being watched by the lost transactions process.

func (*TransactionsManagerInternal) CleanupQueueLength added in v10.1.0

func (t *TransactionsManagerInternal) CleanupQueueLength() int32

CleanupQueueLength returns the current length of the client cleanup queue.

func (*TransactionsManagerInternal) CleanupThreadGetAndResetResourceUnits added in v10.1.5

func (t *TransactionsManagerInternal) CleanupThreadGetAndResetResourceUnits() *TransactionResourceUnitResult

CleanupThreadGetAndResetResourceUnits returns the number of resource units used by the standard cleanup thread, // and resets them.

func (*TransactionsManagerInternal) CreateGetResult added in v10.1.0

CreateGetResult creates a false TransactionGetResult which can be used with Replace/Remove operations where the original TransactionGetResult is no longer available.

func (*TransactionsManagerInternal) ForceCleanupQueue added in v10.1.0

func (t *TransactionsManagerInternal) ForceCleanupQueue(cb func([]TransactionsCleanupAttempt))

ForceCleanupQueue forces the transactions client cleanup queue to drain without waiting for expirations.

func (*TransactionsManagerInternal) LostCleanupGetAndResetResourceUnits added in v10.1.5

func (t *TransactionsManagerInternal) LostCleanupGetAndResetResourceUnits() *TransactionResourceUnitResult

LostCleanupGetAndResetResourceUnits returns the number of resource units used by the lost cleanup thread, and resets them.

type UnlockCallback

type UnlockCallback func(*UnlockResult, error)

UnlockCallback is invoked upon completion of a Unlock operation.

type UnlockOptions

type UnlockOptions struct {
	Key            []byte
	Cas            Cas
	CollectionName string
	ScopeName      string
	CollectionID   uint32
	RetryStrategy  RetryStrategy
	Deadline       time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

UnlockOptions encapsulates the parameters for a UnlockEx operation.

type UnlockResult

type UnlockResult struct {
	Cas           Cas
	MutationToken MutationToken

	// Internal: This should never be used and is not supported.
	Internal struct {
		ResourceUnits *ResourceUnitResult
	}
}

UnlockResult encapsulates the result of a UnlockEx operation.

type UserPassPair

type UserPassPair struct {
	Username string
	Password string
}

UserPassPair represents a username and password pair.

type VBucketIDStatsTarget

type VBucketIDStatsTarget struct {
	VbID uint16
}

VBucketIDStatsTarget indicates that a specific vbucket should be targeted by the Stats operation.

type ValueRecorder

type ValueRecorder interface {
	RecordValue(val uint64)
}

ValueRecorder is used for grouping synchronous count metrics.

type VbSeqNoEntry

type VbSeqNoEntry struct {
	VbID  uint16
	SeqNo SeqNo
}

VbSeqNoEntry represents a single GetVbucketSeqnos sequence number entry.

type VbUUID

type VbUUID uint64

VbUUID represents a unique identifier for a particular vbucket history.

type ViewError

type ViewError struct {
	InnerError         error
	DesignDocumentName string
	ViewName           string
	Errors             []ViewQueryErrorDesc
	Endpoint           string
	RetryReasons       []RetryReason
	RetryAttempts      uint32
	// Uncommitted: This API may change in the future.
	ErrorText string
	// Uncommitted: This API may change in the future.
	HTTPResponseCode int
}

ViewError represents an error returned from a view query.

func (ViewError) Error

func (e ViewError) Error() string

Error returns the string representation of this error.

func (ViewError) MarshalJSON

func (e ViewError) MarshalJSON() ([]byte, error)

MarshalJSON implements the Marshaler interface.

func (ViewError) Unwrap

func (e ViewError) Unwrap() error

Unwrap returns the underlying reason for the error

type ViewQueryCallback

type ViewQueryCallback func(*ViewQueryRowReader, error)

ViewQueryCallback is invoked upon completion of a ViewQuery operation.

type ViewQueryErrorDesc

type ViewQueryErrorDesc struct {
	SourceNode string
	Message    string
}

ViewQueryErrorDesc represents specific view error data.

type ViewQueryOptions

type ViewQueryOptions struct {
	DesignDocumentName string
	ViewType           string
	ViewName           string
	Options            url.Values
	RetryStrategy      RetryStrategy
	Deadline           time.Time

	// Internal: This should never be used and is not supported.
	User string

	TraceContext RequestSpanContext
}

ViewQueryOptions represents the various options available for a view query.

type ViewQueryRowReader

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

ViewQueryRowReader providers access to the rows of a view query

func (*ViewQueryRowReader) Close

func (q *ViewQueryRowReader) Close() error

Close immediately shuts down the connection

func (ViewQueryRowReader) Err

func (q ViewQueryRowReader) Err() error

Err returns any errors that occurred during streaming.

func (*ViewQueryRowReader) MetaData

func (q *ViewQueryRowReader) MetaData() ([]byte, error)

MetaData fetches the non-row bytes streamed in the response.

func (*ViewQueryRowReader) NextRow

func (q *ViewQueryRowReader) NextRow() []byte

NextRow reads the next rows bytes from the stream

type WaitForConfigSnapshotCallback added in v10.2.1

type WaitForConfigSnapshotCallback func(*WaitForConfigSnapshotResult, error)

WaitForConfigSnapshotCallback is invoked upon completion of a WaitForConfigSnapshot operation. Volatile: This API is subject to change at any time.

type WaitForConfigSnapshotOptions added in v10.2.1

type WaitForConfigSnapshotOptions struct {
}

WaitForConfigSnapshotOptions encapsulates the parameters for a WaitForConfigSnapshot operation. Volatile: This API is subject to change at any time.

type WaitForConfigSnapshotResult added in v10.2.1

type WaitForConfigSnapshotResult struct {
	Snapshot *ConfigSnapshot
}

WaitForConfigSnapshotResult encapsulates the result of a WaitForConfig operation. Volatile: This API is subject to change at any time.

type WaitUntilReadyCallback

type WaitUntilReadyCallback func(*WaitUntilReadyResult, error)

WaitUntilReadyCallback is invoked upon completion of a WaitUntilReady operation.

type WaitUntilReadyOptions

type WaitUntilReadyOptions struct {
	DesiredState ClusterState  // Defaults to ClusterStateOnline
	ServiceTypes []ServiceType // Defaults to all services
	// If the cluster state is offline and a connect error has been observed then fast fail and return it.
	RetryStrategy RetryStrategy
}

WaitUntilReadyOptions encapsulates the parameters for a WaitUntilReady operation.

type WaitUntilReadyResult

type WaitUntilReadyResult struct {
}

WaitUntilReadyResult encapsulates the result of a WaitUntilReady operation.

type WithDurationRetryAction

type WithDurationRetryAction struct {
	WithDuration time.Duration
}

WithDurationRetryAction represents an action that indicates to retry with a given duration.

func (*WithDurationRetryAction) Duration

func (ra *WithDurationRetryAction) Duration() time.Duration

Duration is the length of time to wait before retrying an operation.

Notes

Bugs

  • Do not use a synchronous lock for cleanup requests. Because of the need to include the state of the transaction within the cleanup request, we are not able to do registration until the end of commit/rollback, which means that we no longer have the lock on the transaction, and need to relock it.

Source Files

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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