rest

package
v2.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2023 License: Apache-2.0 Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultClientTimeout is the timeout for client connection/single operations i.e. this doesn't include retries.
	DefaultClientTimeout = time.Minute

	// DefaultRequestTimeout is the default timeout for REST requests, note that this includes retries.
	DefaultRequestTimeout = time.Minute

	// DefaultDialerTimeout is the default net.Dialer Timeout value for transport of the HTTP client.
	DefaultDialerTimeout = 30 * time.Second

	// DefaultDialerKeepAlive is the default net.Dialer KeepAlive value for transport of the HTTP client.
	DefaultDialerKeepAlive = 30 * time.Second

	// DefaultTransportIdleConnTimeout is the default IdleConnTimeout value for transport of the HTTP client.
	DefaultTransportIdleConnTimeout = 90 * time.Second

	// DefaultTransportContinueTimeout is the default ContinueTimeout value for transport of the HTTP client.
	DefaultTransportContinueTimeout = 0 * time.Second

	// DefaultResponseHeaderTimeout is the default ResponseHeaderTimeout value for transport of the HTTP client.
	DefaultResponseHeaderTimeout = 0 * time.Second

	// DefaultTLSHandshakeTimeout is the default TLSHandshakeTimeout value for transport of the HTTP client.
	DefaultTLSHandshakeTimeout = 10 * time.Second

	// DefaultRequestRetries is the number of times to attempt a REST request for known failure scenarios. When sending
	// a new request the overall request timeout is not reset, however, the connection/client level timeout is.
	DefaultRequestRetries = 3

	// DefaultPollTimeout is the default timeout for polling operations e.g. waiting for a bucket to report as
	// 'healthy'.
	DefaultPollTimeout = 5 * time.Minute

	// TimeoutsEnvVar is the environment variable that should be used to supply configurable timeouts for a REST HTTP
	// client. If it is not provided then the default values are used.
	TimeoutsEnvVar = "CB_REST_HTTP_TIMEOUTS"
)
View Source
const DefaultCCMaxAge = 15 * time.Second

DefaultCCMaxAge is the maximum amount of time a cluster config will be in use before the client begins to try to update the cluster config. This is around the same time used by the SDKS +/- 5 seconds.

Variables

View Source
var (
	// ErrNodeUninitialized is returned if the user attempts to interact with a node which has not been initialized.
	ErrNodeUninitialized = errors.New("attempted to connect to an uninitialized node")

	// ErrNotBootstrapped is returned when attempting to retrieve hosts from an auth provider which has not been
	// bootstrapped; this error shouldn't be returned when using the 'Client' since the constructor performs
	// bootstrapping.
	ErrNotBootstrapped = errors.New("auth provider not bootstrapped")

	// ErrExhaustedClusterNodes is returned if we've failed to update the clients cluster config and have run out of
	// nodes.
	ErrExhaustedClusterNodes = errors.New("exhausted cluster nodes")

	// ErrThisNodeOnlyExpectsASingleAddress is returned if the user attempts to connect to a single node, but provides
	// more than one node in the connection string.
	ErrThisNodeOnlyExpectsASingleAddress = errors.New("when using 'ThisNodeOnly', a connection string with a single " +
		"address should be supplied")

	// ErrConnectionModeRequiresNonTLS is returned if the user attempts to connect using TLS when the connection mode
	// requires non-TLS communication.
	ErrConnectionModeRequiresNonTLS = errors.New("connection mode requires non-TLS communication")

	// ErrStreamWithTimeout is returned if the user attempts to execute a stream with a non-zero timeout.
	ErrStreamWithTimeout = errors.New("using a timeout when executing a streaming request is unsupported")

	// ErrInvalidNetwork is returned if the user supplies an invalid value for the 'network' query parameter.
	ErrInvalidNetwork = errors.New("invalid use of 'network' query parameter, expected 'default' or 'external'")
)

SupportedConnectionModes is a slice of the supported connection modes, this should be considered as read only.

Functions

func IsEndpointNotFound

func IsEndpointNotFound(err error) bool

IsEndpointNotFound returns a boolean indicating whether the given error is an 'EndpointNotFoundError'.

func IsServiceNotAvailable

func IsServiceNotAvailable(err error) bool

IsServiceNotAvailable returns a boolean indicating whether the given error is a 'ServiceNotAvailableError'.

func NewTestHandler

func NewTestHandler(t *testing.T, status int, body []byte) http.HandlerFunc

