sdk

package
v0.93.0-rc4 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2025 License: MPL-2.0 Imports: 41 Imported by: 1

Documentation

Overview

Package sdk provide an abstraction for communication with API.

Index

Constants

View Source
const (
	HeaderOrganization      = internal.HeaderOrganization
	HeaderProject           = internal.HeaderProject
	HeaderAuthorization     = internal.HeaderAuthorization
	HeaderUserAgent         = internal.HeaderUserAgent
	HeaderTruncatedLimitMax = internal.HeaderTruncatedLimitMax
	HeaderTraceID           = internal.HeaderTraceID
)
View Source
const (
	EnvPrefix      = "NOBL9_SDK_"
	DefaultProject = "default"
)
View Source
const APIVersionRegex = `"?apiVersion"?\s*:\s*"?n9`
View Source
const ProjectsWildcard = "*"

ProjectsWildcard is used in HeaderProject when requesting for all projects.

Variables

View Source
var (
	ErrIoReaderIsNil          = errors.New("io.Reader must no be nil")
	ErrNoFilesMatchingPattern = errors.Errorf(
		"no Nobl9 resource definition files matched the provided path pattern, %s", matchingRulesDisclaimer)
	ErrNoFilesInPath = errors.Errorf("no Nobl9 resource definition files were found under selected path, %s",
		matchingRulesDisclaimer)
	ErrInvalidFile = errors.Errorf("valid Nobl9 resource definition must match against the following regex: '%s'",
		APIVersionRegex)
	ErrInvalidSourceType    = errors.New("invalid ObjectSourceType provided")
	ErrSourceTypeReaderPath = errors.New(
		"ObjectSourceTypeReader ObjectSource may define at most a single ObjectSource.Path")
)
View Source
var ErrInvalidObjectSourceType = fmt.Errorf("not a valid ObjectSourceType, try [%s]", strings.Join(_ObjectSourceTypeNames, ", "))
View Source
var ErrNoDefinitionsFound = errors.New("no definitions in input")

Functions

func DecodeObject added in v0.35.0

func DecodeObject[T manifest.Object](data []byte) (object T, err error)

DecodeObject returns a single, concrete object implementing manifest.Object. It expects exactly one object in the decoded byte slice.

func DecodeObjects added in v0.35.0

func DecodeObjects(data []byte) ([]manifest.Object, error)

DecodeObjects reads objects from the provided bytes slice. It detects if the input is in either of the formats:

func EncodeObject added in v0.83.0

func EncodeObject(object manifest.Object, out io.Writer, format manifest.ObjectFormat) error

EncodeObject writes a single object to the given io.Writer in the specified manifest.ObjectFormat.

func EncodeObjects added in v0.83.0

func EncodeObjects(objects []manifest.Object, out io.Writer, format manifest.ObjectFormat) error

EncodeObjects writes objects to the given io.Writer in the specified manifest.ObjectFormat.

func GetDefaultConfigPath added in v0.30.0

func GetDefaultConfigPath() (string, error)

GetDefaultConfigPath returns the default path to Nobl9 configuration file (config.toml).

func GetSupportedFileExtensions added in v0.35.0

func GetSupportedFileExtensions() []string

GetSupportedFileExtensions returns the file extensions which are used to filter out files to be processed.

func ObjectSourceTypeNames added in v0.35.0

func ObjectSourceTypeNames() []string

ObjectSourceTypeNames returns a list of possible string values of ObjectSourceType.

func PrintObject added in v0.79.1

func PrintObject(object manifest.Object, out io.Writer, format manifest.ObjectFormat) error

PrintObject prints a single object to the given io.Writer in the specified manifest.ObjectFormat. Deprecated: Use EncodeObject instead.

func PrintObjects added in v0.79.1

func PrintObjects(objects []manifest.Object, out io.Writer, format manifest.ObjectFormat) error

PrintObjects prints objects to the given io.Writer in the specified manifest.ObjectFormat. Deprecated: Use EncodeObjects instead.

func ReadObjects added in v0.35.0

func ReadObjects(ctx context.Context, rawSources ...RawObjectSource) ([]manifest.Object, error)

