bonsai

package
v2.4.0 Latest Latest
Warning

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

Go to latest
Published: May 16, 2024 License: MPL-2.0 Imports: 17 Imported by: 0

Documentation

Overview

Package bonsai wraps the Bonsai.io HTTP API to create a Go API Client.

Index

Constants

View Source
const (
	// Version reflects this API Client's version.
	Version = "v2.4.0"
	// BaseEndpoint is the target API URL base location.
	BaseEndpoint = "https://api.bonsai.io"
	// UserAgent is the internally used value for the AccessKey-Agent header
	// in all outgoing HTTP requests.
	UserAgent = "bonsai-api-go/" + Version
)

Client representation configuration.

View Source
const (
	// DefaultClientBurstAllowance is the default Bonsai API request burst
	// allowance.
	DefaultClientBurstAllowance = 60
	// DefaultClientBurstDuration is the default interval for a token
	// bucket of size DefaultClientBurstAllowance to be refilled.
	DefaultClientBurstDuration = 1 * time.Minute
	// ProvisionClientBurstAllowance is the default Bonsai API request burst allowance.
	ProvisionClientBurstAllowance = 5
	// ProvisionClientBurstDuration is the default interval for a token bucket
	// of size ProvisionClientBurstAllowance to be refilled.
	ProvisionClientBurstDuration = 1 * time.Minute
)

Client rate limiter configuration.

View Source
const (
	HTTPHeaderContentType        = "Content-Type"
	HTTPContentTypeJSON   string = "application/json"
)

HTTP Content Types and related Header.

View Source
const (
	ClusterAPIBasePath = "/clusters"
)
View Source
const (
	Float64Epsilon = 1e-9
)
View Source
const (
	// HeaderRetryAfter holds the number of seconds to delay before making the next request.
	// ref: https://bonsai.io/docs/api-error-429-too-many-requests
	HeaderRetryAfter = "Retry-After"
)

Common API Response headers.

View Source
const (
	PlanAPIBasePath = "/plans"
)
View Source
const ReleaseAPIBasePath = "/releases"
View Source
const (
	SpaceAPIBasePath = "/spaces"
)

Variables

View Source
var (
	ErrHTTPStatusNotFound            = errors.New("not found")
	ErrHTTPStatusForbidden           = errors.New("forbidden")
	ErrHTTPStatusPaymentRequired     = errors.New("payment required")
	ErrHTTPStatusUnprocessableEntity = errors.New("unprocessable entity")
	ErrHTTPStatusUnauthorized        = errors.New("unauthorized")
	ErrHTTPStatusTooManyRequests     = errors.New("too many requests")
)

HTTP Status Response Errors.

Functions

func IoClose

func IoClose(c io.Closer, err error) error

IoClose will catch io.Closer errors and wrap them around the previous errors, if any.

Note: due to the Go spec, in order to actually modify the parent's error value, the calling function *must* use named result parameters.

ref: https://go.dev/ref/spec#Defer_statements

Types

type AccessKey

type AccessKey Credential

func NewAccessKey

func NewAccessKey(user string) (AccessKey, error)

NewAccessKey is a convenience method for verifying that access keys intended to be used with the API are valid HTTP header values.

type AccessToken

type AccessToken Credential

func NewAccessToken

func NewAccessToken(password string) (AccessToken, error)

NewAccessToken is a convenience method for verifying that access tokens intended to be used with the API are valid HTTP header values.

type Application

type Application struct {
	Name    string
	Version string
}

func (Application) String

func (app Application) String() string

type Client

type Client struct {

	// Clients
	Space   SpaceClient
	Plan    PlanClient
	Release ReleaseClient
	Cluster ClusterClient
	// contains filtered or unexported fields
}

Client is the exported client that users interact with.

func NewClient

func NewClient(options ...ClientOption) *Client

func (*Client) Do

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

Do performs an HTTP request against the API.

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error)

NewRequest creates an HTTP request against the API. The returned request is assigned with ctx and has all necessary headers set (auth, user agent, etc.).