NewTestHandler creates the most basic type of handler which will respond with the provided status/body.

func NewTestHandlerWithEOF

func NewTestHandlerWithEOF(t *testing.T) http.HandlerFunc

NewTestHandlerWithEOF creates a handler which will cause an EOF error when attempting to read the body.

func NewTestHandlerWithHijack

func NewTestHandlerWithHijack(t *testing.T) http.HandlerFunc

NewTestHandlerWithHijack creates a handler which will hijack the connection an immediately close it; this is simulating a socket closed in flight error.

func NewTestHandlerWithRetries

func NewTestHandlerWithRetries(t *testing.T, numRetries, retryStatus, successStatus int,
	after string, body []byte,
) http.HandlerFunc

NewTestHandlerWithRetries builds upon the basic handler by simulating a flaky/busy endpoint which forces retries a configurable number of times before providing a valid response.

func NewTestHandlerWithStream

func NewTestHandlerWithStream(t *testing.T, responses int, body []byte) http.HandlerFunc

NewTestHandlerWithStream creates a handler which will respond with a streaming response writing the provided body a given number of times.

func NewTestHandlerWithStreamHijack

func NewTestHandlerWithStreamHijack(t *testing.T) http.HandlerFunc

NewTestHandlerWithStreamHijack creates a handler which will respond with a streaming response which will be immediately closed.

func NewTestHandlerWithValue

func NewTestHandlerWithValue(t *testing.T, status int, body []byte, value any) http.HandlerFunc

NewTestHandlerWithValue creates a handler which reads and stores the request body in the provided interface. This should be used to validate that a requests body was the expected value.

Types

type AlternateAddresses

type AlternateAddresses struct {
	External *External `json:"external"`
}

AlternateAddresses represents the 'alternateAddresses' payload sent the 'nodeServices' endpoint.

type AuthProvider

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

AuthProvider is the auth provider for the REST client which handles providing credentials/hosts required to execute REST requests. This handles providing alternative addresses and SSL ports all of which should be completely transparent to the REST client itself.

func NewAuthProvider

func NewAuthProvider(options AuthProviderOptions) *AuthProvider

NewAuthProvider creates a new 'AuthProvider' using the provided credentials.

func (*AuthProvider) GetAllServiceHosts

func (a *AuthProvider) GetAllServiceHosts(service Service) ([]string, error)

GetAllServiceHosts gets all the possible hosts for a given service type.

NOTE: The returned strings are fully qualified hostnames with schemes and ports.

func (*AuthProvider) GetServiceHost

func (a *AuthProvider) GetServiceHost(service Service, offset int) (string, error)

GetServiceHost gets the host required to execute a REST request. A service may be provided to indicate that this request needs to be sent to a specific service.

Supplying an offest will (where possible) "shift" the node index so that we dispatch the request to a different node; this may help in certain cases where a node is currently being removed from the cluster.

NOTE: The returned string is a fully qualified hostname with scheme and port.

func (*AuthProvider) SetClusterConfig

func (a *AuthProvider) SetClusterConfig(host string, config *ClusterConfig) error

SetClusterConfig updates the auth providers cluster config in a thread safe fashion. Returns an error if the provided config is older than the current config; this ensures that we don't use the config from a node which have been removed from the cluster.

func (*AuthProvider) UpdateResolvedAddress

func (a *AuthProvider) UpdateResolvedAddress()

updateResolvedAddress updates the resolved connection string for AuthProvider to contain all node addresses.

type AuthProviderOptions

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

AuthProviderOptions encapsulates the options for creating a new REST AuthProvider.

type AuthenticationError

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

AuthenticationError is returned if we received a 401 status code from the cluster i.e. the users credentials are incorrect.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

type AuthorizationError

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

AuthorizationError is returned if we receive a 403 status code from the cluster which means the credentials are correct but they don't have the needed permissions.

func (*AuthorizationError) Error

func (e *AuthorizationError) Error() string

type BootstrapFailureError

type BootstrapFailureError struct {
	ErrAuthentication error
	ErrAuthorization  error
}

BootstrapFailureError is returned to the user if we've failed to bootstrap the REST client.

NOTE: The error message varies depending on whether we received at least one 401 when attempting to bootstrap.

func (*BootstrapFailureError) Error

func (e *BootstrapFailureError) Error() string

type Client

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

Client is a REST client used to retrieve/send information to/from a Couchbase Cluster.

func NewClient