ReadObjects resolves the RawObjectSource it receives and reads all manifest.Object from the resolved ObjectSource.

Refer to ReadObjectsFromSources for more details on the objects' reading logic.

func ReadObjectsFromSources added in v0.35.0

func ReadObjectsFromSources(ctx context.Context, sources ...*ObjectSource) ([]manifest.Object, error)

ReadObjectsFromSources reads from the provided ObjectSource based on the ObjectSourceType. It calculates a sum for each definition read from ObjectSource and won't create duplicates. This allows the user to combine ObjectSource with potentially overlapping paths. If the same exact definition is identified with multiple sources, it will pick the first ObjectSource path it encounters.

If the ObjectSource is of type ObjectSourceTypeGlobPattern or ObjectSourceTypeDirectory and a file does not contain the required APIVersionRegex, it is skipped. However, in case of ObjectSourceTypeFile, it will throw ErrInvalidFile error.

Each ObjectSourceType is handled according to the following logic:

  1. ObjectSourceTypeFile and ObjectSourceTypeDirectory The path can point to a single file or a directory. If it's a directory, all files with the supported extension will be read.

  2. ObjectSourceTypeGlobPattern All files matching the pattern will be read. On top of what is supported by filepath.Match, the pattern may contain double star '**' wildcard placeholders. The double start will be interpreted as a recursive directory search.

  3. ObjectSourceTypeURL The URL to fetch object definitions from. The endpoint at the provided URL should handle GET request by responding with status code 200 and JSON or YAML encoded representation of manifest.Object.

    Note: This URL is not designed to fetch manifest.Object from the Nobl9 API. It can be used, for instance, to fetch the objects from the users internal repository. In order to read manifest.Object from the Nobl9 API, use Client.Objects API.

  4. ObjectSourceTypeReader The [ObjectSource.Reader] is read directly and [ObjectSource.Paths] is ignored.

Types

type APIError added in v0.87.0

type APIError struct {
	// Title is a human-readable summary of the error. It is required.
	Title string `json:"title"`
	// Code is an application-specific error code. It is optional.
	Code string `json:"code,omitempty"`
	// Source provides additional context for the source of the error. It is optional.
	Source *APIErrorSource `json:"source,omitempty"`
}

APIError defines a standardized format for error responses across all Nobl9 public services. It ensures that errors are communicated in a consistent and structured manner, making it easier for developers to handle and debug issues.

type APIErrorSource added in v0.89.0

type APIErrorSource struct {
	// PropertyName is an optional name of the property that caused the error.
	// It can be a JSON path or a simple property name.
	PropertyName string `json:"propertyName,omitempty"`
	// PropertyValue is an optional value of the property that caused the error.
	PropertyValue string `json:"propertyValue,omitempty"`
}

APIErrorSource provides additional context for the source of the APIError.

type APIErrors added in v0.89.0

type APIErrors struct {
	// Errors is a list of errors returned by the API.
	// At least one error is always guaranteed to be set.
	// At the very minimum it will contain just the [APIError.Title].
	Errors []APIError `json:"errors"`
}

APIErrors is an object returned directly by the API which conveys specific API error(s) details.

func (APIErrors) Error added in v0.89.0

func (r APIErrors) Error() string

Error returns a string representation of the error.

type Client

type Client struct {
	Config *Config
	HTTP   *http.Client
	// contains filtered or unexported fields
}

Client is the entrypoint for interacting with Nobl9 API. It provides access to the following APIs:

func DefaultClient added in v0.8.2

func DefaultClient() (*Client, error)

DefaultClient returns fully configured instance of Client with default Config and http.Client.

func NewClient

func NewClient(config *Config) (*Client, error)

NewClient creates a new Client instance with provided Config.

func (*Client) AuthData added in v0.74.0

func (c *Client) AuthData() authdata.Versions

AuthData is used to access specific authentication API version.

func (*Client) CreateRequest added in v0.29.0

func (c *Client) CreateRequest(
	ctx context.Context,
	method, endpoint string,
	headers http.Header,
	q url.Values,
	body io.Reader,
) (*http.Request, error)

