sdk

package
v0.92.3 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2024 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 JSON (manifest.RawObjectFormatJSON) or YAML (manifest.RawObjectFormatYAML format.

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(s) it receives and calls ReadObjectsFromSources on the resolved ObjectSource(s).

func ReadObjectsFromSources added in v0.35.0

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

ReadObjectsFromSources reads from the provided ObjectSource(s) based on the ObjectSourceType. For ObjectSourceTypeReader it will read directly from ObjectSource.Reader, otherwise it reads from all the ObjectSource.Paths. It calculates a sum for each definition read from ObjectSource and won't create duplicates. This allows the user to combine ObjectSource(s) with possibly overlapping paths. If the same exact definition is identified with multiple sources, it will choose 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 thrown ErrInvalidFile error.

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 represents API high level client.

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

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)

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

func (*Client) SLOStatusAPI added in v0.89.0

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

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             string
	ClientSecret         string
	AccessToken          string
	Project              string
	URL                  *url.URL
	OktaOrgURL           *url.URL
	OktaAuthServer       string
	DisableOkta          bool
	Organization         string
	Timeout              time.Duration
	FilesPromptEnabled   bool
	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 config_activity.mmd.

func (*Config) GetCurrentContext added in v0.30.0

func (c *Config) GetCurrentContext() string

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.

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, an example might be 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 a 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 a ObjectSourceTypeReader ObjectSource 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(s) and aggregates the resolved ObjectSource(s). 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 origin (where does it come from) of 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 (with interpretation): - file path (ObjectSourceTypeFile or ObjectSourceTypeDirectory) - glob pattern (ObjectSourceTypeGlobPattern) - URL (ObjectSourceTypeURL) - input provided via io.Reader, like os.Stdin (ObjectSourceTypeReader)

type Response added in v0.8.0

type Response struct {
	Objects      []manifest.Object
	TruncatedMax int
}

Directories

Path Synopsis
endpoints
authdata
Package authdata aggregates API endpoints' versions which are related to authentication data such as fetching agent credentials.
Package authdata aggregates API endpoints' versions which are related to authentication data such as fetching agent credentials.
authdata/v1
Package v1 defines methods for managing various authentication data.
Package v1 defines methods for managing various authentication data.
objects
Package objects aggregates manifest.Object API endpoints' versions.
Package objects aggregates manifest.Object API endpoints' versions.
objects/v1
Package v1 defines methods for managing manifest.Object.
Package v1 defines methods for managing manifest.Object.
slostatusapi
Package slostatusapi provides the API for managing SLO status API requests in the SDK.
Package slostatusapi provides the API for managing SLO status API requests in the SDK.
slostatusapi/v1
Package v1 provides the API for managing SLO status API V1 requests in the SDK.
Package v1 provides the API for managing SLO status API V1 requests in the SDK.
slostatusapi/v2
Package v2 provides the API for managing SLO status API V2 requests in the SDK.
Package v2 provides the API for managing SLO status API V2 requests in the SDK.
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