func (*Client) SetTransport

func (c *Client) SetTransport(t http.RoundTripper)

Transport returns the HTTP transport used by the Client to make requests.

func (*Client) Transport

func (c *Client) Transport() http.RoundTripper

Transport returns the HTTP transport used by the Client to make requests.

func (*Client) UserAgent

func (c *Client) UserAgent() string

type ClientLimiter

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

type ClientOption

type ClientOption func(*Client)

ClientOption is a functional option, used to configure Client.

func WithApplication

func WithApplication(app Application) ClientOption

WithApplication configures the client to represent itself as a particular Application by modifying the AccessKey-Agent header sent in all requests.

func WithCredentialPair

func WithCredentialPair(pair CredentialPair) ClientOption

WithCredentialPair configures a Client to use the specified username for Basic authorization.

func WithDefaultRateLimit

func WithDefaultRateLimit(l *rate.Limiter) ClientOption

WithDefaultRateLimit configures the default rate limit for client requests.

func WithEndpoint

func WithEndpoint(endpoint string) ClientOption

WithEndpoint configures a Client to use the specified API endpoint.

func WithHTTPTransport

func WithHTTPTransport(t http.RoundTripper) ClientOption

WithHTTPTransport configures the Client's HTTP Transport, such that "the mechanism by which individual HTTP requests are made" can be overridden.

func WithProvisionRateLimit

func WithProvisionRateLimit(l *rate.Limiter) ClientOption

WithProvisionRateLimit configures the rate limit for client requests to the Provision API.

type CloudProvider

type CloudProvider struct {
	// A machine-readable name for the cloud provider in which this space is
	// deployed.
	Provider string `json:"provider"`
	// A machine-readable name for the geographic region of the server group.
	Region string `json:"region"`
}

CloudProvider contains details about the cloud provider and region attributes.

type Cluster

type Cluster struct {
	// Slug represents a unique, machine-readable name for the cluster.
	// A cluster slug is based its name at creation, to which a random integer
	// is concatenated.
	Slug string `json:"slug"`
	// Name is the human-readable name of the cluster.
	Name string `json:"name"`
	// URI is a link to additional information about this cluster.
	URI string `json:"uri"`

	// Plan holds some information about the cluster's current subscription plan.
	Plan Plan `json:"plan"`

	// Release holds some information about the cluster's current release.
	Release Release `json:"release"`

	// Space holds some information about where the cluster is running.
	Space Space `json:"space"`

	// Stats holds a collection of statistics about the cluster.
	Stats ClusterStats `json:"stats"`

	// ClusterAccess holds information about connecting to the cluster.
	Access ClusterAccess `json:"access"`

	// State represents the current state of the cluster. This indicates what
	// the cluster is doing at any given moment.
	State ClusterState `json:"state"`
}

Cluster represents a single cluster on your account.

type ClusterAccess

type ClusterAccess struct {
	// Host name of the cluster.
	Host string `json:"host"`
	// HTTP Port the cluster is running on.
	Port int `json:"port"`
	// HTTP Scheme needed to access the cluster. Default: "https".
	Scheme string `json:"scheme"`

	// User holds the username to access the cluster with.
	// Only shown once, during cluster creation.
	Username string `json:"user,omitempty"`
	// Pass holds the password to access the cluster with.
	// Only shown once, during cluster creation.
	Password string `json:"pass,omitempty"`
	// URL is the Cluster endpoint for access.
	// Only shown once, during cluster creation.
	URL string `json:"url,omitempty"`
}

ClusterAccess holds information about connecting to the cluster.

type ClusterAllOpts

type ClusterAllOpts struct {
	// Optional. A query string for filtering matching clusters.
	// This currently works on name.
	Query string `url:"q,omitempty"`
	// Optional. A string which will constrain results to parent or child
	// cluster. Valid values are: "parent", "child"
	Tenancy string `url:"tenancy,omitempty"`
	// Optional. A string representing the account, region, space, or cluster
	// path where the cluster is located. You can get a list of available spaces
	// with the [bonsai.SpaceClient] API. Space path prefixes work here, so you
	// can find all clusters in a given region for a given cloud.
	Location string `url:"location,omitempty"`
}