func NewClient(options ClientOptions) (*Client, error)

NewClient creates a new REST client which will connection to the provided cluster using the given credentials.

NOTE: The returned client may (depending on the provided options) acquire resources which must be cleaned up using the clients 'Close' function. For example, the 'Close' function must be called to cleanup the cluster config polling goroutine.

func (*Client) AltAddr

func (c *Client) AltAddr() bool

AltAddr returns a boolean indicating whether alternate addressing is currently enabled.

func (*Client) Close

func (c *Client) Close()

Close releases any resources that are actively being consumed/used by the client.

func (*Client) ClusterUUID

func (c *Client) ClusterUUID() string

ClusterUUID returns the cluster uuid.

NOTE: This function may return stale data, for the most up-to-date information, use 'GetClusterMetaData'

func (*Client) DeveloperPreview

func (c *Client) DeveloperPreview() bool

DeveloperPreview returns a boolean indicating whether this cluster is in Developer Preview mode.

NOTE: This function may return stale data, for the most up-to-date information, use 'GetClusterMetaData'.

func (*Client) Do

func (c *Client) Do(ctx context.Context, request *Request) (*http.Response, error)

Do converts and executes the provided request returning the raw HTTP response. In general users should prefer to use the 'Execute' function which handles closing resources and returns more informative errors.

NOTE: If the returned error is nil, the Response will contain a non-nil Body which the caller is expected to close.

func (*Client) EnterpriseCluster

func (c *Client) EnterpriseCluster() bool

EnterpriseCluster returns a boolean indicating whether this is an enterprise cluster.

NOTE: This function may return stale data, for the most up-to-date information, use 'GetClusterMetaData'.

func (*Client) Execute

func (c *Client) Execute(request *Request) (*Response, error)

Execute the given request to completion reading the entire response body whilst honoring request level retries/timeout.

func (*Client) ExecuteStream

func (c *Client) ExecuteStream(request *Request) (<-chan StreamingResponse, error)

ExecuteStream executes the given request, returning a read only channel which can be used to read updates from a streaming endpoint.

NOTE: The returned channel will be close when the remote connection closes the socket, in this case no error will be returned.

func (*Client) ExecuteStreamWithContext

func (c *Client) ExecuteStreamWithContext(ctx context.Context, request *Request) (<-chan StreamingResponse, error)

ExecuteStreamWithContext executes the given request using the provided context, returning a read only channel which can be used to read updates from a streaming endpoint.

The returned channel will be close when either: 1. The remote connection closes the socket, in this case no error will be returned 2. The given context is cancelled, again no error will be returned

func (*Client) ExecuteWithContext

func (c *Client) ExecuteWithContext(ctx context.Context, request *Request) (*Response, error)

ExecuteWithContext the given request to completion, using the provided context, reading the entire response body whilst honoring request level retries/timeout.

func (*Client) GetAllServiceHosts

func (c *Client) GetAllServiceHosts(service Service) ([]string, error)

GetAllServiceHosts retrieves a list of all the nodes in the cluster that are running the provided service.

func (*Client) GetServiceHost

func (c *Client) GetServiceHost(service Service) (string, error)

GetServiceHost retrieves the address for a single node in the cluster which is running the provided service.

func (*Client) Nodes

func (c *Client) Nodes() Nodes

Nodes returns a copy of the slice of all the nodes in the cluster.

NOTE: This function returns a copy because this is the same data structure the client uses to dispatch REST requests.

func (*Client) Poll

func (c *Client) Poll(poll func(attempt int) (bool, error)) (bool, error)

Poll runs the given polling function until we either reach a timeout, or the polling function returns true. Returns a boolean indicating whether we timed out waiting for the polling function to return true.

func (*Client) PollTimeout

func (c *Client) PollTimeout() time.Duration

PollTimeout returns the poll timeout used by the current client.

func (*Client) PollWithContext

func (c *Client) PollWithContext(ctx context.Context, poll func(attempt int) (bool, error)) (bool, error)

PollWithContext runs the given polling function until we either reach a timeout, or the polling function returns true. Returns a boolean indicating whether we timed out waiting for the polling function to return true.

NOTE: Returns true in the event that the provided context is cancelled.

func (*Client) RequestRetries

func (c *Client) RequestRetries() int

RequestRetries returns the number of times a request will be retried for known failure cases.

func (*Client) TLS

func (c *Client) TLS() bool

TLS returns a boolean indicating whether SSL/TLS is currently enabled.

