Documentation
¶
Overview ¶
Package profiles manages named Dash0 configuration profiles.
Profiles are stored in ~/.dash0/profiles.json as named sets of connection parameters (API URL, auth token, OTLP URL, dataset). One profile is marked as active in ~/.dash0/activeProfile and used as the default configuration. Environment variables (DASH0_API_URL, DASH0_AUTH_TOKEN, DASH0_OTLP_URL, DASH0_DATASET) override the active profile.
This package imports the root dash0 package for dash0.ClientOption and dash0.DatasetPtr -- never the reverse.
Index ¶
- Constants
- Variables
- func CanonicalAPIURL(raw string) (string, error)
- func ResolveOAuthClientID(apiURL, stored string, opts ...StoreOption) string
- func WithConfiguration(ctx context.Context, cfg *ResolvedConfiguration) context.Context
- type Configuration
- type ConfigurationField
- type ConfigurationSource
- type OAuthClientRecord
- type OAuthClientStore
- type OAuthState
- type Profile
- type ProfilesFile
- type ResolvedConfiguration
- func FromContext(ctx context.Context) *ResolvedConfiguration
- func ResolveConfiguration(apiUrl, authToken string, opts ...StoreOption) (*ResolvedConfiguration, error)
- func ResolveConfigurationContext(ctx context.Context, apiUrl, authToken string, opts ...StoreOption) (*ResolvedConfiguration, error)
- func ResolveConfigurationWithOtlp(apiUrl, authToken, otlpUrl, dataset string, opts ...StoreOption) (*ResolvedConfiguration, error)
- func ResolveConfigurationWithOtlpContext(ctx context.Context, apiUrl, authToken, otlpUrl, dataset string, ...) (*ResolvedConfiguration, error)
- func (cfg *ResolvedConfiguration) ApiUrl() string
- func (cfg *ResolvedConfiguration) AuthTokenProvider(opts ...StoreOption) dash0.AuthTokenProvider
- func (cfg *ResolvedConfiguration) ClientOptions() []dash0.ClientOption
- func (cfg *ResolvedConfiguration) ConfigDir() string
- func (cfg *ResolvedConfiguration) Dataset() string
- func (cfg *ResolvedConfiguration) DatasetPtr() *string
- func (cfg *ResolvedConfiguration) HasCredentials() bool
- func (cfg *ResolvedConfiguration) OAuth() *OAuthState
- func (cfg *ResolvedConfiguration) OtlpUrl() string
- func (cfg *ResolvedConfiguration) ProfileName() string
- func (cfg *ResolvedConfiguration) Source(field ConfigurationField) ConfigurationSource
- func (cfg *ResolvedConfiguration) Token() string
- type Store
- func (s *Store) AddProfile(profile Profile) error
- func (s *Store) AddProfileContext(ctx context.Context, profile Profile) error
- func (s *Store) GetActiveConfiguration() (*ResolvedConfiguration, error)
- func (s *Store) GetActiveConfigurationContext(ctx context.Context) (*ResolvedConfiguration, error)
- func (s *Store) GetActiveProfile() (*Profile, error)
- func (s *Store) GetConfigurationForProfile(ctx context.Context, profileName string) (*ResolvedConfiguration, error)
- func (s *Store) GetProfiles() ([]Profile, error)
- func (s *Store) RemoveProfile(profileName string) error
- func (s *Store) RemoveProfileContext(ctx context.Context, profileName string) error
- func (s *Store) SetActiveProfile(profileName string) error
- func (s *Store) SetActiveProfileContext(ctx context.Context, profileName string) error
- func (s *Store) UpdateProfile(name string, updateFn func(*Configuration)) error
- func (s *Store) UpdateProfileContext(ctx context.Context, name string, updateFn func(*Configuration)) error
- type StoreOption
Examples ¶
- CanonicalAPIURL
- Configuration.DatasetPtr
- NewOAuthClientStore
- NewStore
- NewStore (WithConfigDir)
- OAuthClientStore.Delete
- OAuthClientStore.Get
- OAuthClientStore.Put
- ResolveConfiguration (ParameterOverride)
- ResolveConfigurationContext
- ResolveConfigurationWithOtlpContext
- ResolveOAuthClientID
- ResolveOAuthClientID (DcrCacheFallback)
- ResolvedConfiguration.AuthTokenProvider
- ResolvedConfiguration.AuthTokenProvider (StaticToken)
- ResolvedConfiguration.ClientOptions
- ResolvedConfiguration.Source
- ResolvedConfiguration.Token
- Store.AddProfileContext
- Store.GetActiveConfiguration
- Store.GetActiveConfiguration (EnvVarOverride)
- Store.GetActiveConfigurationContext
- Store.GetConfigurationForProfile
- Store.RemoveProfile
- Store.RemoveProfileContext
- Store.SetActiveProfileContext
- Store.UpdateProfileContext
- WithConfiguration
Constants ¶
const ( // ConfigDirName is the name of the directory containing Dash0 configuration. ConfigDirName = ".dash0" // ProfilesFileName is the name of the file containing profile configurations. ProfilesFileName = "profiles.json" // ActiveProfileFileName is the name of the file containing the active profile name. ActiveProfileFileName = "activeProfile" // EnvApiUrl is the environment variable for the Dash0 API URL. EnvApiUrl = "DASH0_API_URL" // EnvAuthToken is the environment variable for the Dash0 auth token. EnvAuthToken = "DASH0_AUTH_TOKEN" // EnvOtlpUrl is the environment variable for the Dash0 OTLP URL. EnvOtlpUrl = "DASH0_OTLP_URL" // EnvDataset is the environment variable for the Dash0 dataset. EnvDataset = "DASH0_DATASET" // EnvConfigDir is the environment variable that overrides the default // configuration directory. EnvConfigDir = "DASH0_CONFIG_DIR" )
const MaxProfileNameLength = 64
MaxProfileNameLength is the maximum allowed length of a profile name. The cap keeps profile names within filesystem-friendly bounds and prevents pathological inputs from inflating the activeProfile pointer file.
const OAuthClientsFileName = "oauth-clients.json"
OAuthClientsFileName is the file storing cached dynamic client registrations.
const OAuthRefreshExpiresInDefault = 1 * time.Hour
OAuthRefreshExpiresInDefault is the lifetime assumed when the IdP omits expires_in. RFC 6749 §5.1 makes expires_in RECOMMENDED but not required; rather than reject a compliant response that omits it, the library falls back to this conservative default, which is comfortably above OAuthRefreshMinExpiresIn so an immediate refresh storm does not follow.
const OAuthRefreshMaxExpiresIn = 24 * time.Hour
OAuthRefreshMaxExpiresIn caps the trusted lifetime of an OAuth access token. A token endpoint that returns expires_in beyond this ceiling is treated as untrustworthy and the response is rejected before the caller can adopt it.
const OAuthRefreshMinExpiresIn = 2 * OAuthRefreshThreshold
OAuthRefreshMinExpiresIn is the minimum trusted lifetime of a refreshed access token. Tokens shorter than this would cross OAuthRefreshThreshold almost immediately and trigger a per-minute refresh storm; the IdP either misconfigured the client or is unhealthy, and the safe response is to reject the rotation and surface a clear error. The 2× factor preserves a useful working window: at least one OAuthRefreshThreshold of "fresh" plus another of "still serviceable".
const OAuthRefreshThreshold = 5 * time.Minute
OAuthRefreshThreshold is how far before expiry a token refresh is attempted.
const OAuthRefreshTimeout = 30 * time.Second
OAuthRefreshTimeout bounds a single token refresh, including the wait for the cross-process .profile-lock. A refresh runs on its own deadline rather than the caller's, so this is what stops a hung authorization server from blocking a request forever. Exported alongside OAuthRefreshThreshold so callers can reason about how long a request may block on a refresh.
Variables ¶
var ( // ErrNoActiveProfile is returned when there is no active profile. ErrNoActiveProfile = errors.New("no active profile configured") // ErrProfileNotFound is returned when a requested profile is not found. ErrProfileNotFound = errors.New("profile not found") )
var ErrNoAssociatedProfile = errors.New(
"the credentials are not associated with a Dash0 profile, so the OAuth access token " +
"cannot be refreshed",
)
ErrNoAssociatedProfile was returned when an OAuth access token needed refreshing but the configuration was not associated with a stored profile.
Deprecated: since v1.34.0. Never returned, because only a Store builds a ResolvedConfiguration with OAuth state.
var ErrOAuthClientsFileCorrupt = errors.New("oauth-clients.json is corrupt")
ErrOAuthClientsFileCorrupt is wrapped into the error returned by OAuthClientStore.Get when the on-disk file exists but is unparseable. OAuthClientStore.Put and OAuthClientStore.Delete handle corruption internally by quarantining the bad file (see [OAuthClientStore.load]), rather than failing.
var ErrReauthenticationRequired = errors.New("OAuth refresh token rejected; re-authentication required")
ErrReauthenticationRequired is returned by refresh-bearing operations when the OAuth refresh token is no longer accepted by the authorization server (RFC 6749 invalid_grant) and the caller must initiate a fresh interactive login. Loading a configuration never returns it; match it with errors.Is on the request error from ResolvedConfiguration.AuthTokenProvider. Callers should treat this as a terminal state for the affected profile: the stored refresh token has been cleared from disk before this error is returned, so a subsequent call no longer retries the dead credential.
var ErrRevocationFailed = errors.New("OAuth refresh token revocation failed; the token may still be valid on the authorization server")
ErrRevocationFailed is wrapped into the result of Store.RemoveProfile (and equivalents) when the local profile was successfully removed but the best-effort revocation of the OAuth refresh token failed. The refresh token may still be live on the authorization server until its natural expiry. Callers should detect this via errors.Is and surface a "revoke manually" hint to the user.
Functions ¶
func CanonicalAPIURL ¶ added in v1.15.0
CanonicalAPIURL normalises an API URL into the key form used by OAuthClientStore. It lowercases the scheme and host, strips userinfo (so credentials never reach the on-disk key), drops the port when it matches the scheme default (so "https://api.example.com" and "https://api.example.com:443" share one cache entry), normalises the path with path.Clean, trims a trailing slash from the path, and drops query and fragment components. Returns an error when the input is not a parseable absolute URL.
Example ¶
package main
import (
"fmt"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
key, err := profiles.CanonicalAPIURL("HTTPS://API.EU-WEST-1.AWS.DASH0.COM/?x=1#frag")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(key)
}
Output: https://api.eu-west-1.aws.dash0.com
func ResolveOAuthClientID ¶ added in v1.21.0
func ResolveOAuthClientID(apiURL, stored string, opts ...StoreOption) string
ResolveOAuthClientID returns the client_id to send with token and revoke requests. The profile's stored value wins; if it is empty, the DCR cache for apiURL is consulted. An empty result means the caller must omit client_id rather than send an empty parameter.
Example ¶
package main
import (
"fmt"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
// The profile's stored client ID wins outright; the DCR cache is not consulted.
clientID := profiles.ResolveOAuthClientID("https://api.eu-west-1.aws.dash0.com", "client-from-profile")
fmt.Println(clientID)
}
Output: client-from-profile
Example (DcrCacheFallback) ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewOAuthClientStore(profiles.WithConfigDir(configDir))
_ = store.Put("https://api.eu-west-1.aws.dash0.com", profiles.OAuthClientRecord{
ClientID: "client-from-dcr-cache",
RedirectURI: "http://localhost:8080/callback",
})
// An empty stored value falls back to the DCR cache for apiURL.
clientID := profiles.ResolveOAuthClientID(
"https://api.eu-west-1.aws.dash0.com", "",
profiles.WithConfigDir(configDir),
)
fmt.Println(clientID)
}
Output: client-from-dcr-cache
func WithConfiguration ¶
func WithConfiguration(ctx context.Context, cfg *ResolvedConfiguration) context.Context
WithConfiguration returns a new context with the given configuration stored.
Example ¶
package main
import (
"context"
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
cfg, err := profiles.ResolveConfiguration(
"https://api.eu-west-1.aws.dash0.com",
"auth_example-token",
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
ctx := profiles.WithConfiguration(context.Background(), cfg)
retrieved := profiles.FromContext(ctx)
fmt.Println(retrieved.ApiUrl())
}
Output: https://api.eu-west-1.aws.dash0.com
Types ¶
type Configuration ¶
type Configuration struct {
ApiUrl string `json:"apiUrl"`
// AuthToken is a static auth token.
// For an OAuth profile it is a copy of [OAuthState.AccessToken], kept until
// the release after v1.34.0 so code that reads or writes the access token
// here keeps working.
AuthToken string `json:"authToken"`
OtlpUrl string `json:"otlpUrl,omitempty"`
Dataset string `json:"dataset,omitempty"`
// OAuth is set when the profile authorizes with an OAuth access token.
// Refreshed per request by [ResolvedConfiguration.AuthTokenProvider], never on load.
OAuth *OAuthState `json:"oauth,omitempty"`
}
Configuration is the schema of one profile in profiles.json.
It is what Store.AddProfile and Store.UpdateProfile read and write. To call the API, resolve a ResolvedConfiguration through a Store or one of the ResolveConfiguration functions instead.
func (*Configuration) DatasetPtr ¶
func (cfg *Configuration) DatasetPtr() *string
DatasetPtr returns the dataset as a *string suitable for Dash0 API calls. It returns nil for empty strings and "default", matching dash0.DatasetPtr.
Example ¶
package main
import (
"fmt"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
cfg := &profiles.Configuration{Dataset: "production"}
ptr := cfg.DatasetPtr()
fmt.Println(*ptr)
cfgDefault := &profiles.Configuration{Dataset: "default"}
ptrDefault := cfgDefault.DatasetPtr()
fmt.Println(ptrDefault)
}
Output: production <nil>
func (*Configuration) HasCredentials ¶ added in v1.21.0
func (cfg *Configuration) HasCredentials() bool
HasCredentials reports whether the profile holds a static auth token or an OAuth access token.
type ConfigurationField ¶ added in v1.34.0
type ConfigurationField int
ConfigurationField names a field of a ResolvedConfiguration for ResolvedConfiguration.Source.
const ( // FieldApiUrl is the field returned by [ResolvedConfiguration.ApiUrl]. FieldApiUrl ConfigurationField = iota // FieldAuthToken is the field returned by [ResolvedConfiguration.Token]. FieldAuthToken // FieldOtlpUrl is the field returned by [ResolvedConfiguration.OtlpUrl]. FieldOtlpUrl // FieldDataset is the field returned by [ResolvedConfiguration.Dataset]. FieldDataset )
type ConfigurationSource ¶ added in v1.34.0
type ConfigurationSource string
ConfigurationSource is the layer that supplied the value of a ConfigurationField.
const ( // SourceUnset means no layer supplied a value and the field is empty. SourceUnset ConfigurationSource = "" // SourceProfile means the value came from a profile in profiles.json. SourceProfile ConfigurationSource = "profile" // SourceEnvironment means the value came from an environment variable, such as DASH0_API_URL. SourceEnvironment ConfigurationSource = "environment" // SourceArgument means the value came from an argument the caller passed to a ResolveConfiguration function. SourceArgument ConfigurationSource = "argument" )
type OAuthClientRecord ¶ added in v1.15.0
type OAuthClientRecord struct {
ClientID string `json:"clientId"`
RegistrationAccessToken string `json:"registrationAccessToken,omitempty"`
RedirectURI string `json:"redirectUri"`
}
OAuthClientRecord is a cached dynamic client registration (RFC 7591).
type OAuthClientStore ¶ added in v1.15.0
type OAuthClientStore struct {
// contains filtered or unexported fields
}
OAuthClientStore caches dynamic client registrations keyed by canonical API URL. The file is created mode 0600 because RegistrationAccessToken (RFC 7592) is a long-lived management credential.
In-process mutation (Get/Put/Delete) is serialized by mu; cross-process mutation is serialized via an OS-level advisory lock on [oauthClientsLockFileName] so two CLI invocations sharing the same config directory cannot lose-update each other's RegistrationAccessToken values.
func NewOAuthClientStore ¶ added in v1.15.0
func NewOAuthClientStore(opts ...StoreOption) (*OAuthClientStore, error)
NewOAuthClientStore mirrors NewStore: explicit WithConfigDir > DASH0_CONFIG_DIR > ~/.dash0/. Same best-effort hygiene as NewStore: best-effort dir-mode tightening and stale-tempfile cleanup when the directory already exists.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, err := profiles.NewOAuthClientStore(profiles.WithConfigDir(configDir))
if err != nil {
fmt.Println("error:", err)
return
}
_, found, err := store.Get("https://api.eu-west-1.aws.dash0.com")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("found:", found)
}
Output: found: false
func (*OAuthClientStore) Delete ¶ added in v1.15.0
func (s *OAuthClientStore) Delete(apiURL string) error
Delete removes the record for apiURL. A miss is a no-op. Cross-process serialization mirrors OAuthClientStore.Put.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewOAuthClientStore(profiles.WithConfigDir(configDir))
_ = store.Put("https://api.eu-west-1.aws.dash0.com", profiles.OAuthClientRecord{
ClientID: "client-123",
RedirectURI: "http://localhost:8080/callback",
})
if err := store.Delete("https://api.eu-west-1.aws.dash0.com"); err != nil {
fmt.Println("error:", err)
return
}
_, found, _ := store.Get("https://api.eu-west-1.aws.dash0.com")
fmt.Println("found after delete:", found)
}
Output: found after delete: false
func (*OAuthClientStore) Get ¶ added in v1.15.0
func (s *OAuthClientStore) Get(apiURL string) (OAuthClientRecord, bool, error)
Get returns the cached record for apiURL, or (zero, false, nil) on miss. A missing file is a miss, not an error. A corrupt file returns ErrOAuthClientsFileCorrupt wrapped with the quarantine path so the operator can decide whether to investigate.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewOAuthClientStore(profiles.WithConfigDir(configDir))
_ = store.Put("https://api.eu-west-1.aws.dash0.com", profiles.OAuthClientRecord{
ClientID: "client-123",
RedirectURI: "http://localhost:8080/callback",
})
rec, found, err := store.Get("https://api.eu-west-1.aws.dash0.com")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(found, rec.ClientID)
}
Output: true client-123
func (*OAuthClientStore) Put ¶ added in v1.15.0
func (s *OAuthClientStore) Put(apiURL string, rec OAuthClientRecord) error
Put upserts a record for apiURL. The read-modify-write sequence is guarded by both an in-process mutex and a cross-process advisory lock on [oauthClientsLockFileName] so two CLI invocations sharing the same config directory cannot lose-update each other's RegistrationAccessToken values. If the on-disk file is corrupt it is quarantined (renamed with a timestamp suffix) before the new record is written; the previous registrations are lost from the active file but preserved on disk for manual recovery.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, err := profiles.NewOAuthClientStore(profiles.WithConfigDir(configDir))
if err != nil {
fmt.Println("error:", err)
return
}
if err := store.Put("https://api.eu-west-1.aws.dash0.com", profiles.OAuthClientRecord{
ClientID: "client-123",
RedirectURI: "http://localhost:8080/callback",
}); err != nil {
fmt.Println("error:", err)
return
}
rec, found, _ := store.Get("https://api.eu-west-1.aws.dash0.com")
fmt.Println(found, rec.ClientID)
}
Output: true client-123
type OAuthState ¶ added in v1.15.0
type OAuthState struct {
ClientID string `json:"clientId,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
RefreshToken string `json:"refreshToken,omitempty"`
ExpiresAt time.Time `json:"expiresAt,omitzero"`
}
OAuthState carries the OAuth-specific state that must survive across CLI invocations: the dynamic client identifier issued at registration (RFC 7591), the current access token, the long-lived refresh token used to mint new access tokens, and the access token's expiry deadline.
type Profile ¶
type Profile struct {
Name string `json:"name"`
Configuration Configuration `json:"configuration"`
}
Profile represents a named configuration profile.
type ProfilesFile ¶
type ProfilesFile struct {
Profiles []Profile `json:"profiles"`
}
ProfilesFile represents the file storing multiple profiles.
type ResolvedConfiguration ¶ added in v1.34.0
type ResolvedConfiguration struct {
// contains filtered or unexported fields
}
ResolvedConfiguration is a configuration resolved from a profile, environment variables, and caller arguments.
Only a Store and the ResolveConfiguration functions build one, so a configuration with OAuth state always knows the profile its refreshed tokens are written back to. The zero value has no credentials. All methods are safe to call on a nil pointer.
func FromContext ¶
func FromContext(ctx context.Context) *ResolvedConfiguration
FromContext retrieves the configuration from ctx, or nil if not present.
func ResolveConfiguration ¶
func ResolveConfiguration(apiUrl, authToken string, opts ...StoreOption) (*ResolvedConfiguration, error)
ResolveConfiguration loads the active profile, applies environment variable overrides, then applies the given parameter overrides on top. Non-empty parameters take highest precedence.
This is a convenience function that creates a temporary Store internally. Pass StoreOption values (e.g. WithConfigDir) to control how the profile store is constructed.
Example (ParameterOverride) ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
// Parameters take highest precedence, overriding both profiles and env vars.
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
cfg, err := profiles.ResolveConfiguration(
"https://api.us-west-2.aws.dash0.com", // overrides profile's API URL
"", // falls back to profile's auth token
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.ApiUrl())
fmt.Println(cfg.Token())
}
Output: https://api.us-west-2.aws.dash0.com auth_dev-token
func ResolveConfigurationContext ¶ added in v1.15.0
func ResolveConfigurationContext(ctx context.Context, apiUrl, authToken string, opts ...StoreOption) (*ResolvedConfiguration, error)
ResolveConfigurationContext is the context-aware variant of ResolveConfiguration. ctx is currently unused: this call reads the profile store and makes no network request.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg, err := profiles.ResolveConfigurationContext(ctx, "", "",
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.ApiUrl())
}
Output: https://api.eu-west-1.aws.dash0.com
func ResolveConfigurationWithOtlp ¶
func ResolveConfigurationWithOtlp(apiUrl, authToken, otlpUrl, dataset string, opts ...StoreOption) (*ResolvedConfiguration, error)
ResolveConfigurationWithOtlp is like ResolveConfiguration but also accepts OTLP URL and dataset overrides.
func ResolveConfigurationWithOtlpContext ¶ added in v1.15.0
func ResolveConfigurationWithOtlpContext(ctx context.Context, apiUrl, authToken, otlpUrl, dataset string, opts ...StoreOption) (*ResolvedConfiguration, error)
ResolveConfigurationWithOtlpContext is the context-aware variant of ResolveConfigurationWithOtlp. ctx is currently unused: this call reads the profile store and makes no network request.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg, err := profiles.ResolveConfigurationWithOtlpContext(ctx,
"", "",
"https://ingress.eu-west-1.aws.dash0.com",
"production",
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.OtlpUrl(), cfg.Dataset())
}
Output: https://ingress.eu-west-1.aws.dash0.com production
func (*ResolvedConfiguration) ApiUrl ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) ApiUrl() string
ApiUrl returns the API URL.
func (*ResolvedConfiguration) AuthTokenProvider ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) AuthTokenProvider(opts ...StoreOption) dash0.AuthTokenProvider
AuthTokenProvider returns a dash0.AuthTokenProvider that keeps this configuration's OAuth access token fresh.
Pass the result to dash0.WithAuthTokenProvider instead of handing dash0.WithAuthToken a token resolved once at startup. A Dash0 OAuth access token is valid for 15 minutes, so a client built around a single snapshot of it starts failing with 401 partway through any operation that runs longer than the token's remaining validity — a large telemetry export, a bulk apply, or a Terraform run over many resources. This provider is consulted before every request and refreshes the token once it comes within OAuthRefreshThreshold of expiry, which keeps such an operation running on a single interactive login.
For a configuration with no OAuth state the returned provider serves the static auth token unchanged, so callers do not need to branch on the profile's auth kind.
The returned provider is safe for concurrent use and holds its own copy of cfg, so refreshes are visible to every request the client issues but do not mutate the caller's ResolvedConfiguration.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
// Point the store at a scratch directory so the example does not touch the
// real ~/.dash0.
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, err := profiles.NewStore(profiles.WithConfigDir(configDir))
if err != nil {
fmt.Println("error:", err)
return
}
if err := store.AddProfile(profiles.Profile{
Name: "production",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
OAuth: &profiles.OAuthState{
ClientID: "example-client-id",
AccessToken: "dash0_at_example-token",
RefreshToken: "example-refresh-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
},
},
}); err != nil {
fmt.Println("error:", err)
return
}
// An OAuth-backed configuration yields a provider that refreshes the access
// token as it approaches expiry, so a client built from it keeps working for
// operations longer than a single token's 15-minute lifetime.
cfg, err := store.GetConfigurationForProfile(context.Background(), "production")
if err != nil {
fmt.Println("error:", err)
return
}
provider := cfg.AuthTokenProvider()
// The token is nowhere near expiry, so it is served without a network call.
authToken, err := provider.AuthToken(context.Background())
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(authToken)
}
Output: dash0_at_example-token
Example (StaticToken) ¶
package main
import (
"context"
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
// A configuration with no OAuth state serves its static token unchanged, so
// callers do not need to branch on the profile's auth kind.
cfg, err := profiles.ResolveConfiguration(
"https://api.eu-west-1.aws.dash0.com",
"auth_example-token",
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
authToken, err := cfg.AuthTokenProvider().AuthToken(context.Background())
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(authToken)
}
Output: auth_example-token
func (*ResolvedConfiguration) ClientOptions ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) ClientOptions() []dash0.ClientOption
ClientOptions returns dash0.ClientOption values that configure a client from this ResolvedConfiguration. Non-empty values are mapped as follows:
- ApiUrl -> dash0.WithApiUrl
- Token -> dash0.WithAuthTokenProvider, so an OAuth-backed token is refreshed for the lifetime of the client rather than frozen at construction time, and a static token is served unchanged
- OtlpUrl -> dash0.WithOtlpEndpoint with dash0.OtlpEncodingJson
The dataset is not mapped because it is a per-request parameter, not a client-level setting. Use ResolvedConfiguration.DatasetPtr to convert it for API calls.
Callers can append additional options to override or supplement the returned slice:
opts := cfg.ClientOptions()
opts = append(opts, dash0.WithUserAgent("my-tool/1.0"))
client, err := dash0.NewClient(opts...)
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
cfg, err := profiles.ResolveConfiguration(
"https://api.eu-west-1.aws.dash0.com",
"auth_example-token",
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
opts := cfg.ClientOptions()
fmt.Printf("produced %d client options\n", len(opts))
}
Output: produced 2 client options
func (*ResolvedConfiguration) ConfigDir ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) ConfigDir() string
ConfigDir returns the directory of the profiles.json the configuration was resolved from, or "" when ResolvedConfiguration.ProfileName is "".
func (*ResolvedConfiguration) Dataset ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) Dataset() string
Dataset returns the dataset.
func (*ResolvedConfiguration) DatasetPtr ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) DatasetPtr() *string
DatasetPtr returns the dataset as a *string suitable for Dash0 API calls. It returns nil for empty strings and "default", matching dash0.DatasetPtr.
func (*ResolvedConfiguration) HasCredentials ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) HasCredentials() bool
HasCredentials reports whether ResolvedConfiguration.Token is non-empty.
func (*ResolvedConfiguration) OAuth ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) OAuth() *OAuthState
OAuth returns a copy of the OAuth state, or nil when the configuration uses a static auth token.
func (*ResolvedConfiguration) OtlpUrl ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) OtlpUrl() string
OtlpUrl returns the OTLP URL.
func (*ResolvedConfiguration) ProfileName ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) ProfileName() string
ProfileName returns the name of the profile the configuration was resolved from, or "" when it came from environment variables or caller arguments alone.
func (*ResolvedConfiguration) Source ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) Source(field ConfigurationField) ConfigurationSource
Source returns the layer that supplied the value of field. It returns SourceUnset when the field is empty or field is unknown.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
Dataset: "staging",
},
})
_ = os.Setenv(profiles.EnvDataset, "production")
defer func() { _ = os.Unsetenv(profiles.EnvDataset) }()
cfg, err := profiles.ResolveConfiguration(
"https://api.us-west-2.aws.dash0.com",
"",
profiles.WithConfigDir(configDir),
)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("api url: %q\n", cfg.Source(profiles.FieldApiUrl))
fmt.Printf("auth token: %q\n", cfg.Source(profiles.FieldAuthToken))
fmt.Printf("otlp url: %q\n", cfg.Source(profiles.FieldOtlpUrl))
fmt.Printf("dataset: %q\n", cfg.Source(profiles.FieldDataset))
}
Output: api url: "argument" auth token: "profile" otlp url: "" dataset: "environment"
func (*ResolvedConfiguration) Token ¶ added in v1.34.0
func (cfg *ResolvedConfiguration) Token() string
Token returns the credential as resolved: the OAuth access token for an OAuth profile, otherwise the static auth token. An OAuth access token may be expired. To authenticate requests, use ResolvedConfiguration.AuthTokenProvider, which refreshes it.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, err := profiles.NewStore(profiles.WithConfigDir(configDir))
if err != nil {
fmt.Println("error:", err)
return
}
if err := store.AddProfile(profiles.Profile{
Name: "production",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
OAuth: &profiles.OAuthState{
AccessToken: "dash0_at_example-token",
RefreshToken: "example-refresh-token",
ExpiresAt: time.Now().Add(1 * time.Hour),
},
},
}); err != nil {
fmt.Println("error:", err)
return
}
cfg, err := store.GetConfigurationForProfile(context.Background(), "production")
if err != nil {
fmt.Println("error:", err)
return
}
// Token returns the OAuth access token for an OAuth profile and the static
// auth token otherwise.
fmt.Println(cfg.Token())
}
Output: dash0_at_example-token
type Store ¶
type Store struct {
// contains filtered or unexported fields
}
Store handles profile storage and retrieval.
Cross-process refresh: Store serializes OAuth token refreshes both within a process (via an in-memory mutex) and across processes that share the same config directory (via an OS-level advisory lock on .profile-lock, backed by github.com/gofrs/flock).
func NewStore ¶
func NewStore(opts ...StoreOption) (*Store, error)
NewStore creates a new profile store.
The configuration directory is resolved in this order:
- Explicit WithConfigDir option (if provided).
- The DASH0_CONFIG_DIR environment variable (if set).
- ~/.dash0/ (default).
Best-effort hygiene on the resolved directory: the mode is tightened to [configDirMode] (0700) when broader, and any leftover writeFileAtomic temp files older than [staleTempFileAge] are removed. SIGKILL or a panic mid-write skips the deferred cleanup in writeFileAtomic, so .tmp-* files can accumulate. Both steps tolerate a missing directory (it will be created later by writeFileAtomic when the first write happens).
Example ¶
package main
import (
"fmt"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
svc, err := profiles.NewStore()
if err != nil {
fmt.Println("error:", err)
return
}
allProfiles, err := svc.GetProfiles()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("found %d profiles\n", len(allProfiles))
}
Output:
Example (WithConfigDir) ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
svc, err := profiles.NewStore(profiles.WithConfigDir(configDir))
if err != nil {
fmt.Println("error:", err)
return
}
allProfiles, err := svc.GetProfiles()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("found %d profiles\n", len(allProfiles))
}
Output: found 0 profiles
func (*Store) AddProfile ¶
AddProfile adds a new profile to the configuration. If a profile with the same name already exists, it is replaced. When adding the first profile, it is automatically set as active.
The read-modify-write sequence is serialized cross-process via the .profile-lock sentinel; see Store for the locking model. Lock acquisition uses context.Background; callers that need to bound the wait should use Store.AddProfileContext.
func (*Store) AddProfileContext ¶ added in v1.15.0
AddProfileContext is the context-aware variant of Store.AddProfile. The ctx bounds the wait to acquire the cross-process [.profile-lock]. Returns an error from [validateProfileName] when the profile name is empty, contains control characters or path separators, starts with '.', or exceeds MaxProfileNameLength.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
// The Context variant lets the caller bound the wait for the
// cross-process .profile-lock acquisition — useful when a long-running
// agent flow already has a deadline context to honor.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := store.AddProfileContext(ctx, profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
if err != nil {
fmt.Println("error:", err)
return
}
all, _ := store.GetProfiles()
fmt.Println("count:", len(all))
}
Output: count: 1
func (*Store) GetActiveConfiguration ¶
func (s *Store) GetActiveConfiguration() (*ResolvedConfiguration, error)
GetActiveConfiguration returns the currently active configuration. Environment variables take precedence over the active profile on a per-field basis: each of DASH0_API_URL, DASH0_AUTH_TOKEN, DASH0_OTLP_URL, and DASH0_DATASET overrides only the field it names, and the remaining fields keep the active profile's values. When there is no active profile, a DASH0_AUTH_TOKEN plus at least one of DASH0_API_URL or DASH0_OTLP_URL is a complete configuration on its own.
The OAuth access token is returned as stored and is not refreshed here. Refreshing happens per request, in the provider returned by ResolvedConfiguration.AuthTokenProvider, so it only happens for a client that actually goes on to use the profile's credentials. A caller that reads ResolvedConfiguration.Token directly gets the token on disk, which may be expired.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
// Create a temporary config directory with a profile.
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
Dataset: "staging",
},
})
cfg, err := store.GetActiveConfiguration()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.ApiUrl())
fmt.Println(cfg.Dataset())
}
Output: https://api.eu-west-1.aws.dash0.com staging
Example (EnvVarOverride) ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
// Environment variables override values from the active profile.
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
Dataset: "staging",
},
})
// DASH0_DATASET overrides the profile's dataset.
_ = os.Setenv(profiles.EnvDataset, "production")
defer func() { _ = os.Unsetenv(profiles.EnvDataset) }()
cfg, err := store.GetActiveConfiguration()
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.ApiUrl())
fmt.Println(cfg.Dataset())
}
Output: https://api.eu-west-1.aws.dash0.com production
func (*Store) GetActiveConfigurationContext ¶ added in v1.15.0
func (s *Store) GetActiveConfigurationContext(ctx context.Context) (*ResolvedConfiguration, error)
GetActiveConfigurationContext is the context-aware variant of Store.GetActiveConfiguration. ctx is currently unused: this call reads the profile store and makes no network request.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
cfg, err := store.GetActiveConfigurationContext(ctx)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.ApiUrl())
}
Output: https://api.eu-west-1.aws.dash0.com
func (*Store) GetActiveProfile ¶
GetActiveProfile returns the currently active profile.
func (*Store) GetConfigurationForProfile ¶ added in v1.21.0
func (s *Store) GetConfigurationForProfile(ctx context.Context, profileName string) (*ResolvedConfiguration, error)
GetConfigurationForProfile returns the configuration of a named profile, with environment variable overrides layered on top. It is the per-name counterpart to Store.GetActiveConfigurationContext, and returns ErrProfileNotFound when no profile carries the given name so callers can phrase their own message.
The OAuth access token is not refreshed here. Refreshing happens per request, in the provider returned by ResolvedConfiguration.AuthTokenProvider, so it only happens for a client that actually goes on to use the profile's credentials. Refreshing at lookup time would spend a token exchange, and rotate the refresh token, even when the caller is about to authenticate with a static token supplied elsewhere.
ctx is accepted for symmetry with Store.GetActiveConfigurationContext and is currently unused: this call reads the profile store and makes no network request.
Example ¶
package main
import (
"context"
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, err := profiles.NewStore(profiles.WithConfigDir(configDir))
if err != nil {
fmt.Println("error:", err)
return
}
if err := store.AddProfile(profiles.Profile{
Name: "production",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_example-token",
},
}); err != nil {
fmt.Println("error:", err)
return
}
// Prefer this over GetProfiles plus a search by name: the returned
// configuration records which profile it came from.
cfg, err := store.GetConfigurationForProfile(context.Background(), "production")
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println(cfg.ProfileName())
}
Output: production
func (*Store) GetProfiles ¶
GetProfiles returns all available profiles.
func (*Store) RemoveProfile ¶
RemoveProfile removes a profile from the configuration. If the profile has OAuth state, the refresh token is revoked before removal, using context.Background for the revoke request. Use Store.RemoveProfileContext to plumb a cancellable context.
Revocation is best-effort: if it fails, the local profile is still removed and the returned error wraps ErrRevocationFailed. Callers can detect this with errors.Is and surface a "revoke manually" hint -- the refresh token may still be live on the authorization server.
If the removed profile was the active profile, the first remaining profile becomes active.
Example ¶
package main
import (
"fmt"
"os"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
if err := store.RemoveProfile("dev"); err != nil {
fmt.Println("error:", err)
return
}
all, _ := store.GetProfiles()
fmt.Println("remaining:", len(all))
}
Output: remaining: 0
func (*Store) RemoveProfileContext ¶ added in v1.15.0
RemoveProfileContext is the context-aware variant of Store.RemoveProfile.
The token-revocation HTTP round-trip runs AFTER the in-process and cross-process locks are released, so a hung authorization server cannot pin sibling CLI invocations sharing the same config directory. The cost is that the locks no longer cover the revocation; an interleaved process observing the now-removed profile will not see the revoke in-flight. That is acceptable because the refresh token is already gone from disk before revocation begins; the worst-case server-side residue is the unrevoked refresh token until its natural expiry.
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
// The Context variant plumbs cancellation through the OAuth refresh-token
// revocation HTTP call, so the caller can give up on a slow IdP.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := store.RemoveProfileContext(ctx, "dev"); err != nil {
fmt.Println("error:", err)
return
}
all, _ := store.GetProfiles()
fmt.Println("remaining:", len(all))
}
Output: remaining: 0
func (*Store) SetActiveProfile ¶
SetActiveProfile sets the active profile by name. Returns ErrProfileNotFound if no profile with the given name exists.
The change is serialized cross-process via the .profile-lock sentinel; see Store for the locking model. Lock acquisition uses context.Background; callers that need to bound the wait should use Store.SetActiveProfileContext.
func (*Store) SetActiveProfileContext ¶ added in v1.15.0
SetActiveProfileContext is the context-aware variant of Store.SetActiveProfile. The ctx bounds the wait to acquire the cross-process [.profile-lock].
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
_ = store.AddProfile(profiles.Profile{
Name: "prod",
Configuration: profiles.Configuration{
ApiUrl: "https://api.us-west-2.aws.dash0.com",
AuthToken: "auth_prod-token",
},
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := store.SetActiveProfileContext(ctx, "prod"); err != nil {
fmt.Println("error:", err)
return
}
active, _ := store.GetActiveProfile()
fmt.Println(active.Name)
}
Output: prod
func (*Store) UpdateProfile ¶
func (s *Store) UpdateProfile(name string, updateFn func(*Configuration)) error
UpdateProfile finds a profile by name and applies updateFn to its configuration, then saves. Returns an error if no profile with the given name exists.
The read-modify-write sequence is serialized cross-process via the .profile-lock sentinel; see Store for the locking model. Lock acquisition uses context.Background; callers that need to bound the wait should use Store.UpdateProfileContext.
func (*Store) UpdateProfileContext ¶ added in v1.15.0
func (s *Store) UpdateProfileContext(ctx context.Context, name string, updateFn func(*Configuration)) error
UpdateProfileContext is the context-aware variant of Store.UpdateProfile. The ctx bounds the wait to acquire the cross-process [.profile-lock].
Example ¶
package main
import (
"context"
"fmt"
"os"
"time"
"github.com/dash0hq/dash0-api-client-go/profiles"
)
func main() {
configDir, _ := os.MkdirTemp("", "dash0-example-*")
defer func() { _ = os.RemoveAll(configDir) }()
store, _ := profiles.NewStore(profiles.WithConfigDir(configDir))
_ = store.AddProfile(profiles.Profile{
Name: "dev",
Configuration: profiles.Configuration{
ApiUrl: "https://api.eu-west-1.aws.dash0.com",
AuthToken: "auth_dev-token",
},
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := store.UpdateProfileContext(ctx, "dev", func(cfg *profiles.Configuration) {
cfg.Dataset = "production"
}); err != nil {
fmt.Println("error:", err)
return
}
all, _ := store.GetProfiles()
fmt.Println(all[0].Configuration.Dataset)
}
Output: production
type StoreOption ¶
type StoreOption func(*storeConfig)
StoreOption configures a Store.
func WithConfigDir ¶
func WithConfigDir(dir string) StoreOption
WithConfigDir overrides the default configuration directory (~/.dash0/). This is useful for testing or for applications that store profiles in a non-standard location.