core

package
v0.138.0 Latest Latest
Warning

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

Go to latest
Published: Apr 2, 2026 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderAccept        = "Accept"
	HeaderAuthorization = "Authorization"
	HeaderContentType   = "Content-Type"
	HeaderContentLength = "Content-Length"
	HeaderUserAgent     = "User-Agent"
	HeaderXTenantName   = "X-Tenant-Name"
)

HTTP Header Names

View Source
const (
	ContentTypeJSON           = "application/json"
	ContentTypeMultipartForm  = "multipart/form-data"
	ContentTypeOpenAPI        = "application/openapi+json"
	ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
	ContentTypeTextPlain      = "text/plain"
	ContentTypeOctetStream    = "application/octet-stream"
)

HTTP Content Types

View Source
const (
	AuthTypeBasic  = "Basic"
	AuthTypeBearer = "Bearer"
)

HTTP Authentication Types

View Source
const (
	ResourceTypeKey = "@resourceType"
)
View Source
const VTaskKey = "VTask"

Variables

View Source
var ExtraMethodRegistry = map[string]map[string]ExtraMethodMetadata{}

ExtraMethodRegistry is a global registry of extra method metadata This is populated by code generation during build time

Functions

func BuildResourcePathWithID

func BuildResourcePathWithID(resourcePath string, id any, additionalSegments ...string) string

BuildResourcePathWithID builds a complete resource path with an ID parameter and optional additional segments. It takes a resource path (e.g., "/users"), an ID of any type, and optional additional path segments. Returns the complete path (e.g., "/users/123/tenant_data" or "/users/uuid/tenant_data").

func ClientVersion

func ClientVersion() string

func ExpectStatusCodes

func ExpectStatusCodes(err error, codes ...int) bool

func FlexibleUnmarshal

func FlexibleUnmarshal(data []byte, target any) error

FlexibleUnmarshal unmarshals JSON with flexible type conversion for string fields. When a string field in the target struct receives a non-string value (number, boolean), it automatically converts it to a string.

func IgnoreStatusCodes

func IgnoreStatusCodes(err error, codes ...int) error

func IsApiError

func IsApiError(err error) bool

func IsNotFoundErr

func IsNotFoundErr(err error) bool

func IsTooManyRecordsErr

func IsTooManyRecordsErr(err error) bool

func Must

func Must[T any](v T, err error) T

func RegisterExtraMethod added in v0.122.0

func RegisterExtraMethod(resourceType, methodName, httpVerb, urlPath, summary string)

RegisterExtraMethod registers metadata for an extra method This is called by generated init() functions

func Request

func Request[T RecordUnion](
	ctx context.Context,
	r VastResourceAPIWithContext,
	verb, path string,
	params, body Params,
) (T, error)

func RequestWithHeaders added in v0.104.0

func RequestWithHeaders[T RecordUnion](
	ctx context.Context,
	r VastResourceAPIWithContext,
	verb, path string,
	params, body Params,
	headers []http.Header,
) (T, error)

func ToBool added in v0.123.0

func ToBool(v any) (bool, error)

ToBool converts various types to boolean. Handles special string cases like "true", "false", "1", "0", "yes", "no".

func WithAuth

func WithAuth(config *VMSConfig) error

WithAuth validates that either a username/password combination or an API token is provided for authentication. Returns an error if neither is set.

func WithFillFn

func WithFillFn(config *VMSConfig) error

WithFillFn is a VMSConfigFunc that installs a custom FillFn into the global fillFunc used by the Record.Fill method.

This allows the client to globally override the default record-to-struct population logic.

func WithHost

func WithHost(config *VMSConfig) error

WithHost validates that the Host field is not empty. Panics if Host is an empty string.

func WithUserAgent

func WithUserAgent(config *VMSConfig) error

WithUserAgent sets a default User-Agent header if none is provided in the config. This helps identify the client in HTTP requests. If UserAgent is empty, it defaults to "VASTData Client".

Types

type ApiError

type ApiError struct {
	Method     string
	URL        string
	StatusCode int
	Body       string
	// contains filtered or unexported fields
}

ApiError represents an error returned from an API request.

func (*ApiError) Error

func (e *ApiError) Error() string

Error implements the error interface.

type ApiRTokenAuthenticator

type ApiRTokenAuthenticator struct {
	Host      string
	Port      uint64
	SslVerify bool
	Token     string
	Tenant    string
}

type AsyncResult added in v0.107.0

type AsyncResult struct {
	TaskId  int64
	Rest    VastRest
	Ctx     context.Context
	Success bool
	Err     error
}

AsyncResult represents the result of an asynchronous task. It contains the task's ID, completion status, and any error that occurred.

Fields:

  • TaskId: The unique identifier of the task
  • Rest: The REST client used to query task status
  • Ctx: The context associated with the task operation
  • Success: True if task completed successfully, false if failed
  • Err: The error that occurred during task execution (nil if successful)

func MaybeAsyncResultFromRecord added in v0.107.0

func MaybeAsyncResultFromRecord(ctx context.Context, record Record, rest VastRest) *AsyncResult

MaybeAsyncResultFromRecord attempts to extract an async task ID from a record and create an AsyncResult.

This function handles two common patterns in VAST API responses:

  1. Direct task response: The record itself has a ResourceTypeKey and represents the task
  2. Nested task response: The record has an "async_task" field containing the task information

If the record doesn't contain any task information, or if the task ID cannot be extracted, this function returns nil.

Parameters:

  • ctx: The context to associate with the async result
  • record: The record that may contain async task information
  • rest: The REST client for task operations

Returns:

  • *AsyncResult: An AsyncResult if task information was found, nil otherwise