type ClientOptions

type ClientOptions struct {
	ConnectionString string
	Provider         aprov.Provider
	TLSConfig        *tls.Config

	// DisableCCP stops the client from periodically updating the cluster config. This should only be used if you know
	// what you're doing and you're only using a client for a short period of time, otherwise, it's possible for some
	// client functions to return stale data/attempt to address missing nodes.
	DisableCCP bool

	// ConnectionMode is the connection mode to use when connecting to the cluster, this may be used to limit how/where
	// REST requests are dispatched.
	ConnectionMode ConnectionMode

	// ReqResLogLevel is the level at which to the dispatching and receiving of requests/responses.
	ReqResLogLevel log.Level

	// Logger is the passed Logger struct that implements the Log method for logger the user wants to use.
	Logger log.Logger
}

ClientOptions encapsulates the options for creating a new REST client.

type ClusterConfig

type ClusterConfig struct {
	Revision int64 `json:"rev"`
	Nodes    Nodes `json:"nodesExt"`
}

ClusterConfig represents the payload sent by 'ns_server' when hitting the '/pools/default/nodeServices' endpoint.

func (*ClusterConfig) BootstrapNode

func (c *ClusterConfig) BootstrapNode() *Node

BootstrapNode returns the node which we bootstrapped against.

func (*ClusterConfig) FilterOtherNodes

func (c *ClusterConfig) FilterOtherNodes()

FilterOtherNodes filters out all nodes which aren't the bootstrap node; this has the effect of forcing all communication via the bootstrap node.

type ClusterConfigManager

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

ClusterConfigManager is a utility wrapper around the current cluster config which provides utility functions required when periodically updating the REST clients cluster config.

func NewClusterConfigManager

func NewClusterConfigManager(logger log.Logger) *ClusterConfigManager

NewClusterConfigManager returns a new cluster config manager which will not immediately trigger a cluster config update.

func (*ClusterConfigManager) GetClusterConfig

func (c *ClusterConfigManager) GetClusterConfig() *ClusterConfig

GetClusterConfig returns a copy of the current cluster config. This method should be preferred over manually accessing the cluster config to avoid unexpected modifications.

func (*ClusterConfigManager) Update

func (c *ClusterConfigManager) Update(config *ClusterConfig) error

Update attempts to update the cluster config using the one provided, note that it may be rejected depending on the revision id.

func (*ClusterConfigManager) WaitUntilExpired

func (c *ClusterConfigManager) WaitUntilExpired(ctx context.Context)

WaitUntilExpired blocks the calling goroutine until the current config has expired and the client should update the cluster config.

func (*ClusterConfigManager) WaitUntilUpdated

func (c *ClusterConfigManager) WaitUntilUpdated(ctx context.Context)

WaitUntilUpdated triggers a config update and then blocks the calling goroutine until the update is complete.

type ConnectionMode

type ConnectionMode int

ConnectionMode is a connection mode which slightly changes the behavior of the REST client.

const (
	// ConnectionModeDefault is the standard connection mode, connections use HTTP/HTTPS depending on the given
	// connection string, and REST requests may be dispatched to any node in the cluster.
	ConnectionModeDefault ConnectionMode = iota

	// ConnectionModeThisNodeOnly means connections use HTTP/HTTPS depending on the given connection string, and REST
	// requests will only be dispatched to the given node.
	//
	// NOTE: An error will be raised if this connection mode is used where the connection string contains more than one
	// node.
	ConnectionModeThisNodeOnly

	// ConnectionModeLoopback is equivalent to 'ConnectionModeThisNodeOnly with the added requirement that all requests
	// are sent unencrypted, via loopback (127.0.0.1).
	//
	// NOTE: An error will be raised if this connection mode is used where the connection string contains more than one
	// node, or would create a TLS connection.
	ConnectionModeLoopback
)

func (ConnectionMode) AllowTLS

func (c ConnectionMode) AllowTLS() bool

AllowTLS returns a boolean indicating whether users can supply https/couchbases in the connection string.

func (ConnectionMode) ThisNodeOnly

func (c ConnectionMode) ThisNodeOnly() bool

ThisNodeOnly returns a boolean indicating whether we're expecting to only communicate with a single node; the one provided in the connection string.

type ContentType

type ContentType string

ContentType - Convenience wrapper around the content type of a request. Currently only JSON/form encoded are supported.