CreateRequest creates a new http.Request pointing at the Nobl9 API URL. It also adds all the mandatory headers to the request and encodes query parameters.

func (*Client) Do added in v0.74.0

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

Do is a wrapper around http.Client.Do that adds error handling and response processing.

func (*Client) GetOrganization added in v0.30.0

func (c *Client) GetOrganization(ctx context.Context) (string, error)

GetOrganization returns the organization read from JWT token claims.

func (*Client) GetUser added in v0.79.0

func (c *Client) GetUser(ctx context.Context) (string, error)

GetUser returns the user read from JWT token claims.

func (*Client) Objects added in v0.74.0

func (c *Client) Objects() objects.Versions

Objects is used to access specific manifest.Object API version.

func (*Client) SLOStatusAPI added in v0.89.0

func (c *Client) SLOStatusAPI() slostatusapi.Versions

SLOStatusAPI is used to access specific SLO Status API version.

func (*Client) SetUserAgent added in v0.30.0

func (c *Client) SetUserAgent(userAgent string)

SetUserAgent will set HeaderUserAgent to the provided value.

func (*Client) WithDryRun added in v0.55.0

func (c *Client) WithDryRun() *Client

WithDryRun configures the Client to run all supported state changing operations in dry-run mode.

type Config added in v0.30.0

type Config struct {
	// ClientID is the client ID of the generated access key used to interact with the API.
	// It is required, unless AccessToken is provided.
	ClientID string
	// ClientSecret is the client secret of the generated access key used to interact with the API.
	// It is required, unless AccessToken is provided.
	ClientSecret string
	// AccessToken is an access token used to perform a request to the API.
	// It is required, unless ClientID and ClientSecret are provided.
	// Otherwise, it is generated based on the provided ClientID and ClientSecret.
	AccessToken string
	// Project is the name of the default project used by some of the API requests.
	// It defaults to [DefaultProject].
	Project string
	// URL is the base URL of the Nobl9 API.
	// It is optional and should not be set in most scenarios.
	URL *url.URL
	// OktaOrgURL is the base URL of the Okta organization.
	// It is optional and should not be set in most scenarios.
	OktaOrgURL *url.URL
	// OktaAuthServer is the ID of the Okta authorization server.
	// It is optional and should not be set in most scenarios.
	OktaAuthServer string
	// DisableOkta is a flag that disables Okta authorization.
	// It defaults to false and should not be overridden in most scenarios.
	DisableOkta bool
	// Organization is the name of the organization set in [HeaderOrganization] header.
	// It is optional and should not be set in most scenarios.
	Organization string
	// Timeout is the timeout duration of each HTTP request run against the API.
	Timeout time.Duration
	// FilesPromptEnabled is a flag that enables a prompt for applying/deleting large numbers of files.
	// It is sloctl exclusive.
	FilesPromptEnabled bool
	// FilesPromptThreshold is the number of files that trigger the prompt.
	// It is sloctl exclusive.
	FilesPromptThreshold int
	// contains filtered or unexported fields
}

Config combines the ContextlessConfig and ContextConfig of the current, selected context.

func ReadConfig added in v0.30.0

func ReadConfig(options ...ConfigOption) (*Config, error)

ReadConfig reads the configuration from either (with precedence from top to bottom):

  • provided ConfigOption
  • environment variables
  • config file
  • default values where applicable

Detailed flow can be found in the main README.md.

func (*Config) GetCurrentContext added in v0.30.0

func (c *Config) GetCurrentContext() string

GetCurrentContext returns the current Nobl9 environment context.

func (*Config) GetFileConfig added in v0.30.0

func (c *Config) GetFileConfig() FileConfig

GetFileConfig returns a copy of FileConfig.

func (*Config) Verify added in v0.30.0

func (c *Config) Verify() error

Verify checks if Config fulfills the minimum requirements.

type ConfigOption added in v0.30.0

type ConfigOption func(conf *Config)

ConfigOption conveys extra configuration details for ReadConfig function.

func ConfigOptionEnvPrefix added in v0.30.0