type ClusterClient

type ClusterClient struct {
	*Client
}

ClusterClient is a client for the Clusters API.

func (*ClusterClient) All

func (c *ClusterClient) All(ctx context.Context) ([]Cluster, error)

All lists all active clusters on your account.

func (*ClusterClient) Create

func (*ClusterClient) Destroy

Destroy triggers the deprovisioning of the cluster associated with the slug.

func (*ClusterClient) Do

func (c *ClusterClient) Do(ctx context.Context, req *http.Request) (*Response, error)

Do performs an HTTP request against the API, with any required Cluster-specific configuration/limitations - for example, rate limiting.

func (*ClusterClient) GetBySlug

func (c *ClusterClient) GetBySlug(ctx context.Context, slug string) (Cluster, error)

GetBySlug gets a Cluster from the Clusters API by its slug.

func (*ClusterClient) Update

type ClusterCreateOpts

type ClusterCreateOpts struct {
	// Required. A String representing the name for the new cluster.
	Name string `json:"name"`
	// The slug of the Plan that the new cluster will be configured for.
	// Use the [PlanClient.All] method to view a list of all Plans available.
	Plan string `json:"plan,omitempty"`
	// The path of the Space where the new cluster should be deployed to.
	// Use the [SpaceClient.All] method to view a list of all Spaces.
	Space string `json:"space,omitempty"`
	// The Search Service Release that the new cluster will use.
	// Use the [ReleaseClient.All] method to view a list of all Spaces.
	Release string `json:"release,omitempty"`
}

func (ClusterCreateOpts) Valid

func (o ClusterCreateOpts) Valid() error

type ClusterResultGetBySlug added in v2.2.0

type ClusterResultGetBySlug struct {
	Cluster `json:"cluster"`
}

type ClusterState

type ClusterState string

ClusterState represents the current state of the cluster, indicating what the cluster is doing at any given moment.

const (
	ClusterStateDeprovisioned  ClusterState = "DEPROVISIONED"
	ClusterStateDeprovisioning ClusterState = "DEPROVISIONING"
	ClusterStateDisabled       ClusterState = "DISABLED"
	ClusterStateMaintenance    ClusterState = "MAINTENANCE"
	ClusterStateProvisioned    ClusterState = "PROVISIONED"
	ClusterStateProvisioning   ClusterState = "PROVISIONING"
	ClusterStateReadOnly       ClusterState = "READONLY"
	ClusterStateUpdatingPlan   ClusterState = "UPDATING PLAN"
)

type ClusterStats

type ClusterStats struct {
	// Number of documents in the index.
	Docs int64 `json:"docs,omitempty"`
	// Number of shards the cluster is using.
	ShardsUsed int64 `json:"shards_used,omitempty"`
	// Number of bytes the cluster is using on-disk.
	DataBytesUsed int64 `json:"data_bytes_used,omitempty"`
}

ClusterStats holds *some* statistics about the cluster.

This attribute should not be used for real-time monitoring! Stats are updated every 10-15 minutes. To monitor real-time metrics, monitor your cluster directly, via the Index Stats API.

type ClusterUpdateOpts

type ClusterUpdateOpts struct {
	// Required. A String representing the name for the new cluster.
	Name string `json:"name"`
	// Required. The slug of the Plan that the new cluster will be configured for.
	// Use the [PlanClient.All] method to view a list of all Plans available.
	Plan string `json:"plan,omitempty"`
}

func (ClusterUpdateOpts) Valid

func (o ClusterUpdateOpts) Valid() error

type ClustersResultCreate

type ClustersResultCreate struct {
	// Message contains details about the cluster creation request.
	Message string `json:"message"`
	// Monitor holds a URI to the Cluster overview page.
	Monitor string        `json:"monitor"`
	Access  ClusterAccess `json:"access"`
}