const (
	// ContentTypeURLEncoded - Indicates that the body of this request is url encoded.
	ContentTypeURLEncoded ContentType = "application/x-www-form-urlencoded"

	// ContentTypeJSON - Indicates that the body of this request is json encoded.
	ContentTypeJSON ContentType = "application/json"
)

type Endpoint

type Endpoint string

Endpoint represents a single REST endpoint. Requests should only be dispatched to endpoints which exist in this file i.e. they shouldn't be created on the fly.

NOTE: Endpoints should not include query parameters, they may be supplied as raw 'url.Values' via the 'Request' data structure and will be encoded and postfixed to the request URL accordingly.

const (
	// EndpointPools is the root of the 'ns_server' REST API. Used to fetch version information from the cluster.
	EndpointPools Endpoint = "/pools"

	// EndpointPoolsDefault represents the default cluster (i.e. 'self'). Used for extracting information about the
	// cluster itself.
	EndpointPoolsDefault Endpoint = "/pools/default"

	// EndpointBuckets represents the 'ns_server' endpoint used to interact with the buckets on the cluster.
	EndpointBuckets Endpoint = "/pools/default/buckets"

	// EndpointBucket represents the endpoint for interacting with a specific named bucket.
	EndpointBucket Endpoint = "/pools/default/buckets/%s"

	// EndpointBucketManifest represents the bucket collections manifest endpoint, can be used to get/update the
	// collection manifest for a bucket.
	EndpointBucketManifest Endpoint = "/pools/default/buckets/%s/scopes"

	// EndpointNodesServices is used during the bootstrapping process to fetch a list of all the nodes in the cluster.
	EndpointNodesServices Endpoint = "/pools/default/nodeServices"
)

func (Endpoint) Format

func (e Endpoint) Format(args ...string) Endpoint

Format returns a new endpoint using 'fmt.Sprintf' to fill in any missing/required elements of the endpoint using the given arguments. All arguments will automatically be path escaped before being inserted into the endpoint.

NOTE: No validation takes place to ensure the correct number of arguments are supplied, that's down to you...

type EndpointNotFoundError

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

EndpointNotFoundError is returned if we received a 404 status code from the cluster.

func (*EndpointNotFoundError) Error

func (e *EndpointNotFoundError) Error() string

type External

type External struct {
	Hostname string    `json:"hostname"`
	Services *Services `json:"ports"`
}

External is similar to the 'Node' structure but encapsulates all the alternative addressing information.

type Header map[string]string

Header is a readability wrapper around key/value pairs which will be set in the REST request header.

type InternalServerError

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

InternalServerError is returned if we received a 500 status code from the cluster.

func (*InternalServerError) Error

func (e *InternalServerError) Error() string

type Method

type Method string

Method is a readability wrapper around the method for a given REST request; only the methods defined in the 'http' module should be used.

type Node

type Node struct {
	Hostname           string             `json:"hostname"`
	Services           *Services          `json:"services"`
	AlternateAddresses AlternateAddresses `json:"alternateAddresses"`
	BootstrapNode      bool               `json:"thisNode"`
}

Node encapsulates the addressing information for a single node in a Couchbase Cluster.

func (*Node) Copy

func (n *Node) Copy() *Node

Copy returns a deep copy of the the node.

func (*Node) GetHostname

func (n *Node) GetHostname(useAltAddr bool) string

GetHostname returns the hostname which can be used to address this node whilst honoring alternative addressing.

NOTE: Will return an empty string if this node doesn't have alternative addressing enabled.

func (*Node) GetPort

func (n *Node) GetPort(service Service, useSSL, useAltAddr bool) uint16

GetPort returns the port which will be used to address this node whilst honoring whether to use ssl and alternative addressing.

NOTE: Will return a zero value port if no valid port can be found.

func (*Node) GetQualifiedHostname

func (n *Node) GetQualifiedHostname(service Service, useSSL, useAltAddr bool) (string, bool)

GetQualifiedHostname returns the fully qualified hostname to this node whilst honoring whether to use ssl or alternative addressing.

NOTE: Will return an empty string if there are no valid ports/addresses that we can use against this node.

type Nodes

type Nodes []*Node

Nodes is a wrapper around a slice of nodes which allows custom unmarshalling.

func (Nodes) Copy

func (n Nodes) Copy() Nodes

Copy returns a deep copy of the slice of nodes.

type OldClusterConfigError

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

OldClusterConfigError is returned when the client attempts to bootstrap against a node which returns a cluster config which is older than the one we already have.