func NewAsyncResult added in v0.107.0

func NewAsyncResult(ctx context.Context, taskId int64, rest VastRest) *AsyncResult

NewAsyncResult creates a new AsyncResult from a task ID and REST client.

This constructor is used to create an AsyncResult when you already have a task ID. The context is stored for potential future use with waiting operations.

Parameters:

  • ctx: The context associated with the task operation
  • taskId: The ID of the asynchronous task
  • rest: The REST client that can be used to query task status

Returns:

  • *AsyncResult: A new AsyncResult instance

func (*AsyncResult) IsFailed added in v0.109.0

func (ar *AsyncResult) IsFailed() bool

IsFailed returns true if the task failed during execution.

func (*AsyncResult) IsSuccess added in v0.110.0

func (ar *AsyncResult) IsSuccess() bool

IsSuccess returns true if the task completed successfully.

func (*AsyncResult) Wait added in v0.110.0

func (ar *AsyncResult) Wait(timeout time.Duration) (Record, error)

Wait polls the task status until it completes, fails, or times out.

This method continuously polls the VTask resource to check the task's state. It uses exponential backoff with configurable intervals to avoid overwhelming the API. The Success and Err fields are updated based on the task outcome.

Parameters:

  • timeout: Maximum duration to wait for task completion (uses ar.Ctx for cancellation)

Returns:

  • Record: The final task record when completed
  • error: An error if the task fails, times out, or an API error occurs

Task states handled:

  • "completed": Sets Success=true, returns the task record
  • "running": Continues polling with backoff
  • Any other state: Sets Success=false, Err=error, returns error with task messages

After calling Wait(), check ar.Success and ar.Err for task execution results.

type Authenticator

type Authenticator interface {
	// contains filtered or unexported methods
}

type Awaitable

type Awaitable interface {
	WaitWithContext(context.Context) (Record, error)
	Wait(time.Duration) (Record, error)
}

type BaseAuthAuthenticator

type BaseAuthAuthenticator struct {
	Host      string
	Port      uint64
	SslVerify bool
	Username  string
	Password  string
	Tenant    string
	// contains filtered or unexported fields
}

type DisplayableRecord

type DisplayableRecord interface {
	Renderable
	Filler
}

DisplayableRecord defines a unified interface for working with structured data that has been deserialized from an API response. It combines both rendering and data population capabilities.

Implementing types must support:

  • Rendering themselves as human-readable output via the Renderable interface.
  • Filling provided container structs or slices using the Filler interface.

This interface is implemented by Record and RecordSet, allowing generic handling of different response shapes (single item or list).

type Dummy

type Dummy struct {
	*VastResource
}

Dummy resource is used to support Request interceptors for "low level" session methods like GET, POST etc.

func NewDummy added in v0.103.0

func NewDummy(ctx context.Context, session RESTSession) *Dummy

type DummyRest added in v0.103.0

type DummyRest struct {
	Session RESTSession
	// contains filtered or unexported fields
}

func (*DummyRest) GetCtx added in v0.103.0

func (rest *DummyRest) GetCtx() context.Context

func (*DummyRest) GetResourceMap added in v0.103.0

func (rest *DummyRest) GetResourceMap() map[string]VastResourceAPIWithContext

func (*DummyRest) GetSession added in v0.103.0

func (rest *DummyRest) GetSession() RESTSession

func (*DummyRest) SetCtx added in v0.103.0

func (rest *DummyRest) SetCtx(ctx context.Context)

type ExtraMethodInfo

type ExtraMethodInfo struct {
	Name     string // Method name (e.g., "ViewCheckPermissionsTemplates_POST")
	HTTPVerb string // HTTP method (GET, POST, PATCH, DELETE)
	Path     string // Full path (e.g., "/views/{id}/check_permissions_templates/")
}

ExtraMethodInfo contains information about an extra method discovered on a resource. Extra methods are non-CRUD operations that follow the pattern <MethodName>_<HTTPVerb>.

func DiscoverExtraMethodsFromResource added in v0.104.0

func DiscoverExtraMethodsFromResource(resource any) []ExtraMethodInfo

DiscoverExtraMethodsFromResource discovers all extra methods for a resource using the metadata registry.

type ExtraMethodMetadata added in v0.122.0

type ExtraMethodMetadata struct {
	MethodName string // e.g., "ApiTokenRevoke_PATCH"
	HTTPVerb   string // e.g., "PATCH"
	URLPath    string // e.g., "/apitokens/{id}/revoke/"
	Summary    string // e.g., "Revoke API Token"
}

ExtraMethodMetadata stores the URL path and HTTP verb for extra methods This should be generated at compile time by the code generator

func GetAllExtraMethodsForResource added in v0.122.0

func GetAllExtraMethodsForResource(resourceType string) []ExtraMethodMetadata

GetAllExtraMethodsForResource returns all extra methods for a resource type

func GetExtraMethodMetadata added in v0.122.0

func GetExtraMethodMetadata(resourceType, methodName string) (ExtraMethodMetadata, bool)

GetExtraMethodMetadata retrieves metadata for a specific extra method

type FileData

type FileData struct {
	Filename string
	Content  []byte
}

FileData represents a file to be uploaded in multipart form data

type FillFunc

type FillFunc func(Record, any) error

type Filler

type Filler interface {
	// Fill populates the given container with data from the implementing type.
	// The container can be a pointer to a struct (for Record),
	// or a pointer to a slice of structs (for RecordSet).
	Fill(container any) error
}

Filler is a generic interface for filling a struct or slice of structs.

type InterceptableVastResourceAPI

type InterceptableVastResourceAPI interface {
	RequestInterceptor
	VastResourceAPIWithContext
}