ClustersResultCreate is the result response for Create (POST) requests to the clusters endpoint.

type ClustersResultDestroy

type ClustersResultDestroy struct {
	// Message contains details about the cluster destroy request.
	Message string `json:"message"`
	// Monitor holds a URI to the Cluster overview page.
	Monitor string `json:"monitor"`
}

ClustersResultDestroy is the result response for Destroy (DELETE) requests to the clusters endpoint.

type ClustersResultList

type ClustersResultList struct {
	Clusters []Cluster `json:"clusters"`
}

ClustersResultList is a wrapper around a slice of Clusters for json unmarshaling.

type ClustersResultUpdate

type ClustersResultUpdate struct {
	// Message contains details about the cluster update request.
	Message string `json:"message"`
	// Monitor holds a URI to the Cluster overview page.
	Monitor string `json:"monitor"`
}

ClustersResultUpdate is the result response for Update (PUT) requests to the clusters endpoint.

type Credential

type Credential string

func (Credential) Empty

func (c Credential) Empty() bool

func (Credential) NotEmpty

func (c Credential) NotEmpty() bool

type CredentialPair

type CredentialPair struct {
	AccessKey
	AccessToken
}

func (CredentialPair) Empty

func (c CredentialPair) Empty() bool

func (CredentialPair) NotEmpty

func (c CredentialPair) NotEmpty() bool

type PaginatedResponse

type PaginatedResponse struct {
	PageNumber   int `json:"page_number"`
	PageSize     int `json:"page_size"`
	TotalRecords int `json:"total_records"`
}

type Plan

type Plan struct {
	// Represents a machine-readable name for the plan.
	Slug string `json:"slug"`
	// Represents the human-readable name of the plan.
	Name string `json:"name,omitempty"`
	// Represents the plan price in cents.
	PriceInCents int64 `json:"price_in_cents,omitempty"`
	// Represents the plan billing interval in months.
	BillingIntervalInMonths int `json:"billing_interval_months,omitempty"`
	// Indicates whether the plan is single-tenant or not. A value of false
	// indicates the Cluster will share hardware with other Clusters. Single
	// tenant environments can be reached via the public Internet.
	SingleTenant *bool `json:"single_tenant,omitempty"`
	// Indicates whether the plan is on a publicly addressable network.
	// Private plans provide environments that cannot be reached by the public
	// Internet. A VPC connection will be needed to communicate with a private
	// cluster.
	PrivateNetwork *bool `json:"private_network,omitempty"`
	// A collection of search release slugs available for the plan. Additional
	// information about a release can be retrieved from the Releases API.
	AvailableReleases []Release `json:"available_releases"`
	AvailableSpaces   []Space   `json:"available_spaces"`

	// A URI to retrieve more information about this Plan.
	URI string `json:"uri,omitempty"`
}

Plan represents a subscription plan.

func (*Plan) UnmarshalJSON

func (p *Plan) UnmarshalJSON(data []byte) error

type PlanClient

type PlanClient struct {
	*Client
}

PlanClient is a client for the Plans API.

func (*PlanClient) All

func (c *PlanClient) All(ctx context.Context) ([]Plan, error)

All lists all Plans from the Plans API.

func (*PlanClient) GetBySlug

func (c *PlanClient) GetBySlug(ctx context.Context, slug string) (Plan, error)

GetBySlug gets a Plan from the Plans API by its slug.

type PlansResultList

type PlansResultList struct {
	Plans []Plan `json:"plans"`
}

PlansResultList is a wrapper around a slice of Plans for json unmarshaling.

func (*PlansResultList) UnmarshalJSON

func (p *PlansResultList) UnmarshalJSON(data []byte) error

type Release