func (*OldClusterConfigError) Error

func (e *OldClusterConfigError) Error() string

type PollFunc

type PollFunc func(attempt uint64) (bool, error)

PollFunc is a readbility wrapper around the function which will be polled by the built in polling functionaility. If an error is return from this function, polling will immediately stop and the error will be bubbled up to the calling function.

NOTE: This function is called synchronously, therefore, blocking for extended periods of time could cause the controlling function to overrun the expected timeout.

type Request

type Request struct {
	// Host overrides the host to which the request is dispatched to, when omitted, a host is chosen based on the
	// service the request is to be dispatched to. If this attribute is provided, 'Service' is ignored.
	//
	// NOTE: Here be dragons, it's far more robust to use the 'Service' attribute to determine which host a request
	// should be dispatched to.
	Host string

	// Method is the method used for this REST request. Should be one of the constants defined in the 'http' module.
	Method Method

	// Header is additional key/value pairs which will be set in the REST request header.
	Header Header

	// ContentType indicates what type of value we are sending to the cluster node.
	ContentType ContentType

	// Body is the request body itself. This attribute is not always required.
	Body []byte

	// Endpoint is the REST endpoint to hit, all endpoints should be of type 'Endpoint' so that urls are correctly
	// escaped.
	Endpoint Endpoint

	// QueryParameters are additional values which will be encoded and postfixed to the request URL.
	QueryParameters url.Values

	// Service indicates that this request should be sent to a node which is running a specific service. If 'Host' is
	// provided, this attribute is ignored.
	Service Service

	// ExpectedStatusCode indicates that when this REST request is successful, we will get this specific status code.
	ExpectedStatusCode int

	// Timeout overrides the default client timeout. If not set the client timeout will be used instead.
	//
	// NOTE: A value of -1 indicates that the timeout should be disabled.
	Timeout time.Duration

	// Idempotent indicates whether this request is idempotent and can be retried.
	//
	// The following attributes (RetryOnStatusCodes and NoRetryOnStatusCodes) may be used to configure retry
	// behavior for the request.
	//
	// NOTE: This only needs to be set for certain methods, as by default some should be idempotent as defined in
	// https://developer.mozilla.org/en-US/docs/Glossary/Idempotent.
	Idempotent bool

	// RetryOnStatusCodes is a list of status codes which will be used to indicate that we should retry the request.
	RetryOnStatusCodes []int

	// NoRetryOnStatusCodes is a list of status codes which will explicitly not be retried.
	NoRetryOnStatusCodes []int
}

Request encapsulates the parameters/options which are required when sending a REST request.

func (*Request) IsIdempotent

func (r *Request) IsIdempotent() bool

IsIdempotent returns a boolean indicating whether this request is idempotent and may be retried.

type Response

type Response struct {
	StatusCode int
	Body       []byte
}

Response represents a REST response from the Couchbase Cluster.

type RetriesExhaustedError

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

RetriesExhaustedError is returned if the REST request was retried the maximum number of times.

NOTE: The number of times retried is configurable at runtime via an environment variable. See the 'Client' constructor for more information.

func (*RetriesExhaustedError) Error

func (e *RetriesExhaustedError) Error() string

func (*RetriesExhaustedError) Unwrap

func (e *RetriesExhaustedError) Unwrap() error

type Service

type Service string

Service represents a service which can be running on a Couchbase node.

const (
	// ServiceManagement represents 'ns_server' e.g. port 8091/18091.
	ServiceManagement Service = "Management"

	// ServiceAnalytics represents the Analytics Service.
	ServiceAnalytics Service = "Analytics"

	// ServiceData represents the KV/Data Service.
	ServiceData Service = "Data"

	// ServiceEventing represents the cluster level Eventing Service.
	ServiceEventing Service = "Eventing"

	// ServiceGSI represents the Indexing Service.
	ServiceGSI Service = "Indexing"

	// ServiceQuery represents the Query Service e.g. nodes running N1QL.
	ServiceQuery Service = "Query"

	// ServiceSearch represents the Search/Full Text Search Service.
	ServiceSearch Service = "Search"

	// ServiceViews represents hosts accepting requests for Views.
	ServiceViews Service = "Views"

	// ServiceBackup represents hosts accepting requests for the Backup Service.
	ServiceBackup Service = "Backup"
)

type ServiceNotAvailableError

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