InterceptableVastResourceAPI combines request interception with vast resource behavior.

type Iterator added in v0.104.0

type Iterator interface {
	// Next advances to the next page and returns the records and any error.
	// Returns empty RecordSet when there are no more pages.
	Next() (RecordSet, error)

	// Previous moves to the previous page and returns the records and any error.
	// Returns empty RecordSet when there is no previous page.
	Previous() (RecordSet, error)

	// HasNext returns true if there is a next page available.
	HasNext() bool

	// HasPrevious returns true if there is a previous page available.
	HasPrevious() bool

	// Count returns the total count of items (if available from pagination metadata).
	// Returns -1 if count information is not available.
	Count() int

	// PageSize returns the current page size.
	PageSize() int

	// Reset resets the iterator to the first page and returns the first page records.
	Reset() (RecordSet, error)

	// All fetches all remaining pages and returns all records as a single RecordSet.
	// This should be used with caution for large datasets.
	All() (RecordSet, error)
}

Iterator provides an interface for iterating over paginated or non-paginated API results. It abstracts away the differences between paginated resources (with next/previous links) and non-paginated resources (flat lists).

func NewResourceIterator added in v0.104.0

func NewResourceIterator(ctx context.Context, resource VastResourceAPIWithContext, params Params, pageSize int) Iterator

NewResourceIterator creates an iterator that makes raw HTTP requests to preserve pagination metadata. If pageSize is 0 or negative, uses the session's configured PageSize (default: 0 means no page_size param sent).

type JWTAuthenticator

type JWTAuthenticator struct {
	Host         string
	Port         uint64
	SslVerify    bool
	RespectProxy bool
	Username     string
	Password     string
	Token        *jwtToken
	Tenant       string
	// contains filtered or unexported fields
}

type KeyLocker

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

func NewKeyLocker

func NewKeyLocker() *KeyLocker

NewKeyLocker creates a new KeyLocker.

func (*KeyLocker) Lock

func (kl *KeyLocker) Lock(keys ...any) func()

Lock returns a function that will unlock the key when called

type MultipartFormData

type MultipartFormData struct {
	Body        io.Reader
	ContentType string
}

MultipartFormData represents the result of ToMultipartFormData()

type NotFoundError

type NotFoundError struct {
	Resource string
	Query    string
}

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

type Params

type Params map[string]any

Params represents a generic set of key-value parameters, used for constructing query strings or request bodies.

func NewParamsFromStruct

func NewParamsFromStruct(obj any) (Params, error)

NewParamsFromStruct creates a new Params map from any struct, respecting json tags. This is a convenience function that creates a new Params and calls FromStruct on it.

Special handling for RawData field: If the struct has a RawData field (type Params) with len > 0, the RawData map is returned directly instead of parsing the struct fields. This allows bypassing typed field parsing when custom query parameters are needed.

Example usage:

type MyRequest struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
    RawData Params `json:"-"`
}

// Using typed fields:
req := MyRequest{Name: "John", Age: 30}
params, err := NewParamsFromStruct(req)
// params contains: {"name": "John", "age": 30}

// Using RawData (bypasses typed fields):
req := MyRequest{RawData: Params{"custom__filter": "value"}}
params, err := NewParamsFromStruct(req)
// params contains: {"custom__filter": "value"}

Returns a new Params map or an error if the conversion fails.

func (*Params) FromStruct

func (pr *Params) FromStruct(obj any) error

FromStruct converts any struct to Params while maintaining the json tags as keys. This method uses reflection to directly extract struct fields and their json tags, avoiding the overhead of JSON marshaling/unmarshaling.

Example usage:

type MyRequest struct {
    Name     string `json:"name"`
    Age      int    `json:"age"`
    Optional *bool  `json:"optional,omitempty"`
}

req := MyRequest{Name: "John", Age: 30}
params := make(Params)
err := params.FromStruct(req)
// params now contains: {"name": "John", "age": 30}

Returns an error if the input is not a struct or pointer to struct.

func (*Params) ToBody

func (pr *Params) ToBody() (io.Reader, error)

ToBody serializes the Params into a JSON-encoded io.Reader, suitable for use as the body of an HTTP POST, PUT, or PATCH request.

func (*Params) ToMultipartFormData

func (pr *Params) ToMultipartFormData() (*MultipartFormData, error)

ToMultipartFormData serializes the Params into multipart/form-data format. Files should be provided as FileData values in the Params map. Returns a MultipartFormData struct containing the body and content type.

func (*Params) ToQuery

func (pr *Params) ToQuery() string

ToQuery serializes the Params into a URL-encoded query string. This is useful for GET requests where parameters are passed via the URL.

func (*Params) Update

func (pr *Params) Update(other Params, override bool)

Update merges another Params map into the original Params. If a key already exists and `override` is true, its value is skipped. If a key doesn't exist, the key-value pair is added.

func (*Params) UpdateWithout

func (pr *Params) UpdateWithout(other Params, override bool, without []string)

UpdateWithout merges another Params map into the original Params. If a key exists in the `without` slice, it is skipped. If a key already exists and `override` is false, its value is also skipped. Otherwise, the key-value pair is added or updated based on the `override` flag.

func (*Params) Without

func (pr *Params) Without(keys ...string)

Without removes the specified keys from the Params map. This is useful when you want to exclude certain parameters before sending a request.

type Record

type Record map[string]any

Record represents a single generic data object as a key-value map. It's commonly used to unmarshal a single JSON object from an API response. When a response is empty (e.g., 204 No Content), an empty Record{} is returned.

func IgnoreNotFound

