intelligencecloud

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Apr 14, 2026 License: MIT Imports: 20 Imported by: 0

README

intelligence-cloud-go

Go CI Go Reference

Go SDK and CLI (icctl) for the Intelligence Cloud HTTP API.

The SDK is an idiomatic Go client with typed errors, automatic retry with exponential backoff, streaming pagination, and opt-in OpenTelemetry tracing. The CLI wraps the SDK with human-readable table output, JSON mode for scripting, OS-keychain credential storage, and a Pulumi-style confirmation prompt for destructive operations.

Install

go get github.com/tresic-cloud/intelligence-cloud-go@latest

SDK quickstart

package main

import (
	"context"
	"errors"
	"fmt"
	"log"
	"os"
	"time"

	ic "github.com/tresic-cloud/intelligence-cloud-go"
	"github.com/tresic-cloud/intelligence-cloud-go/auth"
)

func main() {
	token := os.Getenv("IC_TOKEN")
	if token == "" {
		log.Fatal("IC_TOKEN environment variable is required")
	}

	client, err := ic.NewClient(
		"https://api.staging.intelligence.cloud",
		auth.StaticToken(token),
	)
	if err != nil {
		log.Fatalf("client: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	me, err := client.Me.Get(ctx)
	if err != nil {
		switch {
		case errors.Is(err, ic.ErrAuthentication):
			log.Fatal("token expired or invalid")
		case errors.Is(err, ic.ErrRateLimit):
			log.Fatal("rate-limited -- try again later")
		}
		log.Fatalf("me.Get: %v", err)
	}

	fmt.Printf("Hello, %s <%s>\n", me.DisplayName, me.Email)
}

Set your token and run:

export IC_TOKEN="<your bearer token>"
go run main.go

Paginated endpoints return an Iterator[T] that streams pages on demand:

it := client.Resellers.List(ctx, ic.WithPageSize(50))
defer it.Close()

for it.Next(ctx) {
	r := it.Value()
	fmt.Printf("%s\t%s\n", r.ID, r.Name)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

CLI quickstart

Download a binary from the releases page or build from source:

go install github.com/tresic-cloud/intelligence-cloud-go/cmd/icctl@latest

Create a profile (the token is read from stdin so it never appears in shell history):

icctl profile add staging --environment staging --token-stdin

Run commands:

icctl --profile staging resellers list
icctl --profile staging resellers list --output json | jq '.items[].name'

Destructive operations show a preview and require confirmation before executing. Use --yes or ICCTL_ASSUME_YES=1 to bypass in CI.

Development

Prerequisites: Go 1.25+, golangci-lint, govulncheck, staticcheck.

make help        # list all targets
make build       # compile
make test        # test with race detector + coverage
make lint        # golangci-lint
make vuln        # govulncheck
make static      # go vet + staticcheck
make codegen     # regenerate from OpenAPI spec
make bench       # benchmarks
make clean       # remove artifacts

Documentation

Contributing

Contributions are welcome. Please read the Contributing guide for dev environment setup, the conventional-commits requirement, branch naming conventions, TDD discipline, and the pull request process.

License

MIT

Documentation

Overview

Package intelligencecloud provides a typed Go client for the Intelligence Cloud API. It exposes resource services, typed errors, a configurable retry policy, and per-call/per-list options.

Quick start

client, err := intelligencecloud.NewClient(
    "https://api.intelligencecloud.example.com",
    auth.StaticToken("my-bearer-token"),
)
if err != nil {
    log.Fatal(err)
}

Client construction

NewClient is the entry point. It requires a base URL (https:// unless the host is localhost or 127.0.0.1) and an auth.CredentialProvider. Optional ClientOption values configure the HTTP client, retry policy, tracing, logging, and User-Agent header.

The returned Client is immutable after construction and safe for concurrent use by multiple goroutines.

Resource services

Each resource type (Resellers, Companies, Locations, etc.) is accessed as a field on the Client. Resource services provide CRUD and lifecycle methods that return typed responses or errors.

Error handling

API errors implement the APIError interface and wrap sentinel errors for use with errors.Is. Callers can use errors.As to access concrete error types with additional fields.

Configuration errors (returned only from NewClient) are *ConfigurationError and do NOT implement APIError.

Pagination

List methods return an Iterator[T] that lazily fetches pages. Use WithPageSize and WithMaxItems to control pagination behaviour.

Retry policy

By default the client retries transient failures (429, 5xx, transport errors) with exponential backoff and full jitter. Use WithRetryPolicy or WithDisableRetry to customise this behaviour.

Observability

Tracing is supported via OpenTelemetry. Use WithTracerProvider and WithPropagator to enable distributed tracing. Use WithLogger to enable structured logging with automatic PII redaction.

Package intelligencecloud provides the Go SDK for the Intelligence Cloud platform. This file implements the generic Iterator[T] pagination helper used by all List* methods on resource services.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrAuthentication indicates a 401 authentication failure.
	ErrAuthentication = errors.New("intelligencecloud: authentication failed")
	// ErrAuthorization indicates a 403 authorization failure.
	ErrAuthorization = errors.New("intelligencecloud: not authorized")
	// ErrValidation indicates a 400/422 validation failure.
	ErrValidation = errors.New("intelligencecloud: validation failed")
	// ErrNotFound indicates a 404 resource-not-found response.
	ErrNotFound = errors.New("intelligencecloud: resource not found")
	// ErrConflict indicates a 409 resource conflict.
	ErrConflict = errors.New("intelligencecloud: resource conflict")
	// ErrRateLimit indicates a 429 rate-limit response.
	ErrRateLimit = errors.New("intelligencecloud: rate-limited")
	// ErrServer indicates a 5xx server-side failure.
	ErrServer = errors.New("intelligencecloud: server error")
)

Sentinel errors allow callers to classify failures with errors.Is without inspecting concrete types. Every concrete error Unwraps to the corresponding sentinel.

View Source
var RedactedHeaders = []string{
	"Authorization",
	"Cookie",
	"X-Api-Key",
	"X-Token",
}

RedactedHeaders is the default set of HTTP header names whose values must never appear in spans, logs, or error payloads. Callers may extend this slice before constructing a Client.

Functions

func HTTPRequestAttrs

func HTTPRequestAttrs(method, urlTemplate, fullURL, userAgent string, bodySize int) []attribute.KeyValue

HTTPRequestAttrs returns OTel attributes for an outbound HTTP request.

func HTTPResponseAttrs

func HTTPResponseAttrs(statusCode, bodySize int, protoVersion string) []attribute.KeyValue

HTTPResponseAttrs returns OTel attributes for an HTTP response.

func RedactHeaders

func RedactHeaders(h http.Header) map[string]string

RedactHeaders returns a copy of h containing only headers that are NOT in the RedactedHeaders set. Header names are compared case-insensitively.

func RedactURL

func RedactURL(u *url.URL) string

RedactURL returns the string representation of u with the values of query parameters whose key matches the sensitive-key pattern replaced by "[REDACTED]". The URL structure (scheme, host, path) is preserved.

func SDKAttrs

func SDKAttrs(operationID, resource, requestID, sdkVersion string, retryAttempt int, retryCause string) []attribute.KeyValue

SDKAttrs returns OTel attributes for SDK-specific metadata.

func ServerAttrs

func ServerAttrs(host string, port int) []attribute.KeyValue

ServerAttrs returns OTel attributes for the target server.

func SpanName

func SpanName(operationID string) string

SpanName returns the canonical OTel span name for the given OpenAPI operationID. The result is "intelligencecloud." followed by the operationID, e.g. "intelligencecloud.GetMe".

Types

type APIError

type APIError interface {
	error
	// Status returns the HTTP status code of the failed response.
	Status() int
	// Code returns the backend-provided error code, if any.
	Code() string
	// RequestID returns the backend-provided request identifier for support
	// triage.
	RequestID() string
	// Operation returns the SDK operation name that triggered the error.
	Operation() string
}

APIError is satisfied by every non-nil error the SDK returns from an API call. Callers can use errors.As to obtain the concrete type and access additional fields such as RequiredScopes, FieldErrors, or RetryAfter.

type AuditLogEntry

type AuditLogEntry = generated.AuditLogEntry

AuditLogEntry is a single audit log entry from the Intelligence Cloud API.

type AuditLogService

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

AuditLogService provides read-only access to audit log entries. Methods are added by resource-wrapper tasks in Wave 2.

func (*AuditLogService) ListForReseller

func (s *AuditLogService) ListForReseller(ctx context.Context, resellerID string, opts ...ListOption) *Iterator[AuditLogEntry]

ListForReseller returns a paginated iterator over audit log entries for the specified reseller. Filters can be applied using WithFilter with keys: "action", "start_date", "end_date", "actor_id", "search". Use WithPageSize to control page size, and WithMaxItems to cap total results.

type AuthService

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

AuthService provides authentication-related operations such as token exchange. Methods are added by resource-wrapper tasks in Wave 2.

func (*AuthService) Login

func (s *AuthService) Login(ctx context.Context, req LoginRequest, opts ...CallOption) (*LoginResponse, error)

Login authenticates with the Intelligence Cloud API using email and password credentials. This endpoint uses security: [] in the OpenAPI spec, so NO Authorization header is sent. The method handles both OAuth-style error envelopes (error + error_description) and standard ErrorResponse envelopes.

type AuthenticationError

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

AuthenticationError represents a 401 authentication failure.

func NewAuthenticationError

func NewAuthenticationError(statusCode int, code, message, requestID, operationID string) *AuthenticationError

NewAuthenticationError constructs an AuthenticationError.

func (AuthenticationError) Code

func (b AuthenticationError) Code() string

Code returns the backend error code.

func (*AuthenticationError) Error

func (e *AuthenticationError) Error() string

Error implements the error interface.

func (AuthenticationError) Operation

func (b AuthenticationError) Operation() string

Operation returns the operation name.

func (AuthenticationError) RequestID

func (b AuthenticationError) RequestID() string

RequestID returns the request identifier.

func (AuthenticationError) Status

func (b AuthenticationError) Status() int

Status returns the HTTP status code.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type AuthorizationError

type AuthorizationError struct {

	// RequiredScopes lists the scopes the caller would need to succeed, when
	// the backend provides this information.
	RequiredScopes []string
	// contains filtered or unexported fields
}

AuthorizationError represents a 403 authorization failure.

func NewAuthorizationError

func NewAuthorizationError(statusCode int, code, message, requestID, operationID string, requiredScopes []string) *AuthorizationError

NewAuthorizationError constructs an AuthorizationError.

func (AuthorizationError) Code

func (b AuthorizationError) Code() string

Code returns the backend error code.

func (*AuthorizationError) Error

func (e *AuthorizationError) Error() string

Error implements the error interface.

func (AuthorizationError) Operation

func (b AuthorizationError) Operation() string

Operation returns the operation name.

func (AuthorizationError) RequestID

func (b AuthorizationError) RequestID() string

RequestID returns the request identifier.

func (AuthorizationError) Status

func (b AuthorizationError) Status() int

Status returns the HTTP status code.

func (*AuthorizationError) Unwrap

func (e *AuthorizationError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type AvatarConfirmRequest

type AvatarConfirmRequest = generated.AvatarConfirmRequest

AvatarConfirmRequest is the request body for MeService.ConfirmAvatar.

type AvatarResponseData

type AvatarResponseData = generated.AvatarResponseData

AvatarResponseData is the response from MeService.ConfirmAvatar.

type AvatarUploadURLRequest

type AvatarUploadURLRequest = generated.AvatarUploadURLRequest

AvatarUploadURLRequest is the request body for MeService.CreateAvatarUploadURL.

type AvatarUploadURLResponseData

type AvatarUploadURLResponseData = generated.AvatarUploadURLResponseData

AvatarUploadURLResponseData is the response from MeService.CreateAvatarUploadURL.

type CallOption

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

CallOption configures the behaviour of a single API call. Implementations apply themselves to an unexported callConfig that the transport layer reads.

func WithExtraHeader

func WithExtraHeader(name, value string) CallOption

WithExtraHeader returns a CallOption that adds an arbitrary header to the outgoing request. This is intended for future-proofing; common headers such as Authorization are managed by the SDK.

WithExtraHeader panics if name is "Authorization" (case-insensitive), because the SDK manages that header via the CredentialProvider.

func WithIdempotencyKey

func WithIdempotencyKey(key string) CallOption

WithIdempotencyKey returns a CallOption that sets the X-Idempotency-Key header on the outgoing request.

func WithRequestTimeout

func WithRequestTimeout(d time.Duration) CallOption

WithRequestTimeout returns a CallOption that applies a per-call timeout via context.WithTimeout, scoped to the individual request (not including retries).

type Client

type Client struct {

	// Me provides access to the authenticated user's profile and preferences.
	// Populated by resource-wrapper tasks in Wave 2.
	Me *MeService

	// Resellers provides CRUD and lifecycle operations for reseller resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Resellers *ResellerService

	// Companies provides CRUD and lifecycle operations for company resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Companies *CompanyService

	// Locations provides CRUD and lifecycle operations for location resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Locations *LocationService

	// Products provides CRUD and lifecycle operations for product resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Products *ProductService

	// Verticals provides CRUD and lifecycle operations for vertical resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Verticals *VerticalService

	// Connectors provides CRUD and lifecycle operations for connector resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Connectors *ConnectorService

	// AuditLogs provides read-only access to audit log entries.
	// Populated by resource-wrapper tasks in Wave 2.
	AuditLogs *AuditLogService

	// Users provides CRUD and lifecycle operations for user resources.
	// Populated by resource-wrapper tasks in Wave 2.
	Users *UserService

	// Auth provides authentication-related operations (e.g. token exchange).
	// Populated by resource-wrapper tasks in Wave 2.
	Auth *AuthService
	// contains filtered or unexported fields
}

Client is the top-level handle for the Intelligence Cloud API. It is immutable after construction and safe for concurrent use by multiple goroutines. Per-call configuration (timeouts, idempotency keys, extra headers) is supplied via CallOption or ListOption variadic parameters on each resource-service method, not by mutating the Client.

Construct a Client with NewClient; the zero value is not usable.

func NewClient

func NewClient(baseURL string, provider auth.CredentialProvider, opts ...ClientOption) (*Client, error)

NewClient constructs a Client for the Intelligence Cloud API. baseURL is the root URL of the API (must use https:// unless the host is localhost or 127.0.0.1). provider supplies bearer tokens for authentication and must not be nil. Optional ClientOption values configure HTTP client, retry policy, tracing, logging, and user-agent overrides.

NewClient returns a *ConfigurationError (which does NOT implement APIError) when inputs are invalid. The returned Client is immutable and safe for concurrent use.

type ClientOption

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

ClientOption configures the Client during construction. Implementations apply themselves to the Client's unexported fields. The interface is open so that future releases may add new options without breaking existing callers.

func WithDisableRetry

func WithDisableRetry() ClientOption

WithDisableRetry returns a ClientOption that disables automatic retries. This is equivalent to WithRetryPolicy(NoRetry()) and is provided as a convenience.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient returns a ClientOption that sets the underlying HTTP client used for all API requests. When not supplied, NewClient creates a default client with a 30-second timeout. Transport wrapping (retry, tracing, auth injection) is applied additively by the transport layer.

func WithLogger

func WithLogger(l *slog.Logger) ClientOption

WithLogger returns a ClientOption that sets the structured logger. When not supplied, the Client uses a logger backed by a discarding handler so that no log output is produced.

func WithPropagator

func WithPropagator(p propagation.TextMapPropagator) ClientOption

WithPropagator returns a ClientOption that sets the trace-context propagator. When not supplied, the Client uses a composite propagator with W3C TraceContext and Baggage.

func WithRetryPolicy

func WithRetryPolicy(p RetryPolicy) ClientOption

WithRetryPolicy returns a ClientOption that sets the retry policy. The policy is validated during NewClient construction; invalid policies cause NewClient to return a *ConfigurationError.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) ClientOption

WithTracerProvider returns a ClientOption that sets the OpenTelemetry TracerProvider for distributed tracing. When not supplied, the Client uses a no-op tracer provider that allocates nothing.

func WithUserAgent

func WithUserAgent(ua string) ClientOption

WithUserAgent returns a ClientOption that overrides the default User-Agent header value. The default format is "intelligence-cloud-go/<version> (<os>/<arch>)".

type CompanyConnector

type CompanyConnector = generated.CompanyConnectorItem

CompanyConnector is a connector scoped to a company, including its location association.

type CompanyConnectorList

type CompanyConnectorList struct {
	// Iterator provides paginated access to company connectors.
	Iterator *Iterator[CompanyConnector]

	// ErrorSummary lists all connectors in error state across the company.
	// This is populated from the first page response and represents the
	// complete set, independent of pagination.
	ErrorSummary []ConnectorErrorSummaryItem
}

CompanyConnectorList holds both the paginated connector iterator and the aggregate error summary returned by the company-scoped connectors endpoint. The ErrorSummary reflects all connectors in error state across the entire company, regardless of pagination.

type CompanyService

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

CompanyService provides CRUD and lifecycle operations for company resources. Methods are added by resource-wrapper tasks in Wave 2.

type CompanyUser

type CompanyUser = generated.CompanyUserResponseData

CompanyUser represents a user within a company.

type ConfigurationError

type ConfigurationError struct {
	// Message describes the configuration problem.
	Message string
}

ConfigurationError represents a configuration validation failure. It is returned only from option validation and client construction, never from API calls. It deliberately does NOT implement APIError.

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

Error implements the error interface.

type ConflictError

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

ConflictError represents a 409 resource conflict.

func NewConflictError

func NewConflictError(statusCode int, code, message, requestID, operationID string) *ConflictError

NewConflictError constructs a ConflictError.

func (ConflictError) Code

func (b ConflictError) Code() string

Code returns the backend error code.

func (*ConflictError) Error

func (e *ConflictError) Error() string

Error implements the error interface.

func (ConflictError) Operation

func (b ConflictError) Operation() string

Operation returns the operation name.

func (ConflictError) RequestID

func (b ConflictError) RequestID() string

RequestID returns the request identifier.

func (ConflictError) Status

func (b ConflictError) Status() int

Status returns the HTTP status code.

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type ConnectorErrorSummaryItem

type ConnectorErrorSummaryItem = generated.ConnectorErrorSummaryItem

ConnectorErrorSummaryItem is an aggregate error summary for connectors in error state across a company.

type ConnectorService

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

ConnectorService provides CRUD and lifecycle operations for connector resources. Methods are added by resource-wrapper tasks in Wave 2.

func (*ConnectorService) ListByCompany

func (s *ConnectorService) ListByCompany(ctx context.Context, companyID string, opts ...ListOption) *CompanyConnectorList

ListByCompany returns a CompanyConnectorList containing both a paginated iterator over company-scoped connectors and an aggregate error summary. The company connectors endpoint uses nested pagination (pagination.next_cursor + pagination.has_more) and carries a top-level errors array with connector-scoped aggregate diagnostics.

The first page is fetched eagerly so that ErrorSummary is available immediately without calling Iterator.Next(). If the first page fetch fails, ErrorSummary will be empty and the error will surface when Iterator.Next() is called.

Filters can be applied using WithFilter with keys: "search", "status", "type". Use WithPageSize to control page size.

func (*ConnectorService) ListByLocation

func (s *ConnectorService) ListByLocation(ctx context.Context, locationID string, opts ...ListOption) *Iterator[LocationConnector]

ListByLocation returns a paginated iterator over connectors for the specified location. Filters can be applied using WithFilter with keys: "search", "status". Use WithPageSize to control page size.

type CreateResellerRequest

type CreateResellerRequest = generated.CreateResellerRequest

CreateResellerRequest is the request body for ResellerService.Create.

type DailyRecapPreferences

type DailyRecapPreferences = generated.DailyRecapPreferences

DailyRecapPreferences holds the user's daily recap preference settings.

type DailyRecapPreferencesPatch

type DailyRecapPreferencesPatch = generated.PatchDailyRecapPreferencesRequest

DailyRecapPreferencesPatch is the request body for MeService.PatchDailyRecapPreferences (all fields optional).

type DeactivateResellerRequest

type DeactivateResellerRequest = generated.DeactivateResellerRequest

DeactivateResellerRequest is the request body for ResellerService.Deactivate. Reason is required.

type FieldError

type FieldError struct {
	// Field is the path of the invalid field (e.g. "name" or "address.zip").
	Field string
	// Code is the machine-readable validation code (e.g. "required").
	Code string
	// Message is the human-readable description of the failure.
	Message string
}

FieldError describes a single field-level validation failure as reported by the backend.

type Iterator

type Iterator[T any] struct {
	// contains filtered or unexported fields
}

Iterator provides a sequential, demand-driven traversal over paginated backend results. It fetches at most one page of items at a time, keeping memory usage bounded.

Usage:

it := client.Resellers.List(ctx, intelligencecloud.WithPageSize(50))
defer it.Close()
for it.Next(ctx) {
    r := it.Value()
    // ...
}
if err := it.Err(); err != nil {
    return err
}

func (*Iterator[T]) Close

func (it *Iterator[T]) Close()

Close releases resources held by the iterator. It is idempotent and safe to call from a deferred context. After Close, Next returns false.

func (*Iterator[T]) Err

func (it *Iterator[T]) Err() error

Err returns the error that caused Next to return false, or nil if iteration completed successfully (including when capped by maxItems).

func (*Iterator[T]) Next

func (it *Iterator[T]) Next(ctx context.Context) bool

Next advances the iterator to the next item. It returns true if an item is available via Value, or false when iteration is complete (either all items exhausted, maxItems reached, or an error occurred).

Next fetches a new page from the backend when the current page buffer is exhausted and more pages are available. The provided context controls cancellation and deadlines for the page fetch.

After Next returns false, further calls to Next return false without re-fetching.

func (*Iterator[T]) PageInfo

func (it *Iterator[T]) PageInfo() PageInfo

PageInfo returns a snapshot of the current pagination state.

func (*Iterator[T]) Value

func (it *Iterator[T]) Value() T

Value returns the current item. It is undefined before the first call to Next returns true. After Next returns false, Value returns the last successfully yielded item (or the zero value if no items were yielded).

type JitterStrategy

type JitterStrategy int

JitterStrategy controls how jitter is applied to retry backoff delays.

const (
	// NoJitter applies no jitter; the backoff delay is used exactly.
	NoJitter JitterStrategy = iota
	// EqualJitter applies jitter of up to half the computed delay.
	EqualJitter
	// FullJitter applies jitter across the full range [0, delay).
	FullJitter
)

type ListOption

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

ListOption configures the behaviour of a paginated list call. Implementations apply themselves to an unexported listConfig that the iterator reads.

func WithFilter

func WithFilter(key, value string) ListOption

WithFilter returns a ListOption that adds a backend-defined filter parameter to the list request.

func WithMaxItems

func WithMaxItems(n int) ListOption

WithMaxItems returns a ListOption that sets a hard cap on the number of items the iterator will return. n must be >= 0; 0 means unlimited.

WithMaxItems panics if n < 0.

func WithPageSize

func WithPageSize(n int) ListOption

WithPageSize returns a ListOption that hints the backend's page size (page_size query parameter). n must be > 0.

WithPageSize panics if n <= 0.

type LocationConnector

type LocationConnector = generated.LocationConnectorItem

LocationConnector is a connector scoped to a single location.

type LocationService

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

LocationService provides CRUD and lifecycle operations for location resources. Methods are added by resource-wrapper tasks in Wave 2.

type LoginRequest

type LoginRequest = generated.LoginRequest

LoginRequest contains the credentials for authenticating with the Intelligence Cloud API.

type LoginResponse

type LoginResponse = generated.LoginResponse

LoginResponse contains the tokens and user profile returned on successful authentication.

type MeService

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

MeService provides access to the authenticated user's profile and notification preferences. Methods are added by resource-wrapper tasks in Wave 2.

func (*MeService) ConfirmAvatar

func (s *MeService) ConfirmAvatar(ctx context.Context, req AvatarConfirmRequest, opts ...CallOption) (*AvatarResponseData, error)

ConfirmAvatar confirms a previously generated avatar upload by storing the asset URL on the user profile.

func (*MeService) CreateAvatarUploadURL

func (s *MeService) CreateAvatarUploadURL(ctx context.Context, req AvatarUploadURLRequest, opts ...CallOption) (*AvatarUploadURLResponseData, error)

CreateAvatarUploadURL generates a pre-signed upload URL for a profile photo. After uploading the image to the returned URL, call ConfirmAvatar to store the asset on the profile.

func (*MeService) DeleteAvatar

func (s *MeService) DeleteAvatar(ctx context.Context, opts ...CallOption) error

DeleteAvatar removes the authenticated user's profile photo.

func (*MeService) Get

func (s *MeService) Get(ctx context.Context, opts ...CallOption) (*UserProfile, error)

Get retrieves the authenticated user's profile.

func (*MeService) GetDailyRecapPreferences

func (s *MeService) GetDailyRecapPreferences(ctx context.Context, opts ...CallOption) (*DailyRecapPreferences, error)

GetDailyRecapPreferences retrieves the authenticated user's daily recap preference settings.

func (*MeService) GetNotificationPreferences

func (s *MeService) GetNotificationPreferences(ctx context.Context, opts ...CallOption) (*NotificationPreferences, error)

GetNotificationPreferences retrieves the authenticated user's notification preference settings.

func (*MeService) PatchDailyRecapPreferences

func (s *MeService) PatchDailyRecapPreferences(ctx context.Context, req DailyRecapPreferencesPatch, opts ...CallOption) (*DailyRecapPreferences, error)

PatchDailyRecapPreferences partially updates the authenticated user's daily recap preferences. Only the fields present in req are modified.

func (*MeService) PatchNotificationPreferences

func (s *MeService) PatchNotificationPreferences(ctx context.Context, req NotificationPreferencesPatch, opts ...CallOption) (*NotificationPreferences, error)

PatchNotificationPreferences partially updates the authenticated user's notification preferences. Only the fields present in req are modified.

type NotFoundError

type NotFoundError struct {

	// ResourceType identifies the kind of resource that was not found.
	ResourceType string
	// ResourceID identifies the specific resource that was not found.
	ResourceID string
	// contains filtered or unexported fields
}

NotFoundError represents a 404 resource-not-found response.

func NewNotFoundError

func NewNotFoundError(statusCode int, code, message, requestID, operationID, resourceType, resourceID string) *NotFoundError

NewNotFoundError constructs a NotFoundError.

func (NotFoundError) Code

func (b NotFoundError) Code() string

Code returns the backend error code.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error implements the error interface.

func (NotFoundError) Operation

func (b NotFoundError) Operation() string

Operation returns the operation name.

func (NotFoundError) RequestID

func (b NotFoundError) RequestID() string

RequestID returns the request identifier.

func (NotFoundError) Status

func (b NotFoundError) Status() int

Status returns the HTTP status code.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type NotificationPreferences

type NotificationPreferences = generated.NotificationPreferences

NotificationPreferences holds the user's notification preference settings.

type NotificationPreferencesPatch

type NotificationPreferencesPatch = generated.PatchNotificationPreferencesRequest

NotificationPreferencesPatch is the request body for MeService.PatchNotificationPreferences (all fields optional).

type PageInfo

type PageInfo struct {
	// ItemsFetched is the total number of items returned across all pages
	// consumed so far.
	ItemsFetched int

	// PagesFetched is the total number of backend page-fetch calls that
	// have completed so far.
	PagesFetched int

	// HasNextPage is true when the backend indicated that more results are
	// available beyond the most-recently fetched page.
	HasNextPage bool

	// NextPageToken is the opaque token that would be sent to the backend
	// to retrieve the next page. It is empty when HasNextPage is false.
	NextPageToken string
}

PageInfo holds metadata about the pagination state of an Iterator.

type PatchResellerRequest

type PatchResellerRequest = generated.PatchResellerRequest

PatchResellerRequest is the request body for ResellerService.Patch (partial update via PATCH; all fields optional).

type Product

type Product = generated.Product

Product represents a product in the Intelligence Cloud catalogue.

type ProductService

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

ProductService provides CRUD and lifecycle operations for product resources. Methods are added by resource-wrapper tasks in Wave 2.

func (*ProductService) List

func (s *ProductService) List(ctx context.Context, opts ...CallOption) ([]Product, error)

List retrieves all products from the Intelligence Cloud API. The /api/v1/products endpoint returns all products in a single response (no pagination). Error mapping covers 401 (AuthenticationError) and 403 (AuthorizationError).

type RateLimitError

type RateLimitError struct {

	// RetryAfter is the server-suggested delay before retrying.
	RetryAfter time.Duration
	// contains filtered or unexported fields
}

RateLimitError represents a 429 rate-limit response. RetryAfter carries the Retry-After hint from the server, if present.

func NewRateLimitError

func NewRateLimitError(statusCode int, code, message, requestID, operationID string, retryAfter time.Duration) *RateLimitError

NewRateLimitError constructs a RateLimitError.

func (RateLimitError) Code

func (b RateLimitError) Code() string

Code returns the backend error code.

func (*RateLimitError) Error

func (e *RateLimitError) Error() string

Error implements the error interface.

func (RateLimitError) Operation

func (b RateLimitError) Operation() string

Operation returns the operation name.

func (RateLimitError) RequestID

func (b RateLimitError) RequestID() string

RequestID returns the request identifier.

func (RateLimitError) Status

func (b RateLimitError) Status() int

Status returns the HTTP status code.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type RedactingHandler

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

RedactingHandler is an slog.Handler wrapper that:

  • Strips any attribute whose key matches the sensitive-key pattern (token, secret, key, password — case-insensitive substring match).
  • Injects trace_id and span_id attributes when a span is active in the context.
  • Delegates all other behaviour to the underlying handler.

func NewRedactingHandler

func NewRedactingHandler(inner slog.Handler) *RedactingHandler

NewRedactingHandler wraps inner with sensitive-attribute stripping and trace-context injection.

func (*RedactingHandler) Enabled

func (h *RedactingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled delegates to the inner handler.

func (*RedactingHandler) Handle

func (h *RedactingHandler) Handle(ctx context.Context, r slog.Record) error

Handle filters sensitive attributes and injects trace context before delegating to the inner handler.

func (*RedactingHandler) WithAttrs

func (h *RedactingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new handler with the given pre-filtered attributes.

func (*RedactingHandler) WithGroup

func (h *RedactingHandler) WithGroup(name string) slog.Handler

WithGroup returns a new handler with the given group name.

type Reseller

type Reseller = generated.Reseller

Reseller represents a reseller account in the Intelligence Cloud platform.

type ResellerService

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

ResellerService provides CRUD and lifecycle operations for reseller resources. Methods are added by resource-wrapper tasks in Wave 2.

func (*ResellerService) Create

Create creates a new reseller account.

func (*ResellerService) Deactivate

func (s *ResellerService) Deactivate(ctx context.Context, id string, req DeactivateResellerRequest, opts ...CallOption) (*Reseller, error)

Deactivate deactivates a reseller. The reason field in req is required for audit purposes.

func (*ResellerService) Get

func (s *ResellerService) Get(ctx context.Context, id string, opts ...CallOption) (*Reseller, error)

Get retrieves a single reseller by ID.

func (*ResellerService) List

func (s *ResellerService) List(ctx context.Context, opts ...ListOption) *Iterator[Reseller]

List returns a paginated iterator over all resellers. Use ListOption values such as WithPageSize and WithFilter to control pagination and server-side filtering.

func (*ResellerService) ListAuditLogs

func (s *ResellerService) ListAuditLogs(ctx context.Context, resellerID string, opts ...ListOption) *Iterator[AuditLogEntry]

ListAuditLogs returns a paginated iterator over audit log entries for the given reseller. Use ListOption values such as WithPageSize and WithFilter to control pagination and server-side filtering.

func (*ResellerService) Patch

func (s *ResellerService) Patch(ctx context.Context, id string, req PatchResellerRequest, opts ...CallOption) (*Reseller, error)

Patch performs a partial update of a reseller's fields (PATCH).

func (*ResellerService) Reactivate

func (s *ResellerService) Reactivate(ctx context.Context, id string, opts ...CallOption) (*Reseller, error)

Reactivate reactivates a previously deactivated reseller.

func (*ResellerService) Update

func (s *ResellerService) Update(ctx context.Context, id string, req UpdateResellerRequest, opts ...CallOption) (*Reseller, error)

Update performs a full replacement of a reseller's fields (PUT).

type RetryPolicy

type RetryPolicy struct {
	// Enabled controls whether retries are attempted at all.
	Enabled bool
	// MaxAttempts is the total number of attempts (1 initial + N-1 retries).
	// Must be >= 1.
	MaxAttempts int
	// BaseDelay is the initial backoff delay before the first retry. Must be
	// > 0.
	BaseDelay time.Duration
	// MaxDelay caps the computed backoff delay for any single retry. Must be
	// >= BaseDelay.
	MaxDelay time.Duration
	// Jitter selects the jitter strategy applied to the backoff delay.
	Jitter JitterStrategy
	// RetryableStatus lists the HTTP status codes that are eligible for retry.
	RetryableStatus []int
	// HonourRetryAfter controls whether the SDK respects Retry-After headers
	// from 429 responses, overriding the computed backoff for that attempt.
	HonourRetryAfter bool
}

RetryPolicy controls how the SDK retries transient failures. The zero value is not usable; use DefaultRetryPolicy or NoRetry to obtain a valid policy. The retry execution loop lives in internal/transport; this file defines only the policy struct, factories, and validation.

func DefaultRetryPolicy

func DefaultRetryPolicy() RetryPolicy

DefaultRetryPolicy returns the recommended retry policy for production use. It enables retries with 4 total attempts (1 initial + 3 retries), 100 ms base delay, 30 s maximum delay, full jitter, and honours Retry-After headers on 429 responses.

func NoRetry

func NoRetry() RetryPolicy

NoRetry returns a policy that disables all retries.

func (RetryPolicy) Validate

func (p RetryPolicy) Validate() error

Validate checks that the policy fields are internally consistent. It returns a *ConfigurationError if any rule is violated. Validation rules apply regardless of the Enabled flag so that a disabled policy can be re-enabled safely.

type ServerError

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

ServerError represents a 5xx server-side failure.

func NewServerError

func NewServerError(statusCode int, code, message, requestID, operationID string) *ServerError

NewServerError constructs a ServerError.

func (ServerError) Code

func (b ServerError) Code() string

Code returns the backend error code.

func (*ServerError) Error

func (e *ServerError) Error() string

Error implements the error interface.

func (ServerError) Operation

func (b ServerError) Operation() string

Operation returns the operation name.

func (ServerError) RequestID

func (b ServerError) RequestID() string

RequestID returns the request identifier.

func (ServerError) Status

func (b ServerError) Status() int

Status returns the HTTP status code.

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type UnexpectedError

type UnexpectedError struct {

	// CauseBody is the raw response body, capped at 4 KiB.
	CauseBody []byte
	// contains filtered or unexported fields
}

UnexpectedError represents an error response that does not map to any known sentinel. CauseBody is capped at 4 KiB for safety. Use NewUnexpectedError to construct instances; it enforces the size cap.

func NewUnexpectedError

func NewUnexpectedError(statusCode int, code, message, requestID, operationID string, causeBody []byte) *UnexpectedError

NewUnexpectedError constructs an UnexpectedError, capping causeBody at 4 KiB.

func (UnexpectedError) Code

func (b UnexpectedError) Code() string

Code returns the backend error code.

func (*UnexpectedError) Error

func (e *UnexpectedError) Error() string

Error implements the error interface.

func (UnexpectedError) Operation

func (b UnexpectedError) Operation() string

Operation returns the operation name.

func (UnexpectedError) RequestID

func (b UnexpectedError) RequestID() string

RequestID returns the request identifier.

func (UnexpectedError) Status

func (b UnexpectedError) Status() int

Status returns the HTTP status code.

type UpdateCompanyUserRequest

type UpdateCompanyUserRequest = generated.UpdateCompanyUserRequest

UpdateCompanyUserRequest is the request body for patching a company user.

type UpdateResellerRequest

type UpdateResellerRequest = generated.UpdateResellerRequest

UpdateResellerRequest is the request body for ResellerService.Update (full replacement via PUT).

type UserProfile

type UserProfile = generated.UserProfile

UserProfile is the authenticated user's profile returned by MeService.Get.

type UserService

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

UserService provides CRUD and lifecycle operations for user resources. Methods are added by resource-wrapper tasks in Wave 2.

func (*UserService) PatchCompany

func (s *UserService) PatchCompany(ctx context.Context, companyID, userID string, req UpdateCompanyUserRequest, opts ...CallOption) (*CompanyUser, error)

PatchCompany updates a user within a company. It sends a PATCH request to /api/v1/companies/{companyId}/users/{userId}. Error mapping covers 400 (ValidationError), 401 (AuthenticationError), 403 (AuthorizationError), and 404 (NotFoundError).

Both companyID and userID must be non-empty; a ValidationError is returned if either is blank.

type ValidationError

type ValidationError struct {

	// FieldErrors lists the individual field-level validation failures.
	FieldErrors []FieldError
	// contains filtered or unexported fields
}

ValidationError represents a 400 or 422 validation failure. It carries field-level details when the backend provides them.

func NewValidationError

func NewValidationError(statusCode int, code, message, requestID, operationID string, fieldErrors []FieldError) *ValidationError

NewValidationError constructs a ValidationError.

func (ValidationError) Code

func (b ValidationError) Code() string

Code returns the backend error code.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (ValidationError) Operation

func (b ValidationError) Operation() string

Operation returns the operation name.

func (ValidationError) RequestID

func (b ValidationError) RequestID() string

RequestID returns the request identifier.

func (ValidationError) Status

func (b ValidationError) Status() int

Status returns the HTTP status code.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the sentinel so that errors.Is works.

type VerticalService

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

VerticalService provides CRUD and lifecycle operations for vertical resources. Methods are added by resource-wrapper tasks in Wave 2.

Directories

Path Synopsis
Package auth defines the credential-provider model for the Intelligence Cloud Go SDK.
Package auth defines the credential-provider model for the Intelligence Cloud Go SDK.
cmd
icctl command
Package main is the entry point for the icctl CLI binary.
Package main is the entry point for the icctl CLI binary.
icctl/cmd
Package cmd defines the cobra command tree for icctl.
Package cmd defines the cobra command tree for icctl.
icctl/confirm
Package confirm provides destructive-verb preview rendering and confirmation prompting for the icctl CLI.
Package confirm provides destructive-verb preview rendering and confirmation prompting for the icctl CLI.
icctl/output
Package output provides output formatters for the icctl CLI, supporting JSON and table formats.
Package output provides output formatters for the icctl CLI, supporting JSON and table formats.
icctl/profile
Package profile provides CLI profile management including secret storage (keychain-first with file fallback) and profile configuration persistence.
Package profile provides CLI profile management including secret storage (keychain-first with file fallback) and profile configuration persistence.
icctl/tui
Package tui provides helpers for constructing SDK clients and other terminal-UI concerns from the CLI's resolved State.
Package tui provides helpers for constructing SDK clients and other terminal-UI concerns from the CLI's resolved State.
internal
generated
Package generated provides primitives to interact with the openapi HTTP API.
Package generated provides primitives to interact with the openapi HTTP API.
transport
Package transport provides internal HTTP transport primitives for the Intelligence Cloud Go SDK.
Package transport provides internal HTTP transport primitives for the Intelligence Cloud Go SDK.
version
Package version exposes build-time version information injected via Go linker flags (ldflags).
Package version exposes build-time version information injected via Go linker flags (ldflags).

Jump to

Keyboard shortcuts

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