func ConfigOptionEnvPrefix(prefix string) ConfigOption

ConfigOptionEnvPrefix instructs Config to lookup environment variables with the provided prefix. Example:

ConfigOptionEnvPrefix("SLOCTL_") --> looks up "SLOCTL_CLIENT_ID" env and assigns it to [Config.ClientID]

func ConfigOptionFilePath added in v0.30.0

func ConfigOptionFilePath(path string) ConfigOption

ConfigOptionFilePath instructs Config to load config file from the provided path. It has no effect if ConfigOptionNoConfigFile is provided.

func ConfigOptionNoConfigFile added in v0.30.0

func ConfigOptionNoConfigFile() ConfigOption

ConfigOptionNoConfigFile instructs Config to not try reading config.toml file at all.

func ConfigOptionUseContext added in v0.30.0

func ConfigOptionUseContext(context string) ConfigOption

ConfigOptionUseContext instructs Config to use the provided context name. It has no effect if ConfigOptionNoConfigFile is provided.

func ConfigOptionWithCredentials added in v0.30.0

func ConfigOptionWithCredentials(clientID, clientSecret string) ConfigOption

ConfigOptionWithCredentials creates a minimal configuration using provided client id and secret.

type ContextConfig added in v0.30.0

type ContextConfig struct {
	ClientID       string         `toml:"clientId" env:"CLIENT_ID"`
	ClientSecret   string         `toml:"clientSecret" env:"CLIENT_SECRET"`
	AccessToken    string         `toml:"accessToken,omitempty" env:"ACCESS_TOKEN"`
	Project        string         `toml:"project,omitempty" env:"PROJECT"`
	URL            string         `toml:"url,omitempty" env:"URL"`
	OktaOrgURL     string         `toml:"oktaOrgURL,omitempty" env:"OKTA_ORG_URL"`
	OktaAuthServer string         `toml:"oktaAuthServer,omitempty" env:"OKTA_AUTH_SERVER"`
	DisableOkta    *bool          `toml:"disableOkta,omitempty" env:"DISABLE_OKTA"`
	Organization   string         `toml:"organization,omitempty" env:"ORGANIZATION"`
	Timeout        *time.Duration `toml:"timeout,omitempty" env:"TIMEOUT"`
}

ContextConfig stores context specific config.

type ContextlessConfig added in v0.30.0

type ContextlessConfig struct {
	DefaultContext string `toml:"defaultContext" env:"DEFAULT_CONTEXT"`
	// Sloctl exclusive.
	FilesPromptEnabled   *bool `toml:"filesPromptEnabled" env:"FILES_PROMPT_ENABLED"`
	FilesPromptThreshold *int  `toml:"filesPromptThreshold" env:"FILES_PROMPT_THRESHOLD"`
}

ContextlessConfig stores config not tied to any specific context.

type FileConfig added in v0.30.0

type FileConfig struct {
	ContextlessConfig `toml:",inline"`
	Contexts          map[string]ContextConfig `toml:"contexts"`
	// contains filtered or unexported fields
}

FileConfig contains fully parsed config file.

func (*FileConfig) GetPath added in v0.30.0

func (f *FileConfig) GetPath() string

GetPath retrieves the file path FileConfig was loaded from.

func (*FileConfig) Load added in v0.30.0

func (f *FileConfig) Load(path string) error

Load reads the config file from the provided path. If the file does not exist, it will create a default configuration file at the provided path.

func (*FileConfig) Save added in v0.30.0

func (f *FileConfig) Save(path string) (err error)

Save saves FileConfig into provided path, encoding it in TOML format.

type HTTPError added in v0.89.0

type HTTPError struct {
	APIErrors
	// StatusCode is the HTTP status code of the response.
	// Example: 200, 400, 404, 500.
	StatusCode int `json:"statusCode"`
	// Method is the HTTP method used to make the request.
	// Example: "GET", "POST", "PUT", "DELETE".
	Method string `json:"method"`
	// URL is the URL of the API endpoint that was called.
	URL string `json:"url"`
	// TraceID is an optional, unique identifier that can be used to trace the error in Nobl9 platform.
	// Contact [Nobl9 support] if you need help debugging the issue based on the TraceID.
	//
	// [Nobl9 support]: https://nobl9.com/contact/support
	TraceID string `json:"traceId,omitempty"`
}