func IgnoreNotFound(val Record, err error) (Record, error)

func ModelToRecord

func ModelToRecord(model any) Record

ModelToRecord converts any typed model struct to a Record with @resourceType This is a helper function for typed resources to convert their models to Records

func ToRecord

func ToRecord(m map[string]interface{}) Record

func WaitAPICondition added in v0.110.0

func WaitAPICondition(
	ctx context.Context,
	caller VastResourceAPIWithContext,
	searchParams Params,
	waitAPIConditionConfig *WaitAPIConditionConfig,
	verifyFn func(Record) (bool, error),
) (Record, error)

WaitAPICondition polls an API endpoint until a condition is met or timeout occurs.

This is a generic polling function that repeatedly calls an API endpoint, applies a verification function to the result, and waits with exponential backoff between attempts until the condition is satisfied or a timeout is reached.

Parameters:

  • ctx: The context for the operation (can be used for cancellation)
  • caller: The resource API to poll (must support GetByIdWithContext or GetWithContext)
  • searchParams: Parameters to identify the resource (if contains "id", uses GetById, otherwise Get)
  • waitAPIConditionConfig: Configuration for timeout, intervals, and backoff (nil uses defaults)
  • verifyFn: Function that checks if the condition is met. Returns (true, nil) when complete, (false, nil) to continue polling, or (false, error) to abort with error.

Returns:

  • Record: The final record when the condition is met
  • error: An error if verification fails, timeout occurs, or API call fails

Default configuration (when waitAPIConditionConfig is nil):

  • Timeout: 10 minutes
  • Initial Interval: 500ms
  • Max Interval: 30 seconds
  • Backoff Factor: 0.25 (25% increase per iteration)

func (Record) Empty

func (r Record) Empty() bool

func (Record) Fill

func (r Record) Fill(container any) error

Fill populates the exported fields of the given struct pointer using values from the Record (a map[string]any). It uses JSON marshaling and unmarshaling to automatically map keys to struct fields based on their `json` tags and perform type conversions where needed.

The target container must be a non-nil pointer to a struct. Fields in the struct must be exported (i.e., start with an uppercase letter) and optionally tagged with `json` to match keys in the Record.

JSON-based conversion handles common type mismatches (e.g., string to int, int to string) and nested structures if compatible.

Returns an error if the container is not a pointer to a struct or if serialization fails.

func (Record) PrettyJson

func (r Record) PrettyJson(indent ...string) string

PrettyJson prints the Record as JSON, optionally indented

func (Record) PrettyTable

func (r Record) PrettyTable() string

PrettyTable prints a single Record as a table

func (Record) RecordGUID

func (r Record) RecordGUID() string

RecordGUID returns the name of the record as a string. It looks up the "name" field in the record map.

func (Record) RecordID

func (r Record) RecordID() int64

RecordID returns the ID of the record as an int64. It looks up the "id" field in the record map.

func (Record) RecordName

func (r Record) RecordName() string

RecordName returns the name of the record as a string. It looks up the "name" field in the record map.

func (Record) RecordTenantID

func (r Record) RecordTenantID() int64

RecordTenantID returns the tenant's ID as an int64. It looks up the "id" field in the record map.

func (Record) RecordTenantName

func (r Record) RecordTenantName() string

RecordTenantName returns the name of the tenant as a string. It looks up the "tenant_name" field in the record map.

func (Record) SetMissingValue

func (r Record) SetMissingValue(key string, value any)

SetMissingValue If the key is not present in the Record, set it to the provided value

func (Record) String

func (r Record) String() string

type RecordSet

type RecordSet []Record

RecordSet represents a list of Record objects. It is typically used to represent responses containing multiple items.

func ToRecordSet

func ToRecordSet(list []map[string]any) (RecordSet, error)

func (RecordSet) Empty

func (rs RecordSet) Empty() bool

func (RecordSet) Fill

func (rs RecordSet) Fill(container any) error

Fill populates the provided container slice with data from the RecordSet. The container must be a non-nil pointer to a slice of structs. Each Record in the RecordSet is individually marshaled into an element of the slice using JSON serialization, and appended to the resulting slice.

Example usage:

var users []User
err := recordSet.Fill(&users)
if err != nil {
    // handle error
}

Parameters:

  • container: must be a pointer to a slice of structs (e.g., *[]T or *[]*T).

Returns an error if:

  • The container is not a non-nil pointer to a slice.
  • The slice element type is not a struct.
  • Any Record in the RecordSet fails to unmarshal into an element.

func (RecordSet) PrettyJson

func (rs RecordSet) PrettyJson(indent ...string) string

PrettyJson prints the Record as JSON, optionally indented

func (RecordSet) PrettyTable

func (rs RecordSet) PrettyTable() string

PrettyTable prints the full RecordSet by rendering each individual Record

type RecordUnion

type RecordUnion interface {
	Record | RecordSet
}

RecordUnion defines a union of supported record types for generic operations. It can be a single Record or a RecordSet. This allows functions to operate on any supported response type using Go generics.

type Renderable

type Renderable interface {
	PrettyTable() string
	PrettyJson(indent ...string) string
}

Renderable is an interface implemented by types that can render themselves into a human-readable string format, typically for CLI display or logging.

type RequestInterceptor

