smplkit

package module
v1.3.43 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2026 License: MIT Imports: 27 Imported by: 0

README

smplkit Go SDK

Go Reference Build Coverage License Docs

The official Go SDK for smplkit — simple application infrastructure that just works.

Installation

go get github.com/smplkit/go-sdk

Requirements

  • Go 1.24+

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    smplkit "github.com/smplkit/go-sdk"
)

func main() {
    ctx := context.Background()

    // API key resolved from SMPLKIT_API_KEY env var or ~/.smplkit config file.
    // Pass explicitly as the first argument to override:
    //   smplkit.NewClient("sk_api_...", "production", "my-service")
    client, err := smplkit.NewClient("", "production", "my-service")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // ── Runtime: resolve config values ──────────────────────────────────
    // Returns the merged map for the current environment.
    values, err := client.Config().Get(ctx, "user_service")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(values["timeout"])

    // Or unmarshal directly into a typed struct.
    type ServiceConfig struct {
        Timeout int    `json:"timeout"`
        Retries int    `json:"retries"`
    }
    var cfg ServiceConfig
    if err := client.Config().GetInto(ctx, "user_service", &cfg); err != nil {
        log.Fatal(err)
    }
    fmt.Println(cfg.Timeout)

    // ── Management: CRUD operations ──────────────────────────────────────
    mgmt := client.Config().Management()

    configs, err := mgmt.List(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(len(configs))

    raw, err := mgmt.Get(ctx, "user_service")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(raw.ID)

    newConfig := mgmt.New("my_service", smplkit.WithConfigName("My Service"))
    newConfig.Items = map[string]interface{}{"timeout": 30, "retries": 3}
    if err := newConfig.Save(ctx); err != nil {
        log.Fatal(err)
    }

    if err := mgmt.Delete(ctx, "my_service"); err != nil {
        log.Fatal(err)
    }
}

Configuration

The API key is resolved using the following priority:

  1. Explicit argument: Pass apiKey to NewClient().
  2. Environment variable: Set SMPLKIT_API_KEY.
  3. Configuration file: Add api_key under [default] in ~/.smplkit:
# ~/.smplkit

[default]
api_key = sk_api_your_key_here

If none of these are set, NewClient returns a SmplError listing all three methods.

client, err := smplkit.NewClient("sk_api_...",
    smplkit.WithTimeout(30 * time.Second),   // default
    smplkit.WithHTTPClient(customHTTPClient),
)

Error Handling

All SDK errors extend SmplError and support errors.Is() / errors.As():

import "errors"

config, err := client.Config().Management().Get(ctx, "nonexistent")
if err != nil {
    var notFound *smplkit.SmplNotFoundError
    if errors.As(err, &notFound) {
        fmt.Println("Not found:", notFound.Message)
    } else {
        fmt.Println("Error:", err)
    }
}
Error Cause
SmplNotFoundError HTTP 404 — resource not found
SmplConflictError HTTP 409 — conflict
SmplValidationError HTTP 422 — validation error
SmplTimeoutError Request timed out
SmplConnectionError Network connectivity issue
SmplError Any other SDK error

Feature Flags

The SDK includes a full-featured feature flags client with management API, prescriptive runtime evaluation, and real-time updates.

Management API
ctx := context.Background()
mgmt := client.Flags().Management()

// Create a flag using typed factories
flag := mgmt.NewBooleanFlag("checkout-v2", false,
    smplkit.WithFlagName("Checkout V2"),
    smplkit.WithFlagDescription("Controls rollout of the new checkout experience."),
)
if err := flag.Save(ctx); err != nil {
    log.Fatal(err)
}

// Configure environments and rules, then save again
flag.SetEnvironmentEnabled("staging", true)
flag.AddRule(smplkit.NewRule("Enable for enterprise").
    Environment("staging").
    When("user.plan", "==", "enterprise").
    Serve(true).
    Build())
if err := flag.Save(ctx); err != nil {
    log.Fatal(err)
}

// List, get, delete
allFlags, _ := mgmt.List(ctx)
fetched, _ := mgmt.Get(ctx, "checkout-v2")
_ = allFlags
_ = fetched
err := mgmt.Delete(ctx, "checkout-v2")
Runtime Evaluation
// Define typed flag handles
checkout := flags.BoolFlag("checkout-v2", false)
banner   := flags.StringFlag("banner-color", "red")
retries  := flags.NumberFlag("max-retries", 3)

// Register a context provider
flags.SetContextProvider(func(ctx context.Context) []smplkit.Context {
    return []smplkit.Context{
        smplkit.NewContext("user", "user-42", map[string]interface{}{
            "plan": "enterprise",
        }),
    }
})

// Connect to an environment
err := flags.Connect(ctx, "staging")

// Evaluate — uses provider context, caches results
isV2 := checkout.Get(ctx)            // true (rule matched)
color := banner.Get(ctx)             // "blue"

// Explicit context override
basicUser := smplkit.NewContext("user", "u-1", map[string]interface{}{"plan": "free"})
isV2 = checkout.Get(ctx, basicUser)  // false

// Change listeners
flags.OnChange(func(evt *smplkit.FlagChangeEvent) {
    fmt.Println("flag changed:", evt.Key)
})

// Cache stats
stats := flags.Stats()
fmt.Printf("hits=%d misses=%d\n", stats.CacheHits, stats.CacheMisses)

// Cleanup
flags.Disconnect(ctx)
Flag Types
Constant Value
FlagTypeBoolean "BOOLEAN"
FlagTypeString "STRING"
FlagTypeNumeric "NUMERIC"
FlagTypeJSON "JSON"

Documentation

License

MIT

Documentation

Overview

Package smplkit provides a Go client for the smplkit platform.

Quick start:

client, err := smplkit.NewClient("sk_api_...", "production", "my-service")
cfg, err := client.Config().Get(ctx, "my-service")
if err != nil {
    var notFound *smplkit.SmplNotFoundError
    if errors.As(err, &notFound) {
        // handle not found
    }
    return err
}
fmt.Println(cfg.Name)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NormalizeLoggerName added in v1.3.13

func NormalizeLoggerName(name string) string

NormalizeLoggerName normalizes a logger name to the canonical dot-separated, lowercase form. For example: "myapp/database:queries" becomes "myapp.database.queries".

Types

type BooleanFlagHandle added in v1.3.13

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

BooleanFlagHandle is a typed handle for a boolean flag.

func (*BooleanFlagHandle) Get added in v1.3.13

func (h *BooleanFlagHandle) Get(ctx context.Context, contexts ...Context) bool

Get evaluates the flag and returns a typed boolean value.

func (*BooleanFlagHandle) OnChange added in v1.3.13

func (h *BooleanFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type ChangeListenerOption added in v1.2.5

type ChangeListenerOption func(*changeListenerConfig)

ChangeListenerOption configures an OnChange listener.

func WithConfigID added in v1.3.26

func WithConfigID(id string) ChangeListenerOption

WithConfigID restricts the listener to changes in the given config.

func WithItemKey added in v1.2.5

func WithItemKey(key string) ChangeListenerOption

WithItemKey restricts the listener to changes of the given item key.

type Client

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

Client is the top-level entry point for the smplkit SDK.

Create one with NewClient and access sub-clients via accessor methods:

client, err := smplkit.NewClient("sk_api_...", "production", "my-service")
cfgs, err := client.Config().Management().List(ctx)

func NewClient

func NewClient(apiKey string, environment string, service string, opts ...ClientOption) (*Client, error)

NewClient creates a new smplkit API client.

The apiKey is used for Bearer token authentication on every request. Pass an empty string to resolve the API key automatically from the SMPLKIT_API_KEY environment variable or the ~/.smplkit config file.

The environment is required; pass an empty string to resolve from SMPLKIT_ENVIRONMENT.

The service is required; pass an empty string to resolve from SMPLKIT_SERVICE.

Use ClientOption functions to customize the base URL, timeout, or HTTP client.

func (*Client) Close added in v1.3.13

func (c *Client) Close() error

Close releases all resources held by the client and its sub-clients.

func (*Client) Config

func (c *Client) Config() *ConfigClient

Config returns the sub-client for config management operations.

func (*Client) Environment added in v1.2.1

func (c *Client) Environment() string

Environment returns the resolved environment name.

func (*Client) Flags added in v1.2.0

func (c *Client) Flags() *FlagsClient

Flags returns the sub-client for flags management and runtime operations.

func (*Client) Logging added in v1.3.13

func (c *Client) Logging() *LoggingClient

Logging returns the sub-client for logging management and runtime operations.

func (*Client) Service added in v1.2.1

func (c *Client) Service() string

Service returns the resolved service name.

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures the Client. Pass options to NewClient.

func DisableTelemetry added in v1.3.25

func DisableTelemetry() ClientOption

DisableTelemetry disables internal SDK usage telemetry. By default, the SDK reports anonymous usage metrics to the smplkit service.

func WithBaseURL

func WithBaseURL(url string) ClientOption

WithBaseURL overrides the default API base URL.

func WithHTTPClient

func WithHTTPClient(c *http.Client) ClientOption

WithHTTPClient replaces the default HTTP client entirely. When set, the WithTimeout option is ignored because the caller controls the client.

func WithTimeout

func WithTimeout(d time.Duration) ClientOption

WithTimeout sets the HTTP request timeout. The default is 30 seconds.

type Config

type Config struct {
	// ID is the config identifier (e.g. "user_service").
	ID string
	// Name is the display name for the config.
	Name string
	// Description is an optional description of the config.
	Description *string
	// Parent is the parent config ID, or nil for root configs.
	Parent *string
	// Items holds the base configuration values.
	Items map[string]interface{}
	// Environments maps environment names to their value overrides.
	Environments map[string]map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Config represents a configuration resource from the smplkit platform.

func (*Config) Save added in v1.3.13

func (c *Config) Save(ctx context.Context) error

Save persists the config to the server. The Config instance is updated with the server response.

type ConfigChangeEvent added in v1.1.1

type ConfigChangeEvent struct {
	// ConfigID is the config ID that changed (e.g. "user_service").
	ConfigID string
	// ItemKey is the item key within the config that changed.
	ItemKey string
	// OldValue is the value before the change (nil if the key was new).
	OldValue interface{}
	// NewValue is the value after the change (nil if the key was removed).
	NewValue interface{}
	// Source is "websocket" for server-pushed changes or "manual" for Refresh calls.
	Source string
}

ConfigChangeEvent describes a single value change detected on refresh.

type ConfigClient

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

ConfigClient provides operations for config resources and resolved value access. Obtain one via Client.Config().

func (*ConfigClient) Get

func (c *ConfigClient) Get(ctx context.Context, id string) (map[string]interface{}, error)

Get returns the resolved config values for the given ID.

func (*ConfigClient) GetBool added in v1.2.5

func (c *ConfigClient) GetBool(ctx context.Context, configID, itemKey string, defaultVal ...bool) (bool, error)

GetBool returns the resolved bool value for (configID, itemKey).

func (*ConfigClient) GetInt added in v1.2.5

func (c *ConfigClient) GetInt(ctx context.Context, configID, itemKey string, defaultVal ...int) (int, error)

GetInt returns the resolved int value for (configID, itemKey).

func (*ConfigClient) GetInto added in v1.3.35

func (c *ConfigClient) GetInto(ctx context.Context, id string, target interface{}) error

GetInto resolves the config and unmarshals it into the target struct. The target must be a pointer to a struct. Dot-notation keys (e.g. "database.host") are expanded into nested structures before unmarshaling.

func (*ConfigClient) GetString added in v1.2.5

func (c *ConfigClient) GetString(ctx context.Context, configID, itemKey string, defaultVal ...string) (string, error)

GetString returns the resolved string value for (configID, itemKey).

func (*ConfigClient) GetValue added in v1.2.1

func (c *ConfigClient) GetValue(ctx context.Context, configID string, itemKey ...string) (interface{}, error)

GetValue reads a resolved config value.

func (*ConfigClient) Management added in v1.3.35

func (c *ConfigClient) Management() *ConfigManagement

Management returns the sub-object for config CRUD operations.

func (*ConfigClient) OnChange added in v1.2.5

func (c *ConfigClient) OnChange(cb func(*ConfigChangeEvent), opts ...ChangeListenerOption)

OnChange registers a listener that fires when a config value changes (on Refresh). Use WithConfigID and/or WithItemKey to scope the listener.

func (*ConfigClient) Refresh added in v1.2.5

func (c *ConfigClient) Refresh(ctx context.Context) error

Refresh re-fetches all configs and resolves current values. OnChange listeners fire for any values that changed.

func (*ConfigClient) Subscribe added in v1.3.13

func (c *ConfigClient) Subscribe(ctx context.Context, id string) (*LiveConfig, error)

Subscribe returns a LiveConfig whose Value() always reflects the latest resolved values for the given config ID.

type ConfigManagement added in v1.3.35

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

ConfigManagement provides CRUD operations for config resources. Obtain one via ConfigClient.Management().

func (*ConfigManagement) Delete added in v1.3.35

func (m *ConfigManagement) Delete(ctx context.Context, id string) error

Delete removes a config by its ID.

func (*ConfigManagement) Get added in v1.3.35

func (m *ConfigManagement) Get(ctx context.Context, id string) (*Config, error)

Get retrieves a config by its ID. Returns SmplNotFoundError if no match.

func (*ConfigManagement) List added in v1.3.35

func (m *ConfigManagement) List(ctx context.Context) ([]*Config, error)

List returns all configs for the account.

func (*ConfigManagement) New added in v1.3.35

func (m *ConfigManagement) New(id string, opts ...ConfigOption) *Config

New creates an unsaved Config with the given ID. Call Save(ctx) to persist. If name is not provided via WithConfigName, it is auto-generated from the ID.

type ConfigOption added in v1.3.13

type ConfigOption func(*Config)

ConfigOption configures an unsaved Config returned by ConfigClient.New.

func WithConfigDescription added in v1.3.13

func WithConfigDescription(desc string) ConfigOption

WithConfigDescription sets the description for a config.

func WithConfigEnvironments added in v1.3.16

func WithConfigEnvironments(envs map[string]map[string]interface{}) ConfigOption

WithConfigEnvironments sets the environment-specific overrides for a config.

func WithConfigItems added in v1.3.16

func WithConfigItems(items map[string]interface{}) ConfigOption

WithConfigItems sets the base configuration values for a config.

func WithConfigName added in v1.3.13

func WithConfigName(name string) ConfigOption

WithConfigName sets the display name for a config.

func WithConfigParent added in v1.3.13

func WithConfigParent(parentID string) ConfigOption

WithConfigParent sets the parent config UUID for inheritance.

type Context added in v1.2.0

type Context struct {
	// Type is the context type (e.g. "user", "account").
	Type string
	// Key is the unique identifier for this entity.
	Key string
	// Name is an optional display name.
	Name string
	// Attributes holds arbitrary key-value data for rule evaluation.
	Attributes map[string]interface{}
}

Context represents a typed evaluation context entity.

Each Context identifies an entity (user, account, device, etc.) by type and key, with optional attributes that JSON Logic rules can target.

ctx := smplkit.NewContext("user", "user-123", map[string]any{
    "plan": "enterprise",
    "firstName": "Alice",
})

func NewContext added in v1.2.0

func NewContext(contextType, key string, attrs map[string]interface{}, opts ...ContextOption) Context

NewContext creates a new evaluation context. The optional attrs map provides attributes for JSON Logic rule evaluation. Use WithName to set a display name, or WithAttr to add individual attributes.

// Using a map:
ctx := smplkit.NewContext("user", "user-123", map[string]any{"plan": "enterprise"})

// Using functional options:
ctx := smplkit.NewContext("user", "user-123", nil,
    smplkit.WithName("Alice"),
    smplkit.WithAttr("plan", "enterprise"),
)

type ContextOption added in v1.2.0

type ContextOption func(*Context)

ContextOption configures a Context. Use WithName and WithAttr.

func WithAttr added in v1.2.0

func WithAttr(key string, value interface{}) ContextOption

WithAttr adds a single attribute to a Context.

func WithName added in v1.2.0

func WithName(name string) ContextOption

WithName sets the display name on a Context.

type ContextType added in v1.2.0

type ContextType struct {
	// ID is the context type identifier.
	ID string
	// Name is the display name.
	Name string
	// Attributes holds the context type's attribute definitions.
	Attributes map[string]interface{}
}

ContextType represents a context type resource from the management API.

type ErrorDetail added in v1.3.7

type ErrorDetail struct {
	Status string      `json:"status,omitempty"`
	Title  string      `json:"title,omitempty"`
	Detail string      `json:"detail,omitempty"`
	Source ErrorSource `json:"source,omitempty"`
}

ErrorDetail holds a single JSON:API error object.

type ErrorSource added in v1.3.7

type ErrorSource struct {
	Pointer string `json:"pointer,omitempty"`
}

ErrorSource identifies the source of a JSON:API error.

type Flag added in v1.2.0

type Flag struct {
	// ID is the flag identifier (e.g. "dark-mode").
	ID string
	// Name is the display name for the flag.
	Name string
	// Type is the value type (BOOLEAN, STRING, NUMERIC, JSON).
	Type string
	// Default is the default value for the flag.
	Default interface{}
	// Values is the closed set of possible values (constrained), or nil (unconstrained).
	Values *[]FlagValue
	// Description is an optional description of the flag.
	Description *string
	// Environments maps environment names to their configuration.
	Environments map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Flag represents a flag resource from the smplkit platform.

func (*Flag) AddRule added in v1.2.0

func (f *Flag) AddRule(builtRule map[string]interface{}) error

AddRule appends a rule to the specified environment. The builtRule must include an "environment" key (use NewRule(...).Environment("env").Build()). Call Save(ctx) to persist.

func (*Flag) ClearRules added in v1.3.13

func (f *Flag) ClearRules(envKey string)

ClearRules removes all rules for the specified environment. Call Save(ctx) to persist.

func (*Flag) Save added in v1.3.13

func (f *Flag) Save(ctx context.Context) error

Save persists the flag to the server. The Flag instance is updated with the server response.

func (*Flag) SetEnvironmentDefault added in v1.3.13

func (f *Flag) SetEnvironmentDefault(envKey string, defaultVal interface{})

SetEnvironmentDefault sets the environment-specific default value. Call Save(ctx) to persist.

func (*Flag) SetEnvironmentEnabled added in v1.3.13

func (f *Flag) SetEnvironmentEnabled(envKey string, enabled bool)

SetEnvironmentEnabled sets the enabled flag for an environment. Call Save(ctx) to persist.

type FlagChangeEvent added in v1.2.0

type FlagChangeEvent struct {
	// ID is the flag ID that changed.
	ID string
	// Source is "websocket" or "manual".
	Source string
}

FlagChangeEvent describes a flag definition change.

type FlagOption added in v1.3.13

type FlagOption func(*Flag)

FlagOption configures an unsaved Flag returned by factory methods.

func WithFlagDescription added in v1.3.13

func WithFlagDescription(desc string) FlagOption

WithFlagDescription sets the description for a flag.

func WithFlagName added in v1.3.13

func WithFlagName(name string) FlagOption

WithFlagName sets the display name for a flag.

func WithFlagValues added in v1.3.13

func WithFlagValues(values []FlagValue) FlagOption

WithFlagValues sets the closed value set for a flag (constrained).

type FlagStats added in v1.2.0

type FlagStats struct {
	// CacheHits is the number of evaluations served from cache.
	CacheHits int
	// CacheMisses is the number of evaluations that required computation.
	CacheMisses int
}

FlagStats holds runtime statistics for the flags subsystem.

type FlagType added in v1.2.0

type FlagType string

FlagType represents the value type of a flag.

const (
	// FlagTypeBoolean represents a boolean flag.
	FlagTypeBoolean FlagType = "BOOLEAN"
	// FlagTypeString represents a string flag.
	FlagTypeString FlagType = "STRING"
	// FlagTypeNumeric represents a numeric flag.
	FlagTypeNumeric FlagType = "NUMERIC"
	// FlagTypeJSON represents a JSON flag.
	FlagTypeJSON FlagType = "JSON"
)

type FlagValue added in v1.2.0

type FlagValue struct {
	Name  string
	Value interface{}
}

FlagValue represents a named value in a flag's value set.

type FlagsClient added in v1.2.0

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

FlagsClient provides management and runtime operations for flag resources. Obtain one via Client.Flags().

func (*FlagsClient) BooleanFlag added in v1.3.13

func (c *FlagsClient) BooleanFlag(key string, defaultValue bool) *BooleanFlagHandle

BooleanFlag returns a typed handle for a boolean flag.

func (*FlagsClient) ConnectionStatus added in v1.2.0

func (c *FlagsClient) ConnectionStatus() string

ConnectionStatus returns the current real-time connection status.

func (*FlagsClient) Disconnect added in v1.2.0

func (c *FlagsClient) Disconnect(ctx context.Context)

Disconnect stops real-time updates and releases runtime resources.

func (*FlagsClient) Evaluate added in v1.2.0

func (c *FlagsClient) Evaluate(ctx context.Context, key string, environment string, contexts []Context) interface{}

Evaluate evaluates a flag with the given environment and contexts.

func (*FlagsClient) FlushContexts added in v1.2.0

func (c *FlagsClient) FlushContexts(ctx context.Context)

FlushContexts sends any pending context registrations to the server immediately.

func (*FlagsClient) JsonFlag added in v1.2.0

func (c *FlagsClient) JsonFlag(key string, defaultValue map[string]interface{}) *JsonFlagHandle

JsonFlag returns a typed handle for a JSON flag.

func (*FlagsClient) Management added in v1.3.35

func (c *FlagsClient) Management() *FlagsManagement

Management returns the sub-object for flag CRUD operations.

func (*FlagsClient) NumberFlag added in v1.2.0

func (c *FlagsClient) NumberFlag(key string, defaultValue float64) *NumberFlagHandle

NumberFlag returns a typed handle for a numeric flag.

func (*FlagsClient) OnChange added in v1.2.0

func (c *FlagsClient) OnChange(cb func(*FlagChangeEvent))

OnChange registers a global change listener that fires for any flag change.

func (*FlagsClient) OnChangeKey added in v1.3.13

func (c *FlagsClient) OnChangeKey(key string, cb func(*FlagChangeEvent))

OnChangeKey registers a key-scoped change listener that fires only when the specified flag key changes.

func (*FlagsClient) Refresh added in v1.2.0

func (c *FlagsClient) Refresh(ctx context.Context) error

Refresh fetches the latest flag definitions from the server.

func (*FlagsClient) Register added in v1.2.0

func (c *FlagsClient) Register(ctx context.Context, contexts ...Context)

Register explicitly registers context(s) with the server.

func (*FlagsClient) SetContextProvider added in v1.2.0

func (c *FlagsClient) SetContextProvider(fn func(ctx context.Context) []Context)

SetContextProvider registers a function that provides evaluation contexts.

func (*FlagsClient) Stats added in v1.2.0

func (c *FlagsClient) Stats() FlagStats

Stats returns runtime statistics.

func (*FlagsClient) StringFlag added in v1.2.0

func (c *FlagsClient) StringFlag(key string, defaultValue string) *StringFlagHandle

StringFlag returns a typed handle for a string flag.

type FlagsManagement added in v1.3.35

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

FlagsManagement provides CRUD operations for flag resources. Obtain one via FlagsClient.Management().

func (*FlagsManagement) CreateContextType added in v1.3.35

func (m *FlagsManagement) CreateContextType(ctx context.Context, id string, name string) (*ContextType, error)

CreateContextType creates a new context type.

func (*FlagsManagement) Delete added in v1.3.35

func (m *FlagsManagement) Delete(ctx context.Context, id string) error

Delete removes a flag by its ID.

func (*FlagsManagement) DeleteContextType added in v1.3.35

func (m *FlagsManagement) DeleteContextType(ctx context.Context, ctID string) error

DeleteContextType deletes a context type by its ID.

func (*FlagsManagement) Get added in v1.3.35

func (m *FlagsManagement) Get(ctx context.Context, id string) (*Flag, error)

Get retrieves a flag by its ID. Returns SmplNotFoundError if no match.

func (*FlagsManagement) List added in v1.3.35

func (m *FlagsManagement) List(ctx context.Context) ([]*Flag, error)

List returns all flags for the account.

func (*FlagsManagement) ListContextTypes added in v1.3.35

func (m *FlagsManagement) ListContextTypes(ctx context.Context) ([]*ContextType, error)

ListContextTypes lists all context types.

func (*FlagsManagement) ListContexts added in v1.3.35

func (m *FlagsManagement) ListContexts(ctx context.Context, contextTypeKey string) ([]map[string]interface{}, error)

ListContexts lists context instances filtered by context type key.

func (*FlagsManagement) NewBooleanFlag added in v1.3.35

func (m *FlagsManagement) NewBooleanFlag(id string, defaultValue bool, opts ...FlagOption) *Flag

NewBooleanFlag creates an unsaved boolean flag. Call Save(ctx) to persist. If name is not provided via WithFlagName, it is auto-generated from the ID.

func (*FlagsManagement) NewJsonFlag added in v1.3.35

func (m *FlagsManagement) NewJsonFlag(id string, defaultValue map[string]interface{}, opts ...FlagOption) *Flag

NewJsonFlag creates an unsaved JSON flag. Call Save(ctx) to persist.

func (*FlagsManagement) NewNumberFlag added in v1.3.35

func (m *FlagsManagement) NewNumberFlag(id string, defaultValue float64, opts ...FlagOption) *Flag

NewNumberFlag creates an unsaved numeric flag. Call Save(ctx) to persist.

func (*FlagsManagement) NewStringFlag added in v1.3.35

func (m *FlagsManagement) NewStringFlag(id string, defaultValue string, opts ...FlagOption) *Flag

NewStringFlag creates an unsaved string flag. Call Save(ctx) to persist.

func (*FlagsManagement) UpdateContextType added in v1.3.35

func (m *FlagsManagement) UpdateContextType(ctx context.Context, ctID string, attributes map[string]interface{}) (*ContextType, error)

UpdateContextType updates a context type's attributes.

type FlagsRuntime added in v1.2.0

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

FlagsRuntime holds the runtime state for the flags subsystem. Access it via FlagsClient methods like BooleanFlag, Disconnect, etc.

func (*FlagsRuntime) BooleanFlag added in v1.3.13

func (rt *FlagsRuntime) BooleanFlag(key string, defaultValue bool) *BooleanFlagHandle

BooleanFlag returns a typed handle for a boolean flag.

func (*FlagsRuntime) ConnectionStatus added in v1.2.0

func (rt *FlagsRuntime) ConnectionStatus() string

ConnectionStatus returns the current real-time connection status.

func (*FlagsRuntime) Evaluate added in v1.2.0

func (rt *FlagsRuntime) Evaluate(ctx context.Context, key string, environment string, contexts []Context) interface{}

Evaluate evaluates a flag with the given environment and contexts.

func (*FlagsRuntime) FlushContexts added in v1.2.0

func (rt *FlagsRuntime) FlushContexts(ctx context.Context)

FlushContexts sends any pending context registrations to the server immediately.

func (*FlagsRuntime) JsonFlag added in v1.2.0

func (rt *FlagsRuntime) JsonFlag(key string, defaultValue map[string]interface{}) *JsonFlagHandle

JsonFlag returns a typed handle for a JSON flag.

func (*FlagsRuntime) NumberFlag added in v1.2.0

func (rt *FlagsRuntime) NumberFlag(key string, defaultValue float64) *NumberFlagHandle

NumberFlag returns a typed handle for a numeric flag.

func (*FlagsRuntime) OnChange added in v1.2.0

func (rt *FlagsRuntime) OnChange(cb func(*FlagChangeEvent))

OnChange registers a global change listener.

func (*FlagsRuntime) OnChangeKey added in v1.3.13

func (rt *FlagsRuntime) OnChangeKey(key string, cb func(*FlagChangeEvent))

OnChangeKey registers a key-scoped change listener that fires only when the specified flag key changes.

func (*FlagsRuntime) Refresh added in v1.2.0

func (rt *FlagsRuntime) Refresh(ctx context.Context) error

Refresh fetches the latest flag definitions from the server. Change listeners fire after the refresh completes.

func (*FlagsRuntime) Register added in v1.2.0

func (rt *FlagsRuntime) Register(ctx context.Context, contexts ...Context)

Register explicitly registers context(s) with the server.

func (*FlagsRuntime) SetContextProvider added in v1.2.0

func (rt *FlagsRuntime) SetContextProvider(fn func(ctx context.Context) []Context)

SetContextProvider registers a function that provides evaluation contexts.

func (*FlagsRuntime) Stats added in v1.2.0

func (rt *FlagsRuntime) Stats() FlagStats

Stats returns runtime statistics.

func (*FlagsRuntime) StringFlag added in v1.2.0

func (rt *FlagsRuntime) StringFlag(key string, defaultValue string) *StringFlagHandle

StringFlag returns a typed handle for a string flag.

type JsonFlagHandle added in v1.2.0

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

JsonFlagHandle is a typed handle for a JSON flag.

func (*JsonFlagHandle) Get added in v1.2.0

func (h *JsonFlagHandle) Get(ctx context.Context, contexts ...Context) map[string]interface{}

Get evaluates the flag and returns a typed map value.

func (*JsonFlagHandle) OnChange added in v1.2.0

func (h *JsonFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type LiveConfig added in v1.3.13

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

LiveConfig is a handle returned by Subscribe that always reflects the latest resolved values for a config ID.

func (*LiveConfig) Value added in v1.3.13

func (lc *LiveConfig) Value() map[string]interface{}

Value returns the latest resolved values for this config.

func (*LiveConfig) ValueInto added in v1.3.13

func (lc *LiveConfig) ValueInto(target interface{}) error

ValueInto unmarshals the latest resolved values into the target struct. The target must be a pointer to a struct. Dot-notation keys (e.g. "database.host") are expanded into nested structures before unmarshaling.

type LogGroup added in v1.3.13

type LogGroup struct {
	// ID is the log group identifier.
	ID string
	// Name is the display name for the log group.
	Name string
	// Level is the base log level (nil = inherit).
	Level *LogLevel
	// Group is the parent group ID (nil = no parent).
	Group *string
	// Environments maps environment names to their configuration.
	Environments map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

LogGroup represents a log group resource from the smplkit platform.

func (*LogGroup) ClearAllEnvironmentLevels added in v1.3.13

func (g *LogGroup) ClearAllEnvironmentLevels()

ClearAllEnvironmentLevels clears all environment-specific levels. Call Save to persist.

func (*LogGroup) ClearEnvironmentLevel added in v1.3.13

func (g *LogGroup) ClearEnvironmentLevel(env string)

ClearEnvironmentLevel clears the log level for a specific environment. Call Save to persist.

func (*LogGroup) ClearLevel added in v1.3.13

func (g *LogGroup) ClearLevel()

ClearLevel clears the base log level. Call Save to persist.

func (*LogGroup) Save added in v1.3.13

func (g *LogGroup) Save(ctx context.Context) error

Save persists the log group to the server. The LogGroup instance is updated with the server response.

func (*LogGroup) SetEnvironmentLevel added in v1.3.13

func (g *LogGroup) SetEnvironmentLevel(env string, level LogLevel)

SetEnvironmentLevel sets the log level for a specific environment. Call Save to persist.

func (*LogGroup) SetLevel added in v1.3.13

func (g *LogGroup) SetLevel(level LogLevel)

SetLevel sets the base log level. Call Save to persist.

type LogGroupOption added in v1.3.13

type LogGroupOption func(*LogGroup)

LogGroupOption configures an unsaved LogGroup returned by LoggingClient.NewGroup.

func WithLogGroupName added in v1.3.13

func WithLogGroupName(name string) LogGroupOption

WithLogGroupName sets the display name for a log group.

func WithLogGroupParent added in v1.3.13

func WithLogGroupParent(groupID string) LogGroupOption

WithLogGroupParent sets the parent group UUID.

type LogLevel added in v1.3.13

type LogLevel string

LogLevel represents a smplkit canonical log level.

const (
	LogLevelTrace  LogLevel = "TRACE"
	LogLevelDebug  LogLevel = "DEBUG"
	LogLevelInfo   LogLevel = "INFO"
	LogLevelWarn   LogLevel = "WARN"
	LogLevelError  LogLevel = "ERROR"
	LogLevelFatal  LogLevel = "FATAL"
	LogLevelSilent LogLevel = "SILENT"
)

type Logger added in v1.3.13

type Logger struct {
	// ID is the logger identifier.
	ID string
	// Name is the display name for the logger.
	Name string
	// Level is the base log level (nil = inherit).
	Level *LogLevel
	// Group is the group ID (nil = no group).
	Group *string
	// Managed indicates whether smplkit controls this logger's level.
	Managed bool
	// Sources holds source metadata.
	Sources []map[string]interface{}
	// Environments maps environment names to their configuration.
	Environments map[string]interface{}
	// CreatedAt is the creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Logger represents a logger resource from the smplkit platform.

func (*Logger) ClearAllEnvironmentLevels added in v1.3.13

func (l *Logger) ClearAllEnvironmentLevels()

ClearAllEnvironmentLevels clears all environment-specific levels. Call Save to persist.

func (*Logger) ClearEnvironmentLevel added in v1.3.13

func (l *Logger) ClearEnvironmentLevel(env string)

ClearEnvironmentLevel clears the log level for a specific environment. Call Save to persist.

func (*Logger) ClearLevel added in v1.3.13

func (l *Logger) ClearLevel()

ClearLevel clears the base log level. Call Save to persist.

func (*Logger) Save added in v1.3.13

func (l *Logger) Save(ctx context.Context) error

Save persists the logger to the server. The Logger instance is updated with the server response.

func (*Logger) SetEnvironmentLevel added in v1.3.13

func (l *Logger) SetEnvironmentLevel(env string, level LogLevel)

SetEnvironmentLevel sets the log level for a specific environment. Call Save to persist.

func (*Logger) SetLevel added in v1.3.13

func (l *Logger) SetLevel(level LogLevel)

SetLevel sets the base log level. Call Save to persist.

type LoggerChangeEvent added in v1.3.13

type LoggerChangeEvent struct {
	// ID is the logger ID that changed.
	ID string
	// Level is the new resolved level (nil if deleted).
	Level *LogLevel
	// Source is "websocket" or "refresh".
	Source string
}

LoggerChangeEvent describes a logger definition change.

type LoggerOption added in v1.3.13

type LoggerOption func(*Logger)

LoggerOption configures an unsaved Logger returned by LoggingClient.New.

func WithLoggerManaged added in v1.3.13

func WithLoggerManaged(managed bool) LoggerOption

WithLoggerManaged sets whether smplkit controls this logger's level.

func WithLoggerName added in v1.3.13

func WithLoggerName(name string) LoggerOption

WithLoggerName sets the display name for a logger.

type LoggingClient added in v1.3.13

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

LoggingClient provides management and runtime operations for logging resources. Obtain one via Client.Logging().

func (*LoggingClient) Management added in v1.3.35

func (c *LoggingClient) Management() *LoggingManagement

Management returns the sub-object for logger and log group CRUD operations.

func (*LoggingClient) OnChange added in v1.3.13

func (c *LoggingClient) OnChange(cb func(*LoggerChangeEvent))

OnChange registers a global change listener that fires for any logger change.

func (*LoggingClient) OnChangeKey added in v1.3.13

func (c *LoggingClient) OnChangeKey(key string, cb func(*LoggerChangeEvent))

OnChangeKey registers a key-scoped change listener.

func (*LoggingClient) RegisterAdapter added in v1.3.20

func (c *LoggingClient) RegisterAdapter(adapter adapters.LoggingAdapter)

RegisterAdapter registers a logging adapter. Must be called before Start(). At least one adapter must be registered for runtime features to function.

func (*LoggingClient) RegisterLogger added in v1.3.13

func (c *LoggingClient) RegisterLogger(name string, level LogLevel)

RegisterLogger explicitly registers a logger name for smplkit management. Call before or after Start().

func (*LoggingClient) Start added in v1.3.13

func (c *LoggingClient) Start(ctx context.Context) error

Start initializes the logging runtime and begins listening for level changes. Safe to call multiple times; only the first call takes effect.

type LoggingManagement added in v1.3.35

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

LoggingManagement provides CRUD operations for logger and log group resources. Obtain one via LoggingClient.Management().

func (*LoggingManagement) Delete added in v1.3.35

func (m *LoggingManagement) Delete(ctx context.Context, id string) error

Delete removes a logger by its ID.

func (*LoggingManagement) DeleteGroup added in v1.3.35

func (m *LoggingManagement) DeleteGroup(ctx context.Context, id string) error

DeleteGroup removes a log group by its ID.

func (*LoggingManagement) Get added in v1.3.35

func (m *LoggingManagement) Get(ctx context.Context, id string) (*Logger, error)

Get retrieves a logger by its ID.

func (*LoggingManagement) GetGroup added in v1.3.35

func (m *LoggingManagement) GetGroup(ctx context.Context, id string) (*LogGroup, error)

GetGroup retrieves a log group by its ID.

func (*LoggingManagement) List added in v1.3.35

func (m *LoggingManagement) List(ctx context.Context) ([]*Logger, error)

List returns all loggers for the account.

func (*LoggingManagement) ListGroups added in v1.3.35

func (m *LoggingManagement) ListGroups(ctx context.Context) ([]*LogGroup, error)

ListGroups returns all log groups for the account.

func (*LoggingManagement) New added in v1.3.35

func (m *LoggingManagement) New(id string, opts ...LoggerOption) *Logger

New creates an unsaved Logger with the given ID. Call Save(ctx) to persist. If name is not provided via WithLoggerName, it is auto-generated from the ID.

func (*LoggingManagement) NewGroup added in v1.3.35

func (m *LoggingManagement) NewGroup(id string, opts ...LogGroupOption) *LogGroup

NewGroup creates an unsaved LogGroup with the given ID. Call Save(ctx) to persist.

type NumberFlagHandle added in v1.2.0

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

NumberFlagHandle is a typed handle for a numeric flag.

func (*NumberFlagHandle) Get added in v1.2.0

func (h *NumberFlagHandle) Get(ctx context.Context, contexts ...Context) float64

Get evaluates the flag and returns a typed float64 value.

func (*NumberFlagHandle) OnChange added in v1.2.0

func (h *NumberFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

type Rule added in v1.2.0

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

Rule is a fluent builder for JSON Logic rule dicts.

rule := smplkit.NewRule("Enable for enterprise users").
    When("user.plan", "==", "enterprise").
    Serve(true).
    Build()

func NewRule added in v1.2.0

func NewRule(description string) *Rule

NewRule creates a new rule builder with the given description.

func (*Rule) Build added in v1.2.0

func (r *Rule) Build() map[string]interface{}

Build finalizes and returns the rule as a plain map.

func (*Rule) Environment added in v1.2.0

func (r *Rule) Environment(envKey string) *Rule

Environment tags this rule with an environment key (required for AddRule).

func (*Rule) Serve added in v1.2.0

func (r *Rule) Serve(value interface{}) *Rule

Serve sets the value returned when this rule matches.

func (*Rule) When added in v1.2.0

func (r *Rule) When(variable, op string, value interface{}) *Rule

When adds a condition. Multiple calls are AND'd. Supported operators: ==, !=, >, <, >=, <=, in, contains.

type SmplConflictError

type SmplConflictError struct {
	SmplError
}

SmplConflictError is raised when an operation conflicts with the current resource state.

func (*SmplConflictError) Error

func (e *SmplConflictError) Error() string

Error implements the error interface.

func (*SmplConflictError) Unwrap

func (e *SmplConflictError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplConnectionError

type SmplConnectionError struct {
	SmplError
}

SmplConnectionError is raised when a network request fails.

func (*SmplConnectionError) Error

func (e *SmplConnectionError) Error() string

Error implements the error interface.

func (*SmplConnectionError) Unwrap

func (e *SmplConnectionError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplError

type SmplError struct {
	Message      string
	StatusCode   int
	ResponseBody string
	Errors       []ErrorDetail
}

SmplError is the base error type for all smplkit SDK errors. All specific error types embed SmplError, so errors.As(err, &SmplError{}) will match any SDK error.

func (*SmplError) Error

func (e *SmplError) Error() string

Error implements the error interface.

type SmplNotFoundError

type SmplNotFoundError struct {
	SmplError
}

SmplNotFoundError is raised when a requested resource does not exist.

func (*SmplNotFoundError) Error

func (e *SmplNotFoundError) Error() string

Error implements the error interface.

func (*SmplNotFoundError) Unwrap

func (e *SmplNotFoundError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplTimeoutError

type SmplTimeoutError struct {
	SmplError
}

SmplTimeoutError is raised when an operation exceeds its timeout.

func (*SmplTimeoutError) Error

func (e *SmplTimeoutError) Error() string

Error implements the error interface.

func (*SmplTimeoutError) Unwrap

func (e *SmplTimeoutError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type SmplValidationError

type SmplValidationError struct {
	SmplError
}

SmplValidationError is raised when the server rejects a request due to validation errors.

func (*SmplValidationError) Error

func (e *SmplValidationError) Error() string

Error implements the error interface.

func (*SmplValidationError) Unwrap

func (e *SmplValidationError) Unwrap() error

Unwrap returns the embedded SmplError for errors.Is/errors.As support.

type StringFlagHandle added in v1.2.0

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

StringFlagHandle is a typed handle for a string flag.

func (*StringFlagHandle) Get added in v1.2.0

func (h *StringFlagHandle) Get(ctx context.Context, contexts ...Context) string

Get evaluates the flag and returns a typed string value.

func (*StringFlagHandle) OnChange added in v1.2.0

func (h *StringFlagHandle) OnChange(cb func(*FlagChangeEvent))

OnChange registers a flag-specific change listener.

Directories

Path Synopsis
internal
generated/app
Package app contains auto-generated types from the app OpenAPI spec.
Package app contains auto-generated types from the app OpenAPI spec.
generated/config
Package config contains auto-generated types from the config OpenAPI spec.
Package config contains auto-generated types from the config OpenAPI spec.
generated/flags
Package flags provides primitives to interact with the openapi HTTP API.
Package flags provides primitives to interact with the openapi HTTP API.
generated/logging
Package logging provides primitives to interact with the openapi HTTP API.
Package logging provides primitives to interact with the openapi HTTP API.
logging

Jump to

Keyboard shortcuts

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