ServiceNotAvailableError is returned if the requested service is is unavailable i.e. there are no nodes in the cluster running that service.

func (*ServiceNotAvailableError) Error

func (e *ServiceNotAvailableError) Error() string

type Services

type Services struct {
	CAPI              uint16 `json:"capi"`
	CAPISSL           uint16 `json:"capiSSL"`
	KV                uint16 `json:"kv"`
	KVSSL             uint16 `json:"kvSSL"`
	Management        uint16 `json:"mgmt"`
	ManagementSSL     uint16 `json:"mgmtSSL"`
	FullText          uint16 `json:"fts"`
	FullTextSSL       uint16 `json:"ftsSSL"`
	SecondaryIndex    uint16 `json:"indexHttp"`
	SecondaryIndexSSL uint16 `json:"indexHttps"`
	N1QL              uint16 `json:"n1ql"`
	N1QLSSL           uint16 `json:"n1qlSSL"`
	Eventing          uint16 `json:"eventingAdminPort"`
	EventingSSL       uint16 `json:"eventingSSL"`
	CBAS              uint16 `json:"cbas"`
	CBASSSL           uint16 `json:"cbasSSL"`
	Backup            uint16 `json:"backupAPI"`
	BackupSSL         uint16 `json:"backupAPIHTTPS"`
}

Services encapsulates the ports that are active on this cluster node.

func (*Services) GetPort

func (s *Services) GetPort(service Service, useSSL bool) uint16

GetPort returns the port which a request should be sent to whilst honoring whether to use ssl.

type SocketClosedInFlightError

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

SocketClosedInFlightError is returned if the client socket was closed during an active request. This is usually due to socket being closed by the remote host in the event of a fatal error.

func (*SocketClosedInFlightError) Error

func (e *SocketClosedInFlightError) Error() string

type StreamingResponse

type StreamingResponse struct {
	// Payload is the raw payload received from a streaming endpoint.
	Payload []byte

	// Error is an error received during streaming, after the first error, the stream will be terminated.
	Error error
}

StreamingResponse encapsulates a single streaming response payload/error.

type TestBucket

type TestBucket struct {
	UUID        string
	NumVBuckets uint16
	// Manifest should be a '*collections.Manifest' from 'backup'.
	Manifest json.Marshaler
}

TestBucket represents a bucket that will exist in the test cluster. These attributes will configure the values returned by REST requests to the cluster.

type TestBuckets

type TestBuckets map[string]*TestBucket

TestBuckets is a readbility alias around a map of buckets.

type TestCluster

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

TestCluster is a mock Couchbase cluster used for unit testing functionaility which relies on the REST client.

func NewTestCluster

func NewTestCluster(t *testing.T, options TestClusterOptions) *TestCluster

NewTestCluster creates a new test cluster using the provided options.

NOTE: By default, the /pools, /pools/default and /pools/default/nodeServices endpoints are implemented and their return values can be manipulated via the cluster options. These endpoints can be overridden if required, however, note that they will still be required to return valid data which can be used to bootstrap the client.

func (*TestCluster) Address

func (t *TestCluster) Address() string

Address returns the address of the cluster, for the time being should always be "127.0.0.1".

func (*TestCluster) Bucket

func (t *TestCluster) Bucket(name string) func(writer http.ResponseWriter, request *http.Request)

Bucket implements the /pools/default/buckets/<bucket> endpoint, values can be modified by modifying the buckets in the cluster using the cluster options.

func (*TestCluster) BucketManifest

func (t *TestCluster) BucketManifest(name string) func(writer http.ResponseWriter, request *http.Request)

BucketManifest implements the /pools/default/buckets/<bucket>/scopes endpoint. The returned manifest may be set using the cluster options.

func (*TestCluster) Buckets

func (t *TestCluster) Buckets(writer http.ResponseWriter, _ *http.Request)

Buckets implements the /pools/default/buckets endpoint, values can be modified by modifying the buckets in the cluster using the cluster options.

func (*TestCluster) Certificate

func (t *TestCluster) Certificate() *x509.Certificate

Certificate returns the certificate which can be used to authenticate the cluster.

NOTE: This will be <nil> if the cluster is not running with TLS enabled.

func (*TestCluster) Close

func (t *TestCluster) Close()

Close stops the server releasing any held resources.

func (*TestCluster) Handler

func (t *TestCluster) Handler(writer http.ResponseWriter, request *http.Request)

Handler is the base handler function for requests, additional endpoint handlers may be added using the 'Handlers' attribute of the cluster options.