type RequestInterceptor interface {
	// BeforeRequest is invoked prior to sending the API request.
	//
	// Parameters:
	//   - ctx: The request context, useful for deadlines, tracing, or cancellation.
	//   - req: Request object
	//   - verb: The HTTP method (e.g., GET, POST, PUT).
	//   - url: The URL path being accessed (including query params)
	//   - body: The request body as an io.Reader, typically containing JSON data.
	BeforeRequest(context.Context, *http.Request, string, string, io.Reader) error

	// AfterRequest is invoked after the API response is received.
	//
	// The input and output are of type Renderable, which includes types like:
	//   - Record: a single key-value response object
	//   - RecordSet: a list of Record objects
	//   - Record: a map response (may be empty Record{} for DELETE operations)
	//
	// This method can inspect, mutate, or log the response data.
	//
	// Returns:
	//   - A (possibly modified) Renderable
	//   - An error if the interceptor encounters issues processing the response
	AfterRequest(context.Context, Renderable) (Renderable, error)
	// contains filtered or unexported methods
}

RequestInterceptor defines a middleware-style interface for intercepting API requests and responses in client-server interactions. It allows implementing logic that runs before sending a request and after receiving a response. Typical use cases include logging, request mutation, authentication, and response transformation.

type ResourceIterator added in v0.104.0

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

ResourceIterator implements the Iterator interface for VAST API resources. It makes raw HTTP requests to preserve pagination metadata from the API.

func (*ResourceIterator) All added in v0.104.0

func (it *ResourceIterator) All() (RecordSet, error)

All fetches all pages and returns all records.

func (*ResourceIterator) Count added in v0.104.0

func (it *ResourceIterator) Count() int

Count returns the total count of items.

func (*ResourceIterator) HasNext added in v0.104.0

func (it *ResourceIterator) HasNext() bool

HasNext returns true if there is a next page.

func (*ResourceIterator) HasPrevious added in v0.104.0

func (it *ResourceIterator) HasPrevious() bool

HasPrevious returns true if there is a previous page.

func (*ResourceIterator) Next added in v0.104.0

func (it *ResourceIterator) Next() (RecordSet, error)

Next advances to the next page and returns the records and any error.

func (*ResourceIterator) PageSize added in v0.104.0

func (it *ResourceIterator) PageSize() int

PageSize returns the page size.

func (*ResourceIterator) Previous added in v0.104.0

func (it *ResourceIterator) Previous() (RecordSet, error)

Previous moves to the previous page and returns the records and any error.

func (*ResourceIterator) Reset added in v0.104.0

func (it *ResourceIterator) Reset() (RecordSet, error)

Reset resets the iterator to the first page and returns the first page records.

func (*ResourceIterator) String added in v0.104.0

func (it *ResourceIterator) String() string

String returns a formatted string representation of the iterator state.

type ResourceOps

type ResourceOps int

ResourceOps is a bitmask representing which CRUD operations are supported by a given resource (Create, Read, Update, Delete).

const (
	C ResourceOps = 1 << iota // Create permission
	L                         // Read (List) permissions
	R                         // Read (<entry>/<id>) permission
	U                         // Update permission
	D                         // Delete permission
)

func GetCRUDHintsFromResource added in v0.104.0

func GetCRUDHintsFromResource(resource any) ResourceOps

GetCRUDHintsFromResource is a helper function to extract CRUD operation hints from a resource. This is useful for introspection and tooling purposes (e.g., auto-generating widgets).

Example:

hints := core.GetCRUDHintsFromResource(rest.Users)
canCreate := hints & core.C != 0
canList := hints & core.L != 0

func NewResourceOps

func NewResourceOps(flags ...ResourceOps) ResourceOps

NewResourceOps creates a new bitmask from the provided flags. Example: NewResourceOps(R, U) -> Read+Update.

func (ResourceOps) String

func (ops ResourceOps) String() string

String returns a compact string representation of the active flags. Example: "CLRU", "LR", "CD", or "-" if no flags are set.

type TaskWaiter added in v0.107.0

type TaskWaiter interface {
	WaitTaskWithContext(ctx context.Context, taskId int64, timeout time.Duration) (Record, error)
	WaitTask(taskId int64, timeout time.Duration) (Record, error)
}

TaskWaiter defines an interface for resources that can wait on asynchronous tasks. This interface is primarily implemented by the VTask resource to provide task polling capabilities. It allows the core package to call task waiting functionality without creating a circular dependency with the untyped package.

type TooManyRecordsError

type TooManyRecordsError struct {
	ResourcePath string
	Params       Params
}

func (*TooManyRecordsError) Error

func (e *TooManyRecordsError) Error() string

Implement the Error method to satisfy the error interface

type TypedVastResource

type TypedVastResource struct {
	Untyped VastRest
	// contains filtered or unexported fields
}

func NewTypedVastResource

func NewTypedVastResource(resourceType string, rest VastRest) *TypedVastResource

func (*TypedVastResource) GetIterator added in v0.104.0

func (e *TypedVastResource) GetIterator(params Params, pageSize int) Iterator

GetIterator creates a new iterator for paginated results using the bound REST context.

func (*TypedVastResource) GetIteratorWithContext added in v0.104.0

func (e *TypedVastResource) GetIteratorWithContext(ctx context.Context, params Params, pageSize int) Iterator

GetIteratorWithContext creates a new iterator for paginated results using the provided context.

func (*TypedVastResource) GetResourceType

func (e *TypedVastResource) GetResourceType() string

func (*TypedVastResource) Lock

func (e *TypedVastResource) Lock(keys ...any) func()

Lock acquires the resource-level mutex and returns a function to release it. This allows for convenient deferring of unlock operations:

defer resource.Lock()()

func (*TypedVastResource) Session

func (e *TypedVastResource) Session() RESTSession

Session returns the current VMSSession associated with the resource.

func (*TypedVastResource) String added in v0.102.0

func (e *TypedVastResource) String() string

type VMSConfig