HTTPError represents an HTTP error response from the API.

func (HTTPError) Error added in v0.89.0

func (r HTTPError) Error() string

Error returns a string representation of the error.

func (HTTPError) IsRetryable added in v0.89.0

func (r HTTPError) IsRetryable() bool

IsRetryable returns true if the underlying API error can be retried.

type ObjectSource added in v0.35.0

type ObjectSource struct {
	// Type defines how the [ObjectSource] should be read when passed to [ReadObjectsFromSources].
	Type ObjectSourceType
	// Paths lists all resolved URIs the [ObjectSource] points at.
	Paths []string
	// Reader may be optionally provided with [ObjectSourceTypeReader]
	// for [ReadObjectsFromSources] to read from the [io.Reader].
	Reader io.Reader
	// Raw is the original, unresolved [RawObjectSource].
	// Example: a relative path which was resolved to its absolute form.
	Raw RawObjectSource
}

ObjectSource represents a single resource definition source.

func NewObjectSourceReader added in v0.35.0

func NewObjectSourceReader(r io.Reader, source RawObjectSource) *ObjectSource

NewObjectSourceReader creates a special instance of ObjectSource with ObjectSourceTypeReader. ReadObjectsFromSources will process the ObjectSource by reading form the provided io.Reader.

func ResolveObjectSource added in v0.35.0

func ResolveObjectSource(rawSource RawObjectSource) (src *ObjectSource, err error)

ResolveObjectSource attempts to resolve a single RawObjectSource producing an ObjectSource instance read to be passed to ReadObjectsFromSources. It interprets the provided URI and associates it with a specific ObjectSourceType. If you wish to create an ObjectSource of type ObjectSourceTypeReader you should use a separate method: NewObjectSourceReader.

func ResolveObjectSources added in v0.35.0

func ResolveObjectSources(rawSources ...RawObjectSource) ([]*ObjectSource, error)

ResolveObjectSources calls ResolveObjectSource on all supplied RawObjectSource and aggregates the resolved ObjectSource. It fails fast on the first encountered error.

func (ObjectSource) String added in v0.35.0

func (o ObjectSource) String() string

String implements fmt.Stringer interface.

type ObjectSourceType added in v0.35.0

type ObjectSourceType int

ObjectSourceType represents the source (where does it come from) of the manifest.Object definition.

ENUM(

File = 1 Directory GlobPattern URL Reader )

const (
	// ObjectSourceTypeFile is a ObjectSourceType of type File.
	ObjectSourceTypeFile ObjectSourceType = iota + 1
	// ObjectSourceTypeDirectory is a ObjectSourceType of type Directory.
	ObjectSourceTypeDirectory
	// ObjectSourceTypeGlobPattern is a ObjectSourceType of type GlobPattern.
	ObjectSourceTypeGlobPattern
	// ObjectSourceTypeURL is a ObjectSourceType of type URL.
	ObjectSourceTypeURL
	// ObjectSourceTypeReader is a ObjectSourceType of type Reader.
	ObjectSourceTypeReader
)

func ParseObjectSourceType added in v0.35.0

func ParseObjectSourceType(name string) (ObjectSourceType, error)

ParseObjectSourceType attempts to convert a string to a ObjectSourceType.

func (ObjectSourceType) IsValid added in v0.35.0

func (x ObjectSourceType) IsValid() bool

IsValid provides a quick way to determine if the typed value is part of the allowed enumerated values

func (ObjectSourceType) String added in v0.35.0

func (x ObjectSourceType) String() string

String implements the Stringer interface.

type RawObjectSource added in v0.35.0

type RawObjectSource = string

RawObjectSource may be interpreted as:

Directories

Path Synopsis
endpoints
Package models defines sdk.Client API request and response models.
Package models defines sdk.Client API request and response models.

Jump to

Keyboard shortcuts

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