NOTE: The current test will fatally terminate if no valid handler is found.

func (*TestCluster) Hostname

func (t *TestCluster) Hostname() string

Hostname returns the cluster hostname, for the time being this will always be "localhost".

func (*TestCluster) NodeServices

func (t *TestCluster) NodeServices(writer http.ResponseWriter, _ *http.Request)

NodeServices implements the /pools/default/nodeServices endpoint, values can be modified by modifying the nodes in the cluster using the cluster options.

func (*TestCluster) Nodes

func (t *TestCluster) Nodes() Nodes

Nodes returns the list of nodes in the cluster, generated using the test nodes provided in the cluster options.

func (*TestCluster) Pools

func (t *TestCluster) Pools(writer http.ResponseWriter, _ *http.Request)

Pools implements the /pools endpoint, the return values can be modified using the cluster options.

func (*TestCluster) PoolsDefault

func (t *TestCluster) PoolsDefault(writer http.ResponseWriter, _ *http.Request)

PoolsDefault implements the /pools/default endpoint, values can be modified by modifying the nodes in the cluster using the cluster options.

func (*TestCluster) Port

func (t *TestCluster) Port() uint16

Port returns the port which requests should be sent to; this will be the same port for all services.

NOTE: This port is randomly selected at runtime and will therefore vary.

func (*TestCluster) URL

func (t *TestCluster) URL() string

URL returns the fully qualified URL which can be used to connect to the cluster.

type TestClusterOptions

type TestClusterOptions struct {
	// Used for the /pools endpoint
	Enterprise       bool
	UUID             string
	DeveloperPreview bool

	// Used for both the /pools/default and the /pools/default/nodeServices endpoint
	Nodes TestNodes

	// Used for the /pools/default/buckets endpoint
	Buckets TestBuckets

	// Additional handler functions which are run to handle a REST request dispatched to the cluster
	Handlers TestHandlers

	// A non-nil TLS config indicates that the cluster should use TLS
	TLSConfig *tls.Config
}

TestClusterOptions encapsulates the options which can be passed when creating a new test cluster. These options configure the behavior/setup of the cluster.

type TestHandlers

type TestHandlers map[string]http.HandlerFunc

TestHandlers is a readbility wrapper around the endpoint handlers for a test cluster.

func (TestHandlers) Add

func (e TestHandlers) Add(method, endpoint string, handler http.HandlerFunc)

Add a new handler to the endpoint handlers, note that the method is required to ensure unique handlers for each endpoint.

func (TestHandlers) Handle

func (e TestHandlers) Handle(writer http.ResponseWriter, request *http.Request) bool

Handle utility function which handles the provided request returning a boolen indicating whether a handler was found.

type TestNode

type TestNode struct {
	Version    cbvalue.Version
	Status     string
	Services   []Service
	SSL        bool
	AltAddress bool
}

TestNode encapsulates the options which can be used to configure a single node in a test cluster.

type TestNodes

type TestNodes []*TestNode

TestNodes is a readbility wrapper around a slice of test nodes.

type UnexpectedEndOfBodyError

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

UnexpectedEndOfBodyError is returned if the length of the request body does not match the expected length. This may happen in the event that the 'Content-Length' header value is incorrectly set.

func (*UnexpectedEndOfBodyError) Error

func (e *UnexpectedEndOfBodyError) Error() string

type UnexpectedStatusCodeError

type UnexpectedStatusCodeError struct {
	Status int
	// contains filtered or unexported fields
}

UnexpectedStatusCodeError returned if a request was executed successfully, however, we received a response status code which was unexpected.

NOTE: During development its possible to hit this error in the event that the expected status code is set incorrectly and the successful response does not return a body so is therefore something to watch out for.

func (*UnexpectedStatusCodeError) Error

func (e *UnexpectedStatusCodeError) Error() string

type UnknownAuthorityError

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

UnknownAuthorityError is returned when the dispatched REST request receives an 'UnknownAuthorityError'.

func (*UnknownAuthorityError) Error

func (e *UnknownAuthorityError) Error() string

type UnknownX509Error

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

UnknownX509Error is returned when the dispatched REST request receives a generic (unhandled) x509 error.

func (*UnknownX509Error) Error

func (e *UnknownX509Error) Error() string

func (*UnknownX509Error) Unwrap

func (e *UnknownX509Error) Unwrap() error

Jump to

Keyboard shortcuts

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