type VMSConfig struct {
	Host           string         // The hostname or IP address of the VMS API server.
	Port           uint64         // The port to connect to on the VMS API server.
	Username       string         // The username for authentication (used with Password).
	Password       string         // The password for authentication (used with Username).
	ApiToken       string         // Optional API token for authentication (alternative to Username/Password).
	UseBasicAuth   bool           // If true, use HTTP Basic Authentication instead of JWT (requires Username/Password).
	Tenant         string         // Optional tenant name for tenant scoped authentication (tenant admin).
	SslVerify      bool           // Whether to verify SSL certificates.
	RespectProxy   bool           // Whether to respect proxy environment variables (HTTP_PROXY, HTTPS_PROXY, NO_PROXY).
	Timeout        *time.Duration // HTTP client timeout. If nil, a default is applied by validators.
	MaxConnections int            // Maximum number of concurrent HTTP connections.
	UserAgent      string         // Optional custom User-Agent header to use in HTTP requests. If empty, a default may be applied.
	ApiVersion     string         // Optional API version
	PageSize       int            // Default page size for iterators
	// Context is an optional external context for controlling HTTP request lifecycle.
	// When provided, it will be used as the parent context for all HTTP requests made by the client.
	Context context.Context

	// BeforeRequestFn is an optional function hook executed before an API request is sent.
	// It allows for request inspection, mutation, or logging.
	//
	// Parameters:
	//   - ctx: The request context for managing deadlines and cancellations.
	//   - req: Request object
	//   - verb: The HTTP method (e.g., GET, POST, PUT).
	//   - url: The target URL (path and query parameters).
	//   - body: The request body reader, typically containing JSON payload.
	//
	// Return:
	//   - error: Any error returned will abort the request.
	BeforeRequestFn func(ctx context.Context, r *http.Request, verb, url string, body io.Reader) error

	// AfterRequestFn is an optional function hook executed after receiving an API response.
	// It can be used for post-processing, transformation, or logging of the response.
	//
	// Parameters:
	//   - ctx: The request context for managing deadlines and cancellations.
	//   - response: A Renderable result such as Record or RecordSet.
	//
	// Returns:
	//   - A potentially modified Renderable object.
	//   - An error, if processing the response fails.
	AfterRequestFn func(ctx context.Context, response Renderable) (Renderable, error)

	// FillFn optionally overrides the default function used to populate structs
	// from generic Record maps. If provided, this function is invoked instead of
	// the default JSON-based marshal/unmarshal logic.
	//
	// This is useful for customizing how API responses are decoded into typed
	// structures — for example, using a different decoding library or adding hooks.
	//
	// Parameters:
	//   - r: The Record to fill from (typically parsed from JSON response).
	//   - container: A pointer to a struct to be populated.
	//
	// Returns:
	//   - error: Any decoding or validation error encountered during population.
	FillFn func(r Record, container any) error
}

VMSConfig represents the configuration required to create a VMS session.

func (*VMSConfig) Validate

func (config *VMSConfig) Validate(validators ...VMSConfigFunc)

Validate applies the given VMSConfigFunc validators to the config. Panics if any validator returns an error.

type VMSConfigFunc

type VMSConfigFunc func(*VMSConfig) error

VMSConfigFunc defines a function that can modify or validate a VMSConfig.

func WithApiVersion

func WithApiVersion(defaultVer string) VMSConfigFunc

WithApiVersion sets a default API version NOTE: API version can be overwritten for particular VastResource

func WithMaxConnections

func WithMaxConnections(maxConnections int) VMSConfigFunc

WithMaxConnections returns a VMSConfigFunc that sets the maximum number of connections if not explicitly provided.

func WithPort

func WithPort(defaultPort uint64) VMSConfigFunc

WithPort returns a VMSConfigFunc that sets a default port if none is provided.

func WithTimeout

func WithTimeout(timeout time.Duration) VMSConfigFunc

WithTimeout returns a VMSConfigFunc that sets a default timeout if none is provided.

type VMSSession

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

func NewVMSSession

func NewVMSSession(config *VMSConfig) (*VMSSession, error)

func (*VMSSession) Delete

func (s *VMSSession) Delete(ctx context.Context, url string, body Params, headers []http.Header) (Renderable, error)

func (*VMSSession) Get

func (s *VMSSession) Get(ctx context.Context, url string, _ Params, headers []http.Header) (Renderable, error)

func (*VMSSession) GetAuthenticator

func (s *VMSSession) GetAuthenticator() Authenticator

func (*VMSSession) GetConfig

func (s *VMSSession) GetConfig() *VMSConfig

func (*VMSSession) Patch

func (s *VMSSession) Patch(ctx context.Context, url string, body Params, headers []http.Header) (Renderable, error)

func (*VMSSession) Post

func (s *VMSSession) Post(ctx context.Context, url string, body Params, headers []http.Header) (Renderable, error)

func (*VMSSession) Put

func (s *VMSSession) Put(ctx context.Context, url string, body Params, headers []http.Header) (Renderable, error)

type VMSSessionMethod

type VMSSessionMethod func(context.Context, string, Params, []http.Header) (Renderable, error)

type VastResource

type VastResource struct {
	Rest VastRest
	// contains filtered or unexported fields
}

VastResource implements VastResourceAPI and provides common behavior for managing VAST resources.

func NewVastResource

func NewVastResource(resourcePath string, resourceType string, rest VastRest, resourceOps ResourceOps, parent any) *VastResource

func (*VastResource) AfterRequest

func (e *VastResource) AfterRequest(_ context.Context, response Renderable) (Renderable, error)

AfterRequest No op in current implementation. You have to shadow this method on particular VastResource IOW declare the same method with the same signature for Users or Quotas or Views etc.