type Release struct {
	// The name for the release.
	Name string `json:"name,omitempty"`
	// The machine-readable name for the deployment.
	Slug string `json:"slug,omitempty"`
	// The service type of the deployment - for example, "elasticsearch".
	ServiceType string `json:"service_type,omitempty"`
	// The version of the release.
	Version string `json:"version,omitempty"`
	// Whether the release is available on multitenant deployments.
	MultiTenant *bool `json:"multitenant,omitempty"`

	// A URI to retrieve more information about this Release.
	URI string `json:"uri,omitempty"`
	// PackageName is the package name of the release.
	PackageName string `json:"package_name,omitempty"`
}

Release is a version of Elasticsearch available to the account.

type ReleaseClient

type ReleaseClient struct {
	*Client
}

ReleaseClient is a client for the Releases API.

func (*ReleaseClient) All

func (c *ReleaseClient) All(ctx context.Context) ([]Release, error)

All lists all Releases from the Releases API.

func (*ReleaseClient) GetBySlug

func (c *ReleaseClient) GetBySlug(ctx context.Context, slug string) (Release, error)

GetBySlug gets a Release from the Releases API by its slug.

type ReleasesResultList

type ReleasesResultList struct {
	Releases []Release `json:"releases,omitempty"`
}

ReleasesResultList is a wrapper around a slice of Releases for json unmarshaling.

type Response

type Response struct {
	BodyBuf           bytes.Buffer `json:"-"`
	PaginatedResponse `json:"pagination"`
	// contains filtered or unexported fields
}

func NewResponse

func NewResponse() (*Response, error)

NewResponse reserves this function signature, and is the recommended way to instantiate a Response, as its behavior may change.

func (*Response) MarkPaginationComplete

func (r *Response) MarkPaginationComplete()

func (*Response) WithHTTPResponse

func (r *Response) WithHTTPResponse(httpResp *http.Response) error

WithHTTPResponse assigns an *http.Response to a *Response item and reads its response body into the *Response.

type ResponseError

type ResponseError struct {
	Errors []string `json:"errors"`
	Status int      `json:"status"`
}

ResponseError captures API response errors returned as JSON in supported scenarios.

ref: https://bonsai.io/docs/introduction-to-the-api

func (ResponseError) Error

func (r ResponseError) Error() string

Error represents ResponseError, which may have multiple Errors as a string.

The community is as yet undecided on a great way to handle this ref: https://github.com/golang/go/issues/47811

func (ResponseError) Is

func (r ResponseError) Is(target error) bool

type Space

type Space struct {
	// A machine-readable name for the server group.
	Path string `json:"path"`
	// Indicates whether the space is isolated and inaccessible from the
	// public Internet. A VPC connection will be needed to communicate
	// with a private cluster.
	PrivateNetwork *bool `json:"private_network,omitempty"`
	// Details about the cloud provider and region attributes.
	Cloud *CloudProvider `json:"cloud,omitempty"`

	// The geographic region in which the cluster is running.
	Region string `json:"region,omitempty"`
	// A URI to retrieve more information about this Space.
	URI string `json:"uri,omitempty"`
}

Space represents the server groups and geographic regions available to their account, where clusters may be provisioned.

type SpaceClient

type SpaceClient struct {
	*Client
}

SpaceClient is a client for the Spaces API.

func (*SpaceClient) All

func (c *SpaceClient) All(ctx context.Context) ([]Space, error)

All lists all Spaces from the Spaces API.

func (*SpaceClient) GetByPath

func (c *SpaceClient) GetByPath(ctx context.Context, spacePath string) (Space, error)

type SpaceListOptions

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

func (SpaceListOptions) IsZero

func (l SpaceListOptions) IsZero() bool

func (SpaceListOptions) Valid

func (l SpaceListOptions) Valid() bool

type SpacesResultList

type SpacesResultList struct {
	Spaces []Space `json:"spaces,omitempty"`
}

SpacesResultList is a wrapper around a slice of Spaces for json unmarshaling.

Directories

Path Synopsis
internal
dep
Package dep imports unused, but licensed, dependencies for capture by tooling like "go mod vendor" and github.com/google/go-licenses
Package dep imports unused, but licensed, dependencies for capture by tooling like "go mod vendor" and github.com/google/go-licenses

Jump to

Keyboard shortcuts

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