func (*VastResource) BeforeRequest

func (e *VastResource) BeforeRequest(_ context.Context, r *http.Request, verb, url string, body io.Reader) error

BeforeRequest No op in current implementation. You have to shadow this method on particular VastResource IOW declare the same method with the same signature for Users or Quotas or Views etc.

func (*VastResource) Create

func (e *VastResource) Create(params Params) (Record, error)

Create creates a new resource using the provided parameters and the bound REST context.

func (*VastResource) CreateWithContext

func (e *VastResource) CreateWithContext(ctx context.Context, body Params) (Record, error)

CreateWithContext creates a new resource using the provided parameters and context.

func (*VastResource) Delete

func (e *VastResource) Delete(searchParams, deleteParams Params) (Record, error)

Delete deletes a resource found with searchParams using deleteParams and the bound REST context. Returns success even if the resource is not found.

func (*VastResource) DeleteById

func (e *VastResource) DeleteById(id any, queryParams, deleteParams Params) (Record, error)

DeleteById deletes a resource by its ID using the bound REST context and provided deleteParams.

func (*VastResource) DeleteByIdWithContext

func (e *VastResource) DeleteByIdWithContext(ctx context.Context, id any, queryParams, deleteParams Params) (Record, error)

DeleteByIdWithContext deletes a resource by its unique ID using the provided context and delete parameters.

func (*VastResource) DeleteWithContext

func (e *VastResource) DeleteWithContext(ctx context.Context, searchParams, queryParams, deleteParams Params) (Record, error)

DeleteWithContext deletes a resource found using searchParams, using the provided deleteParams, within the given context. If the resource is not found, it returns success without error.

func (*VastResource) Ensure

func (e *VastResource) Ensure(searchParams, body Params) (Record, error)

Ensure ensures a resource exists matching the searchParams. Creates it with body if not found. Uses the bound REST context.

func (*VastResource) EnsureWithContext

func (e *VastResource) EnsureWithContext(ctx context.Context, searchParams Params, body Params) (Record, error)

EnsureWithContext ensures a resource matching the search parameters exists. If not, it creates it using the body. All operations are performed within the given context. Note: This method calls GetWithContext (requires R) and CreateWithContext (requires C) internally, which will validate permissions automatically.

func (*VastResource) Exists

func (e *VastResource) Exists(params Params) (bool, error)

Exists checks if any resource matches the given parameters using the bound REST context. Returns true if a match is found, false if not. Returns error only for unexpected issues.

func (*VastResource) ExistsWithContext

func (e *VastResource) ExistsWithContext(ctx context.Context, params Params) (bool, error)

ExistsWithContext checks if any resource matches the provided parameters within the given context. Returns true if a match is found. Returns false if not found. Returns an error only if an unexpected failure occurs.

func (*VastResource) Get

func (e *VastResource) Get(params Params) (Record, error)

Get retrieves a single resource matching the given parameters using the bound REST context. Returns NotFoundError if the resource does not exist.

func (*VastResource) GetById

func (e *VastResource) GetById(id any) (Record, error)

GetById retrieves a resource by its ID using the bound REST context.

func (*VastResource) GetByIdWithContext

func (e *VastResource) GetByIdWithContext(ctx context.Context, id any) (Record, error)

GetByIdWithContext retrieves a resource by its unique ID using the provided context.

Not all VAST resources have strictly numeric IDs; some may use UUIDs, names, or other formats. Therefore, this method accepts a generic 'id' parameter and dynamically formats the request path to handle both numeric and non-numeric identifiers.

func (*VastResource) GetIterator added in v0.104.0

func (e *VastResource) GetIterator(params Params, pageSize int) Iterator

GetIterator creates a new iterator for paginated results using the bound REST context.

Parameters:

  • params: Query parameters to filter results
  • pageSize: Number of items per page (if <= 0, uses session's configured PageSize; 0 means no page_size param)

Returns an Iterator that can be used to navigate through pages of results.

Example usage:

iter := resource.GetIterator(Params{"tenant_id": 1}, 25)
for {
    records, err := iter.Next()
    if err != nil || len(records) == 0 {
        break
    }
    fmt.Printf("Page has %d records\n", len(records))
}

func (*VastResource) GetIteratorWithContext added in v0.104.0

func (e *VastResource) GetIteratorWithContext(ctx context.Context, params Params, pageSize int) Iterator

GetIteratorWithContext creates a new iterator for paginated results using the provided context. The iterator abstracts away the differences between paginated and non-paginated API responses.

Parameters:

  • ctx: The context for the iterator (used for all subsequent requests)
  • params: Query parameters to filter results
  • pageSize: Number of items per page (if <= 0, uses session's configured PageSize)

Returns an Iterator that can be used to navigate through pages of results.

Example usage:

iter := resource.GetIteratorWithContext(ctx, Params{"name__contains": "test"}, 50)
for {
    records, err := iter.Next()
    if err != nil || len(records) == 0 {
        break
    }
    // Process records
}

func (*VastResource) GetResourcePath

func (e *VastResource) GetResourcePath() string

func (*VastResource) GetResourceType

func (e *VastResource) GetResourceType() string

func (*VastResource) GetWithContext

func (e *VastResource) GetWithContext(ctx context.Context, params Params) (Record, error)

GetWithContext retrieves a single resource that matches the given parameters using the provided context. Returns a NotFoundError if no resource is found.

func (*VastResource) List

func (e *VastResource) List(params Params) (RecordSet, error)

List retrieves all resources matching the given parameters using the bound REST context.

func (*VastResource) ListWithContext

func (e *VastResource) ListWithContext(ctx context.Context, params Params) (RecordSet, error)

ListWithContext retrieves all resources matching the given parameters using the provided context. This method uses GetIteratorWithContext internally and fetches all pages.

func (*VastResource) Lock

func (e *VastResource) Lock(keys ...any) func()

Lock acquires the resource-level mutex and returns a function to release it. This allows for convenient deferring of unlock operations:

defer resource.Lock()()

func (*VastResource) MustExists

func (e *VastResource) MustExists(params Params) bool

MustExists performs an existence check for a resource using the given parameters. It returns true if the resource exists, or false if it does not. If an error occurs during the check (other than not-found), the method panics. This is a convenience method intended for use in control paths where failures are not expected or tolerated.

func (*VastResource) MustExistsWithContext

func (e *VastResource) MustExistsWithContext(ctx context.Context, params Params) bool

MustExistsWithContext checks if a resource exists using the provided context and parameters. It returns true if the resource exists, and false otherwise. This method panics if an unexpected error occurs during the check. It is intended for use in scenarios where failure to access the resource is considered fatal.

func (*VastResource) Session

func (e *VastResource) Session() RESTSession

Session returns the current VMSSession associated with the resource.

func (*VastResource) String added in v0.102.0

func (e *VastResource) String() string

func (*VastResource) Update

func (e *VastResource) Update(id any, params Params) (Record, error)

Update updates a resource by its ID using the provided parameters and the bound REST context.

func (*VastResource) UpdateWithContext

func (e *VastResource) UpdateWithContext(ctx context.Context, id any, body Params) (Record, error)

UpdateWithContext updates an existing resource by its ID using the provided parameters and context.

type VastResourceAPI

type VastResourceAPI interface {
	Session() RESTSession
	GetResourceType() string
	GetResourcePath() string // normalized path to the resource in OpenAPI format

	List(Params) (RecordSet, error)
	Create(Params) (Record, error)
	Update(any, Params) (Record, error)
	Delete(Params, Params) (Record, error)
	DeleteById(any, Params, Params) (Record, error)
	Ensure(Params, Params) (Record, error)
	Get(Params) (Record, error)
	GetById(any) (Record, error)
	Exists(Params) (bool, error)
	MustExists(Params) bool
	GetIterator(Params, int) Iterator
	// Resource-level mutex lock for concurrent access control
	Lock(...any) func()
}

VastResourceAPI defines the interface for standard CRUD operations on a VAST resource.

type VastResourceAPIWithContext

type VastResourceAPIWithContext interface {
	VastResourceAPI
	ListWithContext(context.Context, Params) (RecordSet, error)
	CreateWithContext(context.Context, Params) (Record, error)
	UpdateWithContext(context.Context, any, Params) (Record, error)
	DeleteWithContext(context.Context, Params, Params, Params) (Record, error)
	DeleteByIdWithContext(context.Context, any, Params, Params) (Record, error)
	EnsureWithContext(context.Context, Params, Params) (Record, error)
	GetWithContext(context.Context, Params) (Record, error)
	GetByIdWithContext(context.Context, any) (Record, error)
	ExistsWithContext(context.Context, Params) (bool, error)
	MustExistsWithContext(context.Context, Params) bool
	GetIteratorWithContext(context.Context, Params, int) Iterator
}

type VastRest

type VastRest interface {
	GetSession() RESTSession
	GetResourceMap() map[string]VastResourceAPIWithContext
	GetCtx() context.Context
	SetCtx(context.Context)
}

type WaitAPIConditionConfig added in v0.110.0

type WaitAPIConditionConfig struct {
	Timeout       time.Duration // Maximum total wait time
	Interval      time.Duration // Current/initial polling interval (mutated by NextInterval)
	MaxInterval   time.Duration // Cap for exponential backoff
	BackoffFactor float64       // Rate of interval increase (0.25 = 25% per iteration)
}

WaitAPIConditionConfig defines retry/backoff parameters for polling operations.

This configuration controls how WaitAPICondition polls an API endpoint, including timeout, polling intervals, and exponential backoff behavior.

Fields:

  • Timeout: Maximum duration to wait before giving up (default: 10 minutes)
  • Interval: Initial polling interval between API calls (default: 500ms)
  • MaxInterval: Maximum polling interval after backoff (default: 30 seconds)
  • BackoffFactor: Multiplier for exponential backoff (default: 0.25 = 25% increase per iteration)

Example with custom configuration:

cfg := &WaitAPIConditionConfig{
    Timeout:       5 * time.Minute,
    Interval:      1 * time.Second,
    MaxInterval:   10 * time.Second,
    BackoffFactor: 0.5,  // 50% increase per iteration
}

Zero values will be replaced with defaults by the normalize() method.

func (*WaitAPIConditionConfig) NextInterval added in v0.110.0

func (c *WaitAPIConditionConfig) NextInterval() time.Duration

NextInterval returns the current interval and updates the internal state for the next iteration.

This method implements exponential backoff by:

  1. Returning the current interval value (for immediate use)
  2. Calculating the next interval as: current * (1.0 + BackoffFactor)
  3. Capping the next interval at MaxInterval
  4. Updating c.Interval for the next call

Example progression with Interval=500ms, BackoffFactor=0.25, MaxInterval=30s:

  • 1st call: returns 500ms, sets next to 625ms (500 * 1.25)
  • 2nd call: returns 625ms, sets next to 781ms (625 * 1.25)
  • 3rd call: returns 781ms, sets next to 976ms (781 * 1.25)
  • ...continues until reaching MaxInterval (30s)

WARNING: This method mutates the config's Interval field. Do not reuse the same config instance for multiple concurrent polling operations.

Jump to

Keyboard shortcuts

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