smplkit

package module
v3.0.121 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2026 License: MIT Imports: 33 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/v3

Requirements

  • Go 1.24+

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

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

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

    // APIKey, Environment, Service may also come from SMPLKIT_* env vars
    // or ~/.smplkit; explicit Config fields take precedence.
    client, err := smplkit.NewClient(smplkit.Config{
        APIKey:      "sk_api_...",
        Environment: "production",
        Service:     "my-service",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // ── Runtime: resolve config values ──────────────────────────────────
    // Get returns a LiveConfig proxy; reads always reflect the latest
    // values pushed by the WebSocket.
    cfg, err := client.Config().Get(ctx, "user_service")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(cfg.Value()["timeout"])

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

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

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

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

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

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

client.Manage() exposes the eight management namespaces (Config(), Flags(), Loggers(), LogGroups(), Contexts(), ContextTypes(), Environments(), AccountSettings()). For setup scripts and CI jobs that don't need the runtime, construct a management-only client with no side effects via smplkit.NewManagementClient(smplkit.ManagementConfig{...}).

Configuration

All settings are resolved from four sources, in order of precedence:

  1. Constructor arguments — explicit Config fields, highest priority.
  2. Environment variables — e.g. SMPLKIT_API_KEY, SMPLKIT_ENVIRONMENT.
  3. Configuration file (~/.smplkit) — INI-format with profile support.
  4. Defaults — built-in SDK defaults.
Configuration File

The ~/.smplkit file supports a [common] section (applied to all profiles) and named profiles:

[common]
environment = production
service = my-app

[default]
api_key = sk_api_abc123

[local]
base_domain = localhost
scheme = http
api_key = sk_api_local_xyz
environment = development
debug = true
Constructor Examples
// Use a named profile
client, err := smplkit.NewClient(smplkit.Config{Profile: "local"})

// Or configure explicitly
client, err := smplkit.NewClient(smplkit.Config{
    APIKey:      "sk_api_...",
    Environment: "production",
    Service:     "my-service",
})

For the complete configuration reference, see the Configuration Guide.

Error Handling

All SDK errors extend *smplkit.Error and support errors.Is() / errors.As():

import "errors"

cfg, err := client.Manage().Config().Get(ctx, "nonexistent")
if err != nil {
    var notFound *smplkit.NotFoundError
    if errors.As(err, &notFound) {
        fmt.Println("Not found:", notFound.Base.Message)
    } else {
        fmt.Println("Error:", err)
    }
}
Error Cause
NotFoundError HTTP 404 — resource not found
ConflictError HTTP 409 — conflict
ValidationError HTTP 422 — validation error
TimeoutError Request timed out
ConnectionError Network connectivity issue
Error Any other SDK error

Smpl-prefixed aliases (SmplError, SmplNotFoundError, etc.) exist for cross-SDK familiarity but the unprefixed names are canonical.

Feature Flags

Full management + runtime client with real-time WebSocket updates and a typed-handle evaluation API.

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

// 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)
}

// Per-environment defaults and rules — env="" targets the base default,
// non-empty scopes to that environment.
flag.SetDefault(true, "staging")
if err := flag.AddRule(smplkit.NewRule("Enable for enterprise").
    Environment("staging").
    When("user.plan", "==", "enterprise").
    Serve(true).
    Build()); err != nil {
    log.Fatal(err)
}
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
_ = mgmt.Delete(ctx, "checkout-v2")
Runtime Evaluation
flags := client.Flags()

// Typed flag handles (no Connect step — runtime initializes lazily on
// first Get and opens the live-updates WebSocket in the background).
checkout := flags.BooleanFlag("checkout-v2", false)
banner   := flags.StringFlag("banner-color", "red")
retries  := flags.NumberFlag("max-retries", 3)

// Ambient context: a provider runs on every evaluation that doesn't
// pass an explicit context.
flags.SetContextProvider(func(ctx context.Context) []smplkit.Context {
    return []smplkit.Context{
        smplkit.NewContext("user", "user-42", map[string]interface{}{
            "plan": "enterprise",
        }),
    }
})

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

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

// Live-update listeners.
flags.OnChange(func(evt *smplkit.FlagChangeEvent) {
    fmt.Println("flag changed:", evt.ID)
})
checkout.OnChange(func(evt *smplkit.FlagChangeEvent) {
    fmt.Println("checkout-v2 specifically changed")
})

// Manual re-fetch (bypasses the WebSocket — useful in short-lived scripts).
if err := flags.Refresh(ctx); err != nil {
    log.Fatal(err)
}

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

// Cleanup is handled by client.Close(); call flags.Disconnect(ctx) to
// stop the runtime sub-client without tearing down the rest.

If you need on-change listeners to receive events for writes that happen immediately after construction (e.g. in showcases or tests), call client.WaitUntilReady(ctx, 0) once after NewClient to block until the WebSocket subscription has been registered server-side.

Flag Types
Constant Value
FlagTypeBoolean "BOOLEAN"
FlagTypeString "STRING"
FlagTypeNumeric "NUMERIC"
FlagTypeJSON "JSON"

Logging

Centrally manage log levels per service+environment from the smplkit platform; the SDK pushes resolved levels onto whichever logging framework you wrap.

Adapters

The SDK ships two adapters as separate Go modules so you only pay for the framework you use:

  • github.com/smplkit/go-sdk/logging/adapters/slog — Go's standard log/slog.
  • github.com/smplkit/go-sdk/logging/adapters/zapgo.uber.org/zap.
go get github.com/smplkit/go-sdk/logging/adapters/slog
Runtime: slog
import (
    "log/slog"

    smplkit "github.com/smplkit/go-sdk/v3"
    slogadapter "github.com/smplkit/go-sdk/logging/adapters/slog"
)

adapter := slogadapter.New()

// Wrap and replace the global slog default. Every package that uses
// slog.Info / slog.Warn / slog.Error / slog.Debug now routes through
// the SDK's level-controlled wrapper. Use WrapHandler explicitly if
// you want to keep your own slog.NewJSONHandler / custom destination.
adapter.InstallDefault()

client.Logging().RegisterAdapter(adapter)
if err := client.Logging().Install(ctx); err != nil {
    log.Fatal(err)
}

// Force a re-fetch of managed levels without waiting for the WebSocket.
if err := client.Logging().Refresh(ctx); err != nil {
    log.Fatal(err)
}

// Listen for level changes from the platform.
client.Logging().OnChange(func(evt *smplkit.LoggerChangeEvent) {
    fmt.Println("logger changed:", evt.ID, "level:", evt.Level, "source:", evt.Source)
})

Why InstallDefault replaces (rather than wraps) the existing default: Go's log/slog has no global registry of loggers, so the SDK can only manage handlers it sits in front of. Wrapping slog.Default()'s pre-existing handler causes a recursion deadlock through log.Default(); installing a fresh TextHandler to stderr avoids the cycle. To attach smplkit control to a non-default handler, use adapter.WrapHandler(yourHandler) and call slog.SetDefault yourself.

Runtime: zap
import (
    "go.uber.org/zap"
    "go.uber.org/zap/zapcore"

    zapadapter "github.com/smplkit/go-sdk/logging/adapters/zap"
)

adapter := zapadapter.New()
core := adapter.WrapCore(zapcore.NewCore(
    zapcore.NewJSONEncoder(zap.NewProductionEncoderConfig()),
    zapcore.AddSync(os.Stderr),
    zapcore.DebugLevel,
))
logger := zap.New(core)

client.Logging().RegisterAdapter(adapter)
_ = client.Logging().Install(ctx)
logger.Info("hello from zap")
Management API
mgmt := client.Manage().Loggers()

// Create or update a logger entry on the platform. PUT is upsert.
logger := mgmt.New("acme.app")
logger.SetLevel(smplkit.LogLevelInfo, "")          // base level
logger.SetLevel(smplkit.LogLevelDebug, "staging")  // env override
if err := logger.Save(ctx); err != nil {
    log.Fatal(err)
}

// Read paths.
fetched, _ := mgmt.Get(ctx, "acme.app")
all, _    := mgmt.List(ctx)
_ = fetched
_ = all

// Force the discovery buffer to send any pending registrations now
// (the runtime drains it on a 5s ticker by default).
if err := mgmt.Flush(ctx); err != nil {
    log.Fatal(err)
}

// Log groups have their own namespace; see client.Manage().LogGroups().
groups := client.Manage().LogGroups()
group := groups.New("infra", smplkit.WithLogGroupName("Infra"))
group.SetLevel(smplkit.LogLevelWarn)
if err := group.Save(ctx); err != nil {
    log.Fatal(err)
}
Log Levels
Constant Value
LogLevelTrace "TRACE"
LogLevelDebug "DEBUG"
LogLevelInfo "INFO"
LogLevelWarn "WARN"
LogLevelError "ERROR"
LogLevelFatal "FATAL"
LogLevelSilent "SILENT"

Debug Logging

Set SMPLKIT_DEBUG=1 to enable verbose diagnostic output to stderr. This is useful for troubleshooting real-time level changes, WebSocket connectivity, and SDK initialization. Debug output bypasses the managed logging framework and writes directly to stderr.

SMPLKIT_DEBUG=1 ./my-app

Accepted values: 1, true, yes (case-insensitive). Any other value (or unset) disables debug output.

Documentation

License

MIT

Documentation

Overview

Package smplkit — Smpl Jobs management surface (mgmt.Jobs()).

Unlike Config/Flags/Logging, Jobs has no live "phone-home" agent — no environment registration, no WebSocket — so its entire surface lives on the management client, exactly like audit forwarder CRUD. Defining a job, triggering a run, and reading run history are all plain request/response calls here:

mgmt.Jobs().New / Get / List / Delete / Run / Usage
mgmt.Jobs().Runs().List / Get / Cancel / Rerun
(*Job).Save / (*Job).Delete

A Job is an active record: build it with JobsManagement.New, mutate fields, and call Save(ctx) (create when unsaved, full-replace update when it already exists) or Delete(ctx). Runs are read-only views; run actions live on mgmt.Jobs().Runs().

Package smplkit provides a Go client for the smplkit platform.

Quick start:

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

Index

Constants

View Source
const (
	ForwarderTypeDatadog   = genaudit.Datadog
	ForwarderTypeElastic   = genaudit.Elastic
	ForwarderTypeHoneycomb = genaudit.Honeycomb
	ForwarderTypeHTTP      = genaudit.Http
	ForwarderTypeNewRelic  = genaudit.NewRelic
	ForwarderTypeSplunkHEC = genaudit.SplunkHec
	ForwarderTypeSumoLogic = genaudit.SumoLogic
)

Supported ForwarderType values, alphabetical by wire constant.

Supported HttpMethod values, alphabetical.

View Source
const (
	JobHttpMethodDelete = JobHttpMethod("DELETE")
	JobHttpMethodGet    = JobHttpMethod("GET")
	JobHttpMethodPatch  = JobHttpMethod("PATCH")
	JobHttpMethodPost   = JobHttpMethod("POST")
	JobHttpMethodPut    = JobHttpMethod("PUT")
)

Supported JobHttpMethod values, alphabetical.

View Source
const (
	ForwarderTransformTypeJSONata = genaudit.JSONATA
)

Supported ForwarderTransformType values.

Variables

ForwarderTypes enumerates every supported ForwarderType value. Useful for `<select>`-style menus or membership checks on free-form input.

HttpMethods enumerates every supported HttpMethod value.

Functions

func NormalizeLoggerName

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 AccountSettings

type AccountSettings struct {
	// Raw is the full settings map. Mutations here are persisted on Save.
	Raw map[string]interface{}
	// contains filtered or unexported fields
}

AccountSettings holds per-account configuration. The wire format is an opaque JSON object; documented keys are exposed as typed accessors, and all keys (known and unknown) are preserved in Raw. Mutate via the setters and call Save(ctx) to persist.

func (*AccountSettings) EnvironmentOrder

func (s *AccountSettings) EnvironmentOrder() []string

EnvironmentOrder returns the canonical ordering of STANDARD environments. Returns nil if not set.

func (*AccountSettings) Save

func (s *AccountSettings) Save(ctx context.Context) error

Save writes the full settings object back to the server.

func (*AccountSettings) SetEnvironmentOrder

func (s *AccountSettings) SetEnvironmentOrder(order []string)

SetEnvironmentOrder sets the canonical ordering of STANDARD environments.

type AccountSettingsManagement

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

AccountSettingsManagement provides get/save for account-level settings. Obtain one via ManagementClient.AccountSettings().

func (*AccountSettingsManagement) Get

Get retrieves the current account settings.

type ApiErrorDetail

type ApiErrorDetail struct {
	// Status is the HTTP status code as a string (e.g. "404").
	Status string `json:"status,omitempty"`
	// Code is an application-specific machine-readable error code (e.g.
	// "environment_unmanaged"). Per JSON:API §7 and ADR-014, smplkit
	// sets this on every error so callers can branch without
	// string-matching the human Detail field.
	Code string `json:"code,omitempty"`
	// Title is a short, human-readable summary (e.g. "Not Found").
	Title string `json:"title,omitempty"`
	// Detail is a longer, human-readable explanation specific to this
	// occurrence.
	Detail string `json:"detail,omitempty"`
	// Source identifies the source of the error within the request.
	Source ErrorSource `json:"source,omitempty"`
	// Meta carries additional structured context (e.g.
	// {"environment": "staging"}). The value types are JSON-decoded
	// natively (string, float64, bool, []any, map[string]any, nil).
	Meta map[string]any `json:"meta,omitempty"`
}

ApiErrorDetail holds a single JSON:API error object as surfaced by the smplkit platform's JSON:API responses. Mirrors Python's ApiErrorDetail.

type AuditClient added in v3.0.10

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

AuditClient is the runtime audit surface — accessed via Client.Audit().

Sub-clients: Events for event recording / listing / retrieval, ResourceTypes for the distinct resource-type index, EventTypes for the distinct event-type index.

SIEM forwarder CRUD lives on the management plane: Client.Manage().Audit().Forwarders().

func (*AuditClient) EventTypes added in v3.0.69

func (a *AuditClient) EventTypes() *AuditEventTypes

EventTypes returns the event-types index sub-client.

func (*AuditClient) Events added in v3.0.10

func (a *AuditClient) Events() *AuditEvents

Events returns the events sub-client.

func (*AuditClient) ResourceTypes added in v3.0.34

func (a *AuditClient) ResourceTypes() *AuditResourceTypes

ResourceTypes returns the resource-types index sub-client.

type AuditEvent added in v3.0.10

type AuditEvent struct {
	// ID is the server-assigned UUID for this event.
	ID uuid.UUID
	// EventType is the event type slug — e.g. "user.created", "invoice.paid".
	EventType string
	// ResourceType is the type of resource the event operated on — e.g. "invoice".
	ResourceType string
	// ResourceID is the customer-facing id of the resource the event operated on.
	ResourceID string
	// OccurredAt is when the event actually happened, as reported by the source.
	OccurredAt time.Time
	// CreatedAt is when the audit service first ingested this event.
	CreatedAt time.Time
	// ActorType is a free-form label for the kind of actor that caused
	// the event (e.g. "USER", "API_KEY", "SYSTEM", or any custom value).
	// Empty when the caller did not supply one; the audit service never
	// backfills from the request credential.
	ActorType string
	// ActorID is the actor identifier. Free-form — any string scheme
	// is accepted; non-UUID values round-trip verbatim. Empty when not
	// supplied.
	ActorID string
	// ActorLabel is a human-readable label for the actor (e.g. an email
	// address or API key name). Empty when not supplied.
	ActorLabel string
	// Data is the free-form per-event payload defined by the customer.
	Data map[string]interface{}
	// IdempotencyKey is the customer-supplied dedupe key. Empty when
	// the customer didn't supply one.
	IdempotencyKey string
	// DoNotForward, when true, skips this event from SIEM forwarder
	// delivery regardless of any matching forwarder filter.
	DoNotForward bool
	// Environment is the environment the event was recorded in. Read-only
	// and always present on reads — the audit service resolves it when the
	// event is recorded (from a single-environment credential, or from the
	// runtime SDK's configured environment, which the SDK sends on every
	// recording call). Never set on the recording request body.
	Environment string
}

AuditEvent is the public-facing representation of an audit event.

ADR-047 §2.3.1. The SDK exposes flat-named fields rather than the nested JSON:API attribute object — the wrapper takes care of the envelope on both create and read.

type AuditEventType added in v3.0.69

type AuditEventType struct {
	// ID is the event type slug (e.g. "invoice.created").
	ID string
	// EventType is the same slug as ID; both fields are populated for clarity.
	EventType string
}

AuditEventType is one row from the event-types index.

type AuditEventTypes added in v3.0.69

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

AuditEventTypes lists the distinct event type slugs seen in the account.

func (*AuditEventTypes) List added in v3.0.69

List returns one page of distinct event type slugs seen in the account.

Without FilterResourceType, returns one row per distinct event type. With the filter, returns only the event types seen with that specific resource type. Sorted alphabetically; offset pagination via PageNumber / PageSize.

type AuditEvents added in v3.0.10

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

AuditEvents handles event recording, listing, and retrieval. Writes are fire-and-forget by default and return as soon as the event is enqueued onto the in-process buffer (ADR-047 §2.6).

func (*AuditEvents) Flush added in v3.0.10

func (e *AuditEvents) Flush(timeout time.Duration)

Flush blocks until the in-memory event buffer is drained or the timeout elapses. Useful for shutdown semantics in short-lived processes that don't always reach Client.Close.

func (*AuditEvents) Get added in v3.0.10

func (e *AuditEvents) Get(ctx context.Context, eventID uuid.UUID) (*AuditEvent, error)

Get retrieves a single audit event by id.

Returns a *NotFoundError if no event with that id exists in the caller's account.

func (*AuditEvents) List added in v3.0.10

List returns one page of audit events scoped to the caller's account.

Filters are exact-match except OccurredAtRange which uses the platform's range syntax (e.g. "[2026-01-01T00:00:00Z,*)"). Pass the previous page's NextCursor as PageAfter to walk subsequent pages.

func (*AuditEvents) Record added in v3.0.13

func (e *AuditEvents) Record(input CreateEventInput) error

Record enqueues an audit event for asynchronous delivery.

Returns nil immediately. The buffer worker handles the actual POST and retries on transient failures. ResourceType beginning with "smpl." is rejected by the server with 403 — that namespace is reserved for smplkit-emitted events.

type AuditForwarders added in v3.0.16

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

AuditForwarders manages SIEM streaming destinations for the authenticated account. Accessed via Client.Manage().Audit().Forwarders().

func (*AuditForwarders) Delete added in v3.0.16

func (f *AuditForwarders) Delete(ctx context.Context, forwarderID string) error

Delete soft-deletes a forwarder.

func (*AuditForwarders) Get added in v3.0.16

func (f *AuditForwarders) Get(ctx context.Context, forwarderID string) (*Forwarder, error)

Get returns one forwarder by id; returned instance is bound to this client so forwarder.Save(ctx) and forwarder.Delete(ctx) work.

func (*AuditForwarders) List added in v3.0.16

List returns one page of forwarders. Offset pagination via PageNumber / PageSize (ADR-014).

func (*AuditForwarders) New added in v3.0.52

func (f *AuditForwarders) New(
	id string,
	name string,
	forwarderType ForwarderType,
	configuration HttpConfiguration,
	opts ...ForwarderOption,
) *Forwarder

New returns an unsaved Forwarder bound to this client. Call (*Forwarder).Save(ctx) to persist.

id is the caller-supplied forwarder key — required at create time (the audit service does not auto-generate it). Use a stable, human-readable identifier (e.g. "splunk-prod"); the key is what appears in every URL and audit-log line for this forwarder.

type AuditManagement added in v3.0.34

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

AuditManagement is the mgmt.audit.* surface — forwarder CRUD. Obtained via ManagementClient.Audit().

func (*AuditManagement) Forwarders added in v3.0.34

func (a *AuditManagement) Forwarders() *AuditForwarders

Forwarders returns the SIEM forwarder CRUD sub-client.

type AuditResourceType added in v3.0.34

type AuditResourceType struct {
	// ID is the resource_type slug (e.g. "invoice").
	ID string
	// ResourceType is the same slug as ID; both fields are populated
	// for clarity.
	ResourceType string
}

AuditResourceType is one row from the resource-type index.

type AuditResourceTypes added in v3.0.34

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

AuditResourceTypes lists the distinct resource-type slugs seen in the account.

func (*AuditResourceTypes) List added in v3.0.34

List returns one page of distinct resource-type slugs seen in the account.

Backed by a maintain-by-write side table (ADR-047 §2.5), so the response time is independent of event volume. Sorted alphabetically; offset pagination via PageNumber / PageSize (ADR-014).

type BindOption added in v3.0.83

type BindOption func(*bindOptions)

BindOption configures a Bind call.

func WithBindParent added in v3.0.83

func WithBindParent(parent interface{}) BindOption

WithBindParent declares the named target as inheriting from a previously bound parent. The parent must be the same object reference previously returned from a successful Bind call on this client. Activates parent-chain inheritance at the server side for any keys the caller omitted from the target (map-target form only — struct fields always register as explicit overrides).

type BooleanFlagHandle

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

BooleanFlagHandle is a typed handle for a boolean flag.

func (*BooleanFlagHandle) Get

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

Get evaluates the flag and returns a typed boolean value.

func (*BooleanFlagHandle) OnChange

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

OnChange registers a flag-specific change listener.

type ChangeListenerOption

type ChangeListenerOption func(*changeListenerConfig)

ChangeListenerOption configures an OnChange listener.

func WithConfigID

func WithConfigID(id string) ChangeListenerOption

WithConfigID restricts the listener to changes in the given config.

func WithItemKey

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(smplkit.Config{APIKey: "sk_api_...", Environment: "production", Service: "my-service"})
cfgs, err := client.Config().Management().List(ctx)

func NewClient

func NewClient(cfg Config, opts ...ClientOption) (*Client, error)

NewClient creates a new smplkit API client.

Configuration is resolved from four layers (later layers override earlier ones):

  1. Defaults (scheme=https, baseDomain=smplkit.com)
  2. Config file (~/.smplkit) with [common] and profile sections
  3. Environment variables (SMPLKIT_API_KEY, SMPLKIT_ENVIRONMENT, etc.)
  4. Explicit Config struct fields

Use ClientOption functions to customize the timeout or HTTP client.

func (*Client) Audit added in v3.0.10

func (c *Client) Audit() *AuditClient

Audit returns the audit-product sub-client. Same instance every call.

func (*Client) Close

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

func (c *Client) Environment() string

Environment returns the resolved environment name.

func (*Client) Flags

func (c *Client) Flags() *FlagsClient

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

func (*Client) Logging

func (c *Client) Logging() *LoggingClient

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

func (*Client) Manage

func (c *Client) Manage() *ManagementClient

Manage returns the management-plane sub-client. Mirrors Python's SmplClient.manage attribute (rule 1).

The returned ManagementClient exposes eight flat namespaces:

client.Manage().Contexts()
client.Manage().ContextTypes()
client.Manage().Environments()
client.Manage().AccountSettings()
client.Manage().Config()
client.Manage().Flags()
client.Manage().Loggers()
client.Manage().LogGroups()
client.Manage().Jobs()

The same *ManagementClient is shared by the runtime sub-clients — client.Config().Management() returns the same instance as client.Manage().Config().

func (*Client) Management

func (c *Client) Management() *ManagementClient

Management returns the sub-client for app-service management operations (environments, context types, contexts, account settings).

func (*Client) Service

func (c *Client) Service() string

Service returns the resolved service name.

func (*Client) WaitUntilReady added in v3.0.2

func (c *Client) WaitUntilReady(ctx context.Context, timeout time.Duration) error

WaitUntilReady eagerly opens the live-updates WebSocket and blocks until the server has accepted the upgrade, validated the API key, and registered the subscription. After this returns, on-change listeners are guaranteed to receive every server event from this point forward — including events triggered by writes the caller fires immediately afterward.

Without this, code that constructs a Client and immediately calls a management write (Save / Delete / SetX+Save) can race the broadcast of the resulting change event and silently miss it: the SDK has not yet appeared in the server's subscriber registry when the broadcast runs, so the broadcast goes to zero subscribers.

timeout=0 uses the SDK default (5s). Context cancellation also returns. Mirrors Python's client.wait_until_ready() and TypeScript's client.waitUntilReady().

type ClientOption

type ClientOption func(*clientConfig)

ClientOption configures the Client. Pass options to NewClient.

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 Color

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

Color is a CSS hex color string. It is immutable: construct a fresh Color via NewColor or NewColorRGB to change a value. Mirrors the Python SDK's Color type (rule 8 of the cross-SDK overhaul).

The constructors validate their inputs at the SDK boundary so customer mistakes surface at the call site rather than as a server 400 later.

func MustColor

func MustColor(hex string) Color

MustColor is the panic-on-error variant of NewColor for compile-time constants. Customer code that builds colors from runtime input should always use NewColor and check the error.

func NewColor

func NewColor(hex string) (Color, error)

NewColor constructs a Color from a CSS hex string. Accepts #RGB, #RRGGBB, or #RRGGBBAA. Any other input returns a non-nil error.

func NewColorRGB

func NewColorRGB(r, g, b int) (Color, error)

NewColorRGB constructs a Color from 0–255 integer components. Each component is validated; out-of-range values produce a non-nil error.

func (Color) Hex

func (c Color) Hex() string

Hex returns the canonical (lowercase) CSS hex string.

func (Color) IsZero

func (c Color) IsZero() bool

IsZero reports whether c is the zero Color value (i.e. unset).

func (Color) String

func (c Color) String() string

String returns the canonical hex string, satisfying fmt.Stringer.

type Config

type Config struct {
	// Profile selects the INI profile from ~/.smplkit.
	// Falls back to SMPLKIT_PROFILE env var, then "default".
	Profile string

	// APIKey is the Bearer token for API authentication.
	// Falls back to SMPLKIT_API_KEY env var, then the config file.
	APIKey string

	// BaseDomain overrides the base domain for service URLs.
	// Default: "smplkit.com". Falls back to SMPLKIT_BASE_DOMAIN env var.
	BaseDomain string

	// Scheme overrides the URL scheme. Default: "https".
	// Falls back to SMPLKIT_SCHEME env var.
	Scheme string

	// Environment is the target environment (e.g. "production", "staging").
	// Falls back to SMPLKIT_ENVIRONMENT env var, then the config file.
	Environment string

	// Service is the service identifier.
	// Falls back to SMPLKIT_SERVICE env var, then the config file.
	Service string

	// Debug enables verbose debug output.
	// Falls back to SMPLKIT_DEBUG env var, then the config file.
	Debug bool

	// DisableTelemetry disables anonymous SDK usage telemetry.
	// Falls back to SMPLKIT_DISABLE_TELEMETRY env var, then the config file.
	DisableTelemetry bool

	// ExtraHeaders are additional HTTP headers sent on every request.
	// SDK-owned headers (Authorization, Accept, User-Agent) take precedence
	// over any key supplied here — callers cannot override them.
	ExtraHeaders map[string]string
}

Config holds user-facing configuration for the smplkit SDK. Fields use Go zero values (empty string, false) to represent "unset". Resolution order: defaults -> config file -> env vars -> struct fields.

type ConfigChangeEvent

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) Bind added in v3.0.83

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

Bind declares a configuration from code and registers `target` as the live, in-place-mutated handle for it.

`target` must be a non-nil pointer to a struct, or a non-nil `map[string]interface{}`. Both kinds are reference types in Go — the SDK mutates them in place when the server pushes updates, so the caller's reference always sees the current resolved value.

  • Struct pointer: every exported field is registered as a config item, using the field's `json` tag if present (without the `,omitempty` suffix), else the field name. Nested struct fields flatten to dot-notation. Every field is treated as an explicit override — Go's type system has no equivalent of Pydantic's `model_fields_set`, so omit-to-inherit semantics are not available on the struct path. Use a `map[string]interface{}` if you need omit-to-inherit.
  • Map: every key in the map is registered as a config item; values are used as the in-code defaults; nested maps flatten to dot-notation. Keys absent from the map inherit from the parent at the server side.

Idempotent. Repeated calls with the same `id` return without re-registering — the originally bound target keeps receiving updates.

After Bind returns, the local cache has been synced into `target` for any keys the server already had values for. On every subsequent WebSocket-delivered change, the SDK mutates `target` in place.

Mirrors python-sdk's `client.config.bind()` and typescript-sdk's `client.config.bind()`.

func (*ConfigClient) Get

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

Get returns the resolved config values for the given ID. Get returns a LiveConfig — a live, dict-like, read-only proxy whose reads always reflect the latest resolved values for the given config ID. WebSocket updates are picked up automatically.

Returns a NotFoundError if the config is missing. For typed access via an in-place-mutated struct or map, use Bind instead.

func (*ConfigClient) GetValue

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

GetValue returns the resolved value of `key` within `configID`. Returns a NotFoundError if either the config or the key is missing. Does not register the key — use GetValueOr if you want default-on-miss + code- first console observability.

func (*ConfigClient) GetValueOr added in v3.0.83

func (c *ConfigClient) GetValueOr(ctx context.Context, configID, key string, defaultValue interface{}) interface{}

GetValueOr returns the resolved value of `key` within `configID`, or `defaultValue` if either the config or the key is missing. Never returns an error. Auto-registers the config and key (with `defaultValue` as the in-code default) for code-first console observability — operators see the reference in the smplkit console even when no schema was declared via Bind.

The item type is inferred from `defaultValue`'s Go runtime type: bool → BOOLEAN, int / int64 / float / float64 → NUMBER, string → STRING, anything else → STRING (universal fallback; an admin can retype the item in the console).

func (*ConfigClient) Management

func (c *ConfigClient) Management() *ConfigManagement

Management returns the sub-object for config CRUD operations.

Returns the same *ConfigManagement instance that client.Manage().Config() returns — runtime and management surfaces share one management object.

func (*ConfigClient) OnChange

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

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.

type ConfigEntry

type ConfigEntry 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 (*ConfigEntry) Delete

func (c *ConfigEntry) Delete(ctx context.Context) error

Delete removes the config from the server. Equivalent to mgmt.Config().Delete(ctx, c.ID).

func (*ConfigEntry) Remove

func (c *ConfigEntry) Remove(name, environment string)

Remove removes an item. environment="" removes from base; non-empty removes the per-env override only.

func (*ConfigEntry) Save

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

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

func (*ConfigEntry) SetBoolean

func (c *ConfigEntry) SetBoolean(name string, value bool, environment string)

SetBoolean sets a boolean item.

func (*ConfigEntry) SetJSON

func (c *ConfigEntry) SetJSON(name string, value interface{}, environment string)

SetJSON sets a JSON item.

func (*ConfigEntry) SetNumber

func (c *ConfigEntry) SetNumber(name string, value float64, environment string)

SetNumber sets a numeric item.

func (*ConfigEntry) SetString

func (c *ConfigEntry) SetString(name, value, environment string)

SetString sets a string item. environment="" updates the base item; non-empty scopes to that environment.

func (*ConfigEntry) TypedEnvironments

func (c *ConfigEntry) TypedEnvironments() map[string]ConfigEnvironment

TypedEnvironments returns a typed, read-only view of per-environment item overrides on a ConfigEntry.

type ConfigEnvironment

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

ConfigEnvironment is the per-environment configuration on a Config. Frozen — mutate via Config.SetString / SetNumber / SetBoolean / SetJSON / Remove with an environment kwarg.

Mirrors Python's smplkit.config.models.ConfigEnvironment.

func NewConfigEnvironment

func NewConfigEnvironment(values map[string]interface{}) ConfigEnvironment

NewConfigEnvironment constructs a ConfigEnvironment. Used by the SDK when parsing server responses.

func (ConfigEnvironment) Values

func (e ConfigEnvironment) Values() map[string]interface{}

Values returns a defensive copy of the per-env value overrides.

type ConfigManagement

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

func (*ConfigManagement) Delete

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

func (*ConfigManagement) Flush added in v3.0.77

func (m *ConfigManagement) Flush(ctx context.Context) error

Flush sends any pending declarations to POST /api/v1/configs/bulk. Per ADR-024 §2.9 the bulk endpoint is plan-limit-exempt; failures here never propagate to customer code. Drained entries are not requeued.

func (*ConfigManagement) Get

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

func (*ConfigManagement) List

func (m *ConfigManagement) List(ctx context.Context, opts ...ListOption) ([]*ConfigEntry, error)

List returns one page of configs for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages. The wrapper does not loop — callers that want every config should iterate until a short page is returned.

func (*ConfigManagement) New

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

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

func (*ConfigManagement) PendingCount added in v3.0.77

func (m *ConfigManagement) PendingCount() int

PendingCount returns the number of pending config declarations awaiting flush.

func (*ConfigManagement) RegisterConfig added in v3.0.77

func (m *ConfigManagement) RegisterConfig(configID, service, environment, parent, name, description string)

Delete removes a config by its ID. RegisterConfig queues a configuration declaration for bulk-discovery upload. Internal — called by ConfigClient.Bind and ConfigClient.GetValueOr.

func (*ConfigManagement) RegisterConfigItem added in v3.0.77

func (m *ConfigManagement) RegisterConfigItem(configID, itemKey, itemType string, defaultVal interface{}, description string)

RegisterConfigItem queues a config item declaration for bulk-discovery upload. Internal — called by ConfigClient.Bind and ConfigClient.GetValueOr.

type ConfigOption

type ConfigOption func(*ConfigEntry)

ConfigOption configures an unsaved Config returned by ConfigClient.New.

func WithConfigDescription

func WithConfigDescription(desc string) ConfigOption

WithConfigDescription sets the description for a config.

func WithConfigEnvironments

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

WithConfigEnvironments sets the environment-specific overrides for a config.

func WithConfigItems

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

WithConfigItems sets the base configuration values for a config.

func WithConfigName

func WithConfigName(name string) ConfigOption

WithConfigName sets the display name for a config.

func WithConfigParent

func WithConfigParent(parentID string) ConfigOption

WithConfigParent sets the parent config UUID for inheritance.

type ConflictError

type ConflictError struct {
	// Base is the embedded base Error carrying the HTTP status, message,
	// raw response body, and any parsed JSON:API error details.
	Base Error
}

ConflictError is raised when an operation conflicts with current resource state.

func (*ConflictError) Error

func (e *ConflictError) Error() string

Error implements the error interface.

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type ConnectionError

type ConnectionError struct {
	// Base is the embedded base Error carrying the HTTP status, message,
	// raw response body, and any parsed JSON:API error details.
	Base Error
}

ConnectionError is raised when a network request fails.

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

Error implements the error interface.

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type Context

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",
})

Identity locking note (rule 9): Python's Context locks `type` and `key` after the entity has been persisted. Go's idiom of exported struct fields makes that lock unenforceable at compile time — `ctx.Type = "X"` is always allowed by the language. Customer code that wants identity-locking semantics should treat persisted Contexts (those returned by mgmt.Contexts().Get / List) as read-only and construct fresh ones via NewContext for new entities. The compile-time-checkable equivalent in Python (TypeError on non-string args) is enforced here by the type system; the runtime "must not be empty" check is enforced by NewContext which panics on empty inputs.

func NewContext

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"),
)

Fail-fast validation (rule 6 of the cross-SDK overhaul): empty type or key panics with a clear message. The Python SDK raises TypeError for non-string args; in Go the type system enforces that, so we only need to enforce non-emptiness. Numeric IDs must be stringified at the SDK boundary — silent normalization weakens the contract.

func (Context) CompositeID

func (c Context) CompositeID() string

CompositeID returns the composite "type:key" identifier mirroring Python's Context.id property. Useful when calling sub-clients that accept either a composite id or separate (type, key) arguments.

type ContextEntity

type ContextEntity struct {
	// ContextType is the context type key (e.g. "user").
	ContextType string
	// Key is the entity's unique identifier within its type.
	Key string
	// Name is an optional display name.
	Name *string
	// Attributes holds arbitrary attribute data.
	Attributes map[string]interface{}
	// CreatedAt is the server creation timestamp.
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

ContextEntity is the active-record model returned by ContextsManagement.List / Get. Mutate Attributes (or Name) and call Save(ctx) to persist; call Delete(ctx) to remove.

Mirrors Python's smplkit.Context active-record model (rule 3). The builder-style smplkit.Context (in flags_types.go) remains the canonical input type for flag evaluation; this struct is the management-side read/write model with a back-reference to its parent client.

func (*ContextEntity) CompositeID

func (ce *ContextEntity) CompositeID() string

CompositeID returns the composite "type:key" identifier.

func (*ContextEntity) Delete

func (ce *ContextEntity) Delete(ctx context.Context) error

Delete removes this context entity from the server. Equivalent to mgmt.Contexts().Delete(ctx, ce.ContextType, ce.Key).

func (*ContextEntity) Save

func (ce *ContextEntity) Save(ctx context.Context) error

Save persists the context entity to the server. The instance is updated with server-returned fields on success.

type ContextOption

type ContextOption func(*Context)

ContextOption configures a Context. Use WithName and WithAttr.

func WithAttr

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

WithAttr adds a single attribute to a Context.

func WithName

func WithName(name string) ContextOption

WithName sets the display name on a Context.

type ContextType

type ContextType struct {
	// ID is the context type identifier (e.g. "user", "account").
	ID string
	// Name is the display name.
	Name string
	// Attributes maps attribute names to their metadata dicts.
	Attributes map[string]map[string]interface{}
	// CreatedAt is the server creation timestamp (nil for unsaved instances).
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

ContextType represents a context-type resource on the smplkit platform. Mutate Attributes via AddAttribute / RemoveAttribute / UpdateAttribute, then call Save(ctx) to persist.

func (*ContextType) AddAttribute

func (ct *ContextType) AddAttribute(name string, meta ...map[string]interface{})

AddAttribute adds (or replaces) an attribute slot with the given metadata. Call Save(ctx) to persist.

func (*ContextType) RemoveAttribute

func (ct *ContextType) RemoveAttribute(name string)

RemoveAttribute removes an attribute slot. Call Save(ctx) to persist.

func (*ContextType) Save

func (ct *ContextType) Save(ctx context.Context) error

Save creates or updates the context type on the server. Creates if CreatedAt is nil, otherwise updates.

func (*ContextType) UpdateAttribute

func (ct *ContextType) UpdateAttribute(name string, meta map[string]interface{})

UpdateAttribute replaces an attribute slot's metadata. Call Save(ctx) to persist.

type ContextTypeOption

type ContextTypeOption func(*ContextType)

ContextTypeOption configures an unsaved ContextType returned by ContextTypesManagement.New.

func WithContextTypeName

func WithContextTypeName(name string) ContextTypeOption

WithContextTypeName sets the display name for a context type.

type ContextTypesManagement

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

ContextTypesManagement provides CRUD operations for context type resources. Obtain one via ManagementClient.ContextTypes().

func (*ContextTypesManagement) Delete

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

Delete removes a context type by ID.

func (*ContextTypesManagement) Get

Get retrieves a single context type by ID.

func (*ContextTypesManagement) List

func (m *ContextTypesManagement) List(ctx context.Context, opts ...ListOption) ([]*ContextType, error)

List returns one page of context types for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*ContextTypesManagement) New

New returns an unsaved ContextType. Call ct.Save(ctx) to persist. If no name option is provided the ID is used as the display name.

type ContextsManagement

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

ContextsManagement provides context registration, listing, and deletion. Obtain one via ManagementClient.Contexts().

func (*ContextsManagement) Delete

func (m *ContextsManagement) Delete(ctx context.Context, parts ...string) error

Delete removes a context by its composite "type:key" id, or by separate type and key arguments.

func (*ContextsManagement) Flush

func (m *ContextsManagement) Flush(ctx context.Context) error

Flush sends any pending context observations to the server immediately.

func (*ContextsManagement) Get

func (m *ContextsManagement) Get(ctx context.Context, parts ...string) (*ContextEntity, error)

Get retrieves a single context by its composite "type:key" id, or by separate type and key arguments:

management.Contexts().Get(ctx, "user:usr_123")
management.Contexts().Get(ctx, "user", "usr_123")

func (*ContextsManagement) List

func (m *ContextsManagement) List(ctx context.Context, contextType string, opts ...ListOption) ([]*ContextEntity, error)

List returns one page of context instances of the given context type.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*ContextsManagement) Register

func (m *ContextsManagement) Register(ctx context.Context, contexts []Context, opts ...ContextsRegisterOption) error

Register buffers contexts for registration with the server. By default contexts are queued for background flush; use WithContextFlush() to perform an immediate synchronous flush after queuing.

type ContextsRegisterOption

type ContextsRegisterOption func(*contextsRegisterOpts)

ContextsRegisterOption configures a Register call.

func WithContextFlush

func WithContextFlush() ContextsRegisterOption

WithContextFlush causes Register to immediately flush the buffer to the server. Without this option contexts are queued for the next background flush.

type CreateEventInput added in v3.0.10

type CreateEventInput struct {
	// EventType is the event type slug — required.
	EventType string
	// ResourceType is the type of resource the event operated on. Must
	// not start with "smpl." (reserved for SDK-emitted events).
	ResourceType string
	// ResourceID is the customer-facing id of the resource.
	ResourceID string
	// OccurredAt is when the event actually happened. Defaults to the
	// server's receive time when nil.
	OccurredAt *time.Time
	// ActorType is a free-form label for the kind of actor that caused
	// the event (e.g. "USER", "API_KEY", "SYSTEM", or any custom value).
	// The audit service never backfills this from the request
	// credential — set it explicitly when you want the event attributed.
	ActorType string
	// ActorID is the actor identifier. Free-form — any string scheme is
	// accepted.
	ActorID string
	// ActorLabel is a human-readable label for the actor (e.g. an email
	// address or API key name).
	ActorLabel string
	// Data is free-form contextual JSON. To record a resource snapshot,
	// nest it inside Data — the smplkit internal convention is
	// Data["snapshot"], but the shape is unconstrained.
	Data map[string]interface{}
	// IdempotencyKey is an optional customer-supplied dedupe key.
	IdempotencyKey string
	// DoNotForward suppresses SIEM forwarder execution for this event.
	// The event itself is still recorded; the forwarder loop records a
	// "skipped_do_not_forward" delivery row for each enabled forwarder.
	DoNotForward bool
}

CreateEventInput is the input for AuditEvents.Record.

Customers must NOT use a ResourceType prefixed with "smpl." — the server returns 403 for those because that namespace is reserved for smplkit-emitted events.

DoNotForward suppresses SIEM forwarder execution for this event. The event itself is still recorded; the forwarder loop records a "skipped_do_not_forward" delivery row for each enabled forwarder so the skip is visible in the delivery log. Data is free-form contextual JSON. To record a resource snapshot, nest it inside Data — smplkit's internal convention is Data["snapshot"], but the shape is unconstrained.

type Environment

type Environment struct {
	// ID is the environment slug (e.g. "production").
	ID string
	// Name is the display name.
	Name string
	// Color is an optional hex color string for the Console UI.
	Color *string
	// Classification controls whether this environment participates in ordering.
	Classification EnvironmentClassification
	// CreatedAt is the server creation timestamp (nil for unsaved instances).
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Environment represents a smplkit environment resource. Mutate fields and call Save(ctx) to persist.

func (*Environment) Save

func (e *Environment) Save(ctx context.Context) error

Save creates or updates the environment on the server. The instance is updated with server-returned fields on success. PUT semantics: creates if CreatedAt is nil, otherwise updates.

func (*Environment) SetTypedColor

func (e *Environment) SetTypedColor(c Color)

SetTypedColor sets the environment's display color from a typed Color. A zero Color clears the color. Call Save(ctx) to persist.

func (*Environment) TypedColor

func (e *Environment) TypedColor() Color

TypedColor returns the environment's display color as a typed Color value, or a zero Color if no color is set on this environment.

Mirrors Python's Environment.color property which returns a Color instance (rule 9). The wire transports a hex string; the SDK wraps it at the boundary. A malformed hex string on the wire returns the zero Color rather than surfacing a validation error on read.

type EnvironmentClassification

type EnvironmentClassification string

EnvironmentClassification indicates whether an environment participates in the canonical environment ordering.

STANDARD environments are the customer's deploy targets — production, staging, development, etc. They participate in AccountSettings.EnvironmentOrder and appear in the standard Console environment columns.

AD_HOC environments are transient targets (preview branches, individual developer sandboxes) that should not appear in the standard ordering.

const (
	// EnvironmentClassificationAdHoc marks an environment as a transient,
	// non-ordered target (preview branches, developer sandboxes).
	EnvironmentClassificationAdHoc EnvironmentClassification = "AD_HOC"
	// EnvironmentClassificationStandard marks an environment as a canonical
	// deploy target — appears in AccountSettings.EnvironmentOrder.
	EnvironmentClassificationStandard EnvironmentClassification = "STANDARD"
)

Supported EnvironmentClassification values, alphabetical by wire constant.

type EnvironmentOption

type EnvironmentOption func(*Environment)

EnvironmentOption configures an unsaved Environment returned by EnvironmentsManagement.New.

func WithEnvironmentClassification

func WithEnvironmentClassification(c EnvironmentClassification) EnvironmentOption

WithEnvironmentClassification sets the classification (STANDARD or AD_HOC).

func WithEnvironmentColor

func WithEnvironmentColor(color string) EnvironmentOption

WithEnvironmentColor sets the display color (hex string, e.g. "#ef4444").

type EnvironmentsManagement

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

EnvironmentsManagement provides CRUD operations for environment resources. Obtain one via ManagementClient.Environments().

func (*EnvironmentsManagement) Delete

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

Delete removes an environment by ID.

func (*EnvironmentsManagement) Get

Get retrieves a single environment by ID.

func (*EnvironmentsManagement) List

func (m *EnvironmentsManagement) List(ctx context.Context, opts ...ListOption) ([]*Environment, error)

List returns one page of environments for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*EnvironmentsManagement) New

New returns an unsaved Environment. Call env.Save(ctx) to persist.

type Error

type Error struct {
	// Message is a human-readable summary of the error.
	Message string
	// StatusCode holds the HTTP status code if the error came from the API.
	StatusCode int
	// ResponseBody holds the raw response body if available.
	ResponseBody string
	// Errors holds parsed JSON:API error details when available.
	Errors []ApiErrorDetail
}

Error is the base error type for all smplkit SDK errors. The flat hierarchy mirrors the Python SDK: ConnectionError, TimeoutError, NotFoundError, ConflictError, and ValidationError are direct subtypes.

To match any SDK error use errors.As against *Error:

var e *smplkit.Error
if errors.As(err, &e) { ... }

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

type ErrorDetail

type ErrorDetail = ApiErrorDetail

ErrorDetail is an alias for ApiErrorDetail kept for backward compatibility. New code should use ApiErrorDetail.

type ErrorSource

type ErrorSource struct {
	// Pointer is the JSON Pointer to the offending member in the
	// request body (e.g. "/data/attributes/name").
	Pointer string `json:"pointer,omitempty"`
}

ErrorSource identifies the source of a JSON:API error.

type EventTypeListPage added in v3.0.69

type EventTypeListPage struct {
	// EventTypes is the slice of event types on this page.
	EventTypes []AuditEventType
	// Pagination describes the page boundaries and totals (if requested).
	Pagination Pagination
}

EventTypeListPage is one page of event type slugs.

type Flag

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

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) AddValue

func (f *Flag) AddValue(name string, value interface{}) *Flag

AddValue appends a constrained value to the flag's value set. Returns f for chaining. Mirrors Python's flag.add_value.

func (*Flag) ClearDefault

func (f *Flag) ClearDefault(environment string)

ClearDefault clears the per-environment default override on the named environment. environment must be non-empty (mirrors Python's `clear_default(*, environment)` which makes the kwarg required).

Call Flag.Save(ctx) to persist.

func (*Flag) ClearRules

func (f *Flag) ClearRules(envKey string)

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

func (*Flag) ClearRulesAll

func (f *Flag) ClearRulesAll()

ClearRulesAll clears rules in every environment configured on this flag. Mirrors Python's clear_rules(*, environment=None) with environment=None. For a single-environment clear, use the existing ClearRules(envKey).

func (*Flag) ClearValues

func (f *Flag) ClearValues()

ClearValues sets values to nil (unconstrained). Call Save(ctx) to persist.

func (*Flag) Delete

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

Delete removes the flag from the server. Equivalent to mgmt.Flags().Delete(ctx, f.ID) — provided as a convenience on the active-record model (rule 3 of the cross-SDK overhaul).

func (*Flag) DisableRules

func (f *Flag) DisableRules(environment string)

DisableRules disables rule evaluation (kill switch). environment="" disables rules in every environment configured on this flag.

func (*Flag) EnableRules

func (f *Flag) EnableRules(environment string)

EnableRules enables rule evaluation. environment="" enables rules in every environment configured on this flag; non-empty scopes to that single environment. Mirrors Python's enable_rules(*, environment=None).

func (*Flag) RemoveValue

func (f *Flag) RemoveValue(value interface{}) *Flag

RemoveValue removes the first values entry whose Value field matches. Returns f for chaining.

func (*Flag) Save

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) SetDefault

func (f *Flag) SetDefault(value interface{}, environment string)

SetDefault sets the default served value. environment="" updates the flag-level base default; environment="production" sets the per-env default. Mirrors Python's flag.set_default(value, *, environment=None).

Call Flag.Save(ctx) to persist.

func (*Flag) SetEnvironmentDefault

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

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

func (*Flag) SetEnvironmentEnabled

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

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

func (*Flag) TypedEnvironments

func (f *Flag) TypedEnvironments() map[string]FlagEnvironment

TypedEnvironments returns a typed, read-only view of per-environment configuration on a Flag. Mirrors Python's flag.environments property returning dict[str, FlagEnvironment].

The returned map is a defensive copy; mutating it has no effect on the underlying flag. Mutate the flag via SetDefault / EnableRules / DisableRules / AddRule (with environment scoping) instead.

type FlagChangeEvent

type FlagChangeEvent struct {
	// ID is the flag ID that changed.
	ID string
	// Source is "websocket" or "manual".
	Source string
	// Deleted is true when the flag was deleted server-side.
	Deleted bool
}

FlagChangeEvent describes a flag definition change.

type FlagEnvironment

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

FlagEnvironment is the per-environment configuration on a Flag. Frozen. Mutate via Flag.AddRule / Flag.EnableRules / Flag.DisableRules / Flag.SetDefault / Flag.ClearRules with environment scoping.

Mirrors Python's smplkit.flags.models.FlagEnvironment.

func NewFlagEnvironment

func NewFlagEnvironment(enabled bool, defaultValue interface{}, rules []FlagRule) FlagEnvironment

NewFlagEnvironment constructs a FlagEnvironment. Used by the SDK when parsing server responses; exposed for completeness.

func (FlagEnvironment) Default

func (e FlagEnvironment) Default() interface{}

Default returns the environment-specific default override, or nil if no override is set (in which case the flag's base default applies).

func (FlagEnvironment) Enabled

func (e FlagEnvironment) Enabled() bool

Enabled reports whether the flag is active in this environment.

func (FlagEnvironment) Rules

func (e FlagEnvironment) Rules() []FlagRule

Rules returns a defensive copy of the targeting rules.

type FlagOption

type FlagOption func(*Flag)

FlagOption configures an unsaved Flag returned by factory methods.

func WithFlagDescription

func WithFlagDescription(desc string) FlagOption

WithFlagDescription sets the description for a flag.

func WithFlagName

func WithFlagName(name string) FlagOption

WithFlagName sets the display name for a flag.

func WithFlagValues

func WithFlagValues(values []FlagValue) FlagOption

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

type FlagRule

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

FlagRule is a single targeting rule on a Flag. Frozen — author rules via the smplkit.Rule fluent builder and pass through Flag.AddRule.

Mirrors Python's smplkit.flags.models.FlagRule.

func NewFlagRule

func NewFlagRule(logic map[string]interface{}, value interface{}, description string) FlagRule

NewFlagRule constructs a FlagRule. Customer code typically uses the Rule fluent builder; this constructor is used by the SDK when parsing server responses and exposed for completeness.

func (FlagRule) Description

func (r FlagRule) Description() string

Description returns the human-readable label, if any.

func (FlagRule) Logic

func (r FlagRule) Logic() map[string]interface{}

Logic returns a defensive copy of the JSON Logic predicate. Empty map means "always match".

func (FlagRule) Value

func (r FlagRule) Value() interface{}

Value returns the value served when Logic evaluates truthy.

type FlagStats

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

type FlagType string

FlagType represents the value type of a flag.

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

Supported FlagType values, alphabetical by wire constant.

type FlagValue

type FlagValue struct {
	// Name is the human-readable label for this value option.
	Name string
	// Value is the raw value returned when this option is selected.
	// Shape depends on the flag's FlagType.
	Value interface{}
}

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

type FlagsClient

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

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

BooleanFlag returns a typed handle for a boolean flag.

func (*FlagsClient) ConnectionStatus

func (c *FlagsClient) ConnectionStatus() string

ConnectionStatus returns the current real-time connection status.

func (*FlagsClient) Disconnect

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

Disconnect stops real-time updates and releases runtime resources.

func (*FlagsClient) Evaluate

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) JsonFlag

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

JsonFlag returns a typed handle for a JSON flag.

func (*FlagsClient) Management

func (c *FlagsClient) Management() *FlagsManagement

Management returns the sub-object for flag CRUD operations.

func (*FlagsClient) NumberFlag

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

NumberFlag returns a typed handle for a numeric flag.

func (*FlagsClient) OnChange

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

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

func (*FlagsClient) OnChangeKey

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

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

Refresh fetches the latest flag definitions from the server.

func (*FlagsClient) SetContextProvider

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

SetContextProvider registers a function that provides evaluation contexts.

func (*FlagsClient) Stats

func (c *FlagsClient) Stats() FlagStats

Stats returns runtime statistics.

func (*FlagsClient) StringFlag

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

StringFlag returns a typed handle for a string flag.

type FlagsManagement

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

FlagsManagement provides CRUD operations for flag resources. Obtain one via Client.Manage().Flags() or FlagsClient.Management().

Owns its generated API client directly (no runtime-skeleton dependency); the optional runtime back-reference is set only when wired into a runtime Client so context-type CRUD (which lives on the app service) and runtime cache invalidation work via the live FlagsClient.

func (*FlagsManagement) CreateContextType

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

CreateContextType creates a new context type.

func (*FlagsManagement) Delete

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

Delete removes a flag by its ID.

func (*FlagsManagement) DeleteContextType

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

DeleteContextType deletes a context type by its ID.

func (*FlagsManagement) Get

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

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

func (*FlagsManagement) List

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

List returns one page of flags for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages. The wrapper does not loop — callers that want every flag should iterate until a short page is returned.

func (*FlagsManagement) ListContextTypes

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

ListContextTypes returns one page of context types.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*FlagsManagement) ListContexts

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

ListContexts returns one page of context instances filtered by context type key.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*FlagsManagement) NewBooleanFlag

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

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

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

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

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

UpdateContextType updates a context type's attributes.

type FlagsRuntime

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

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

BooleanFlag returns a typed handle for a boolean flag.

func (*FlagsRuntime) ConnectionStatus

func (rt *FlagsRuntime) ConnectionStatus() string

ConnectionStatus returns the current real-time connection status.

func (*FlagsRuntime) Evaluate

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

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

FlushContexts sends any pending context registrations to the server immediately.

func (*FlagsRuntime) JsonFlag

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

JsonFlag returns a typed handle for a JSON flag.

func (*FlagsRuntime) NumberFlag

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

NumberFlag returns a typed handle for a numeric flag.

func (*FlagsRuntime) OnChange

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

OnChange registers a global change listener.

func (*FlagsRuntime) OnChangeKey

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

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

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

Register explicitly registers context(s) with the server.

func (*FlagsRuntime) SetContextProvider

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

SetContextProvider registers a function that provides evaluation contexts.

func (*FlagsRuntime) Stats

func (rt *FlagsRuntime) Stats() FlagStats

Stats returns runtime statistics.

func (*FlagsRuntime) StringFlag

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

StringFlag returns a typed handle for a string flag.

type Forwarder added in v3.0.16

type Forwarder struct {
	// ID is the caller-supplied key for this forwarder. Required at
	// create time (the audit service does not auto-generate it). Empty
	// string until Save has run for an unsaved instance constructed
	// without an id.
	ID string
	// Name is the display name. Free-form.
	Name string
	// Description is an optional free-text description.
	Description *string
	// ForwarderType is the destination type — see ForwarderType.
	ForwarderType ForwarderType
	// Enabled is read-only and always false. The base enablement is
	// pinned off (ADR-055); whether a forwarder actually delivers is
	// decided per environment via Environments. Mutating this field has
	// no effect on the server — the wrapper does not send it. It is kept
	// so reads round-trip the server value.
	Enabled bool
	// Environments holds per-environment overrides keyed by environment
	// key (e.g. "production", "staging"). A forwarder delivers in an
	// environment only when Environments[env].Enabled is true. Each entry
	// may carry an optional HttpConfiguration override; leave it nil to
	// inherit the base Configuration. Every referenced environment must
	// exist and be managed for the account. Nil/empty means the forwarder
	// delivers nowhere until enabled per environment.
	Environments map[string]ForwarderEnvironment
	// Filter is an optional JSON Logic expression evaluated per event.
	// When set, events that don't match are recorded as filtered_out
	// deliveries instead of being POSTed to the destination.
	Filter map[string]interface{}
	// Transform is an optional template applied to each event before
	// delivery. Shape depends on TransformType; for JSONATA, a string
	// containing a JSONata expression. Future engines may carry richer
	// shapes (objects, arrays, …), so the field is untyped. Nil
	// delivers the event JSON as-is; when set, TransformType must also
	// be set.
	Transform interface{}
	// TransformType identifies the engine used to evaluate Transform.
	// Currently only ForwarderTransformTypeJSONata is supported. Must
	// be set whenever Transform is set.
	TransformType *ForwarderTransformType
	// Configuration is the destination request configuration.
	Configuration HttpConfiguration
	// CreatedAt is when the audit service first persisted this
	// forwarder. Nil for an unsaved instance.
	CreatedAt *time.Time
	// UpdatedAt is when this forwarder was last mutated.
	UpdatedAt *time.Time
	// DeletedAt is the soft-delete timestamp. Nil for live forwarders.
	DeletedAt *time.Time
	// Version is a monotonic counter bumped on every server-side write.
	Version *int
	// contains filtered or unexported fields
}

Forwarder is a SIEM streaming destination configured on the customer's account. Active-record style: mutate fields directly and call Save(ctx) to persist, or Delete(ctx) to remove. Headers in Configuration.Headers are always returned redacted on reads — re- supply the real values before calling Save (the SDK does not cache them client-side).

func (*Forwarder) Delete added in v3.0.52

func (fwd *Forwarder) Delete(ctx context.Context) error

Delete soft-deletes this forwarder on the server.

func (*Forwarder) Save added in v3.0.52

func (fwd *Forwarder) Save(ctx context.Context) error

Save creates or updates this forwarder on the server. Upsert behavior keyed on CreatedAt: nil → create (POST), set → full-replace update (PUT). After the call, every field is refreshed from the server response (including CreatedAt, UpdatedAt, Version). Header values must be plaintext: reads return them redacted, so a "<redacted>" round-tripped through Save would persist that literal.

type ForwarderEnvironment added in v3.0.120

type ForwarderEnvironment struct {
	// Enabled controls whether the forwarder delivers events in this
	// environment. Defaults to false.
	Enabled bool
	// Configuration is an optional per-environment destination
	// configuration that fully replaces the forwarder's base
	// Configuration for this environment. Nil (the default) inherits the
	// base configuration. As with the base configuration, header values
	// are plaintext on writes and returned redacted on reads — re-supply
	// real values before Save.
	Configuration *HttpConfiguration
}

ForwarderEnvironment is a per-environment override for a forwarder's enablement and optional configuration. A forwarder delivers events in a given environment only when that environment has an entry in Forwarder.Environments with Enabled=true; an environment with no entry (or Enabled=false) receives no deliveries.

type ForwarderOption added in v3.0.52

type ForwarderOption func(*Forwarder)

ForwarderOption configures an unsaved Forwarder returned by AuditForwarders.New.

func WithForwarderDescription added in v3.0.52

func WithForwarderDescription(description string) ForwarderOption

WithForwarderDescription sets the optional free-text description.

func WithForwarderEnvironments added in v3.0.120

func WithForwarderEnvironments(environments map[string]ForwarderEnvironment) ForwarderOption

WithForwarderEnvironments sets the per-environment override map that drives enablement (ADR-055). A forwarder delivers in an environment only when that environment's entry has Enabled=true; each entry may carry an optional HttpConfiguration override (nil inherits the base configuration). Every referenced environment must exist and be managed for the account. Without this option the forwarder is created enabled nowhere.

func WithForwarderFilter added in v3.0.52

func WithForwarderFilter(filter map[string]interface{}) ForwarderOption

WithForwarderFilter sets the optional JSON Logic filter applied per event.

func WithForwarderTransform added in v3.0.52

func WithForwarderTransform(transformType ForwarderTransformType, transform interface{}) ForwarderOption

WithForwarderTransform sets the optional template applied to each event before delivery, paired with the engine used to evaluate it. transform is intentionally untyped — today JSONATA carries a string expression, but the field shape is engine-defined and future engines may carry richer payloads. Both arguments must be supplied together; passing a non-nil transform without a transformType (or vice versa) is rejected server-side.

type ForwarderTransformType added in v3.0.52

type ForwarderTransformType = genaudit.ForwarderTransformType

ForwarderTransformType identifies the engine used to evaluate a forwarder's transform expression. Currently only JSONATA is supported; additional engines may join later.

type ForwarderType added in v3.0.25

type ForwarderType = genaudit.ForwarderType

ForwarderType is a SIEM streaming destination type. The audit service rejects any value outside the constants below with a 400. See ADR-047 §2.12.

type HttpConfig added in v3.0.114

type HttpConfig struct {
	// Method is the HTTP verb used when the job fires. Defaults to
	// JobHttpMethodPost when zero-valued.
	Method JobHttpMethod
	// URL is the absolute http:// or https:// destination the job calls.
	URL string
	// Headers are attached to every run's request. Values carry
	// credentials and are encrypted at rest server-side; reads return
	// them as plaintext.
	Headers []HttpHeader
	// Body is the request body sent on each run. Nil sends an empty body
	// (suitable for a connectivity ping). Sent verbatim — pair with a
	// matching Content-Type header.
	Body *string
	// SuccessStatus is the response status that counts as success — an
	// exact code ("200", "204") or a class ("2xx", "5xx"). Defaults to
	// "2xx" server-side when zero-valued.
	SuccessStatus string
	// Timeout is the per-run timeout in seconds. A run that does not
	// complete within this many seconds fails with reason TIMEOUT.
	// Defaults to 30 server-side when zero-valued.
	Timeout int
	// TlsVerify controls whether the destination's TLS certificate chain
	// is verified. Pointer-valued so the zero-value HttpConfig is
	// unambiguous: nil means "leave at the server default of true", &false
	// means "skip verification", &true means "verify explicitly".
	TlsVerify *bool
	// CaCert is an optional PEM-encoded certificate (or bundle) trusted in
	// addition to the system CA store. Ignored when TlsVerify points to
	// false. Nil means "use system CAs only".
	CaCert *string
}

HttpConfig is the HTTP request a job performs when it fires (the job's "configuration"). It mirrors the shared HttpConfiguration used by audit forwarders but adds the two fields a scheduled job needs: a request Body and a per-run Timeout.

type HttpConfiguration added in v3.0.52

type HttpConfiguration struct {
	// Method is the HTTP verb used for delivery. Defaults to
	// HttpMethodPost when zero-valued.
	Method HttpMethod
	// URL is the destination the audit service POSTs each event to.
	URL string
	// Headers are attached to every outbound request. Values carry
	// credentials and are encrypted at rest server-side; reads return
	// them redacted.
	Headers []HttpHeader
	// SuccessStatus is the response status the destination must return
	// for delivery to count as success — an exact code ("200", "204")
	// or a class ("2xx", "4xx"). Defaults to "2xx" server-side when
	// zero-valued.
	SuccessStatus string
	// TlsVerify controls whether the destination's TLS certificate
	// chain is verified. Pointer-valued so the zero-value HttpConfiguration
	// is unambiguous: nil means "leave at the server default of true",
	// &false means "skip verification" (the trial-Splunk escape hatch),
	// &true means "verify explicitly". Prefer pinning the issuing CA via
	// CaCert for long-lived self-signed setups.
	TlsVerify *bool
	// CaCert is an optional PEM-encoded certificate (or bundle) trusted
	// in addition to the system CA store. Ignored when TlsVerify points
	// to false. Empty/nil string (the default) means "use system CAs only".
	CaCert *string
}

HttpConfiguration is the destination HTTP request configuration used by a forwarder of the HTTP family (HTTP, DATADOG, SPLUNK_HEC, SUMO_LOGIC, NEW_RELIC, HONEYCOMB, ELASTIC). Other transports will join this as members of a discriminated union under the Configuration field of Forwarder when they ship.

type HttpHeader added in v3.0.16

type HttpHeader struct {
	// Name is the header name (e.g. "Authorization", "DD-API-KEY").
	Name string
	// Value is the header value, plaintext on writes. The audit service
	// encrypts values at rest; reads return them as "<redacted>".
	Value string
}

HttpHeader is a single name/value HTTP header on a forwarder destination request.

type HttpMethod added in v3.0.52

type HttpMethod = genaudit.HttpConfigurationMethod

HttpMethod is the HTTP verb a forwarder uses when delivering an event. The audit service rejects any value outside the constants below with a 400.

type Job added in v3.0.114

type Job struct {
	// ID is the caller-supplied unique identifier for the job. Required
	// at create time (the jobs service does not auto-generate it) and
	// immutable thereafter.
	ID string
	// Name is the human-readable name for the job.
	Name string
	// Description is an optional free-text description.
	Description *string
	// Enabled controls whether the job schedules runs. Set false to pause
	// without deleting. Defaults to true on an unsaved Job.
	Enabled bool
	// Type is the job type. Only "http" is supported today.
	Type string
	// Schedule is when the job runs: an ISO-8601 datetime (a one-off run
	// at that instant), a 5-field cron expression evaluated in UTC
	// (recurring), or the literal "now" (run once, as soon as possible).
	Schedule string
	// Configuration is the HTTP request the job performs when it fires.
	Configuration HttpConfig
	// ConcurrencyPolicy is how overlapping runs are handled. "ALLOW" (the
	// only value today) permits them.
	ConcurrencyPolicy string
	// NextRunAt is the next scheduled fire time. Nil once a one-off job
	// has fired.
	NextRunAt *time.Time
	// CreatedAt is when the job was created. Nil for an unsaved Job.
	CreatedAt *time.Time
	// UpdatedAt is when the job was last modified.
	UpdatedAt *time.Time
	// DeletedAt is the soft-delete timestamp. Nil for live jobs.
	DeletedAt *time.Time
	// Version is a monotonic counter incremented on every update,
	// starting at 1.
	Version *int
	// contains filtered or unexported fields
}

Job is a scheduled unit of work: an HTTP request run on a schedule.

Active-record style: mutate fields directly and call Save(ctx) to persist, or Delete(ctx) to remove. The Job's id is caller-supplied, unique within the account, and immutable.

func (*Job) Delete added in v3.0.114

func (job *Job) Delete(ctx context.Context) error

Delete soft-deletes this job on the server.

func (*Job) Save added in v3.0.114

func (job *Job) Save(ctx context.Context) error

Save creates this job on the server, or full-replaces it if it already exists. Upsert behavior keyed on CreatedAt: nil → create (POST), set → full-replace update (PUT). After the call, every field is refreshed from the server response (including CreatedAt, UpdatedAt, Version).

type JobHttpMethod added in v3.0.114

type JobHttpMethod = genjobs.JobHttpConfigurationMethod

JobHttpMethod is the HTTP verb a job uses when it fires. The jobs service rejects any value outside the constants below with a 400.

type JobOption added in v3.0.114

type JobOption func(*Job)

JobOption configures an unsaved Job returned by JobsManagement.New.

func WithJobConcurrencyPolicy added in v3.0.114

func WithJobConcurrencyPolicy(policy string) JobOption

WithJobConcurrencyPolicy overrides the default concurrency policy ("ALLOW").

func WithJobDescription added in v3.0.114

func WithJobDescription(description string) JobOption

WithJobDescription sets the optional free-text description.

func WithJobEnabled added in v3.0.114

func WithJobEnabled(enabled bool) JobOption

WithJobEnabled overrides the default Enabled=true.

type JobsManagement added in v3.0.114

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

JobsManagement is the mgmt.Jobs() surface: active-record job CRUD, the run-now action, run history (Runs), and usage. Obtained via ManagementClient.Jobs().

func (*JobsManagement) Delete added in v3.0.114

func (j *JobsManagement) Delete(ctx context.Context, id string) error

Delete soft-deletes a job by id.

func (*JobsManagement) Get added in v3.0.114

func (j *JobsManagement) Get(ctx context.Context, id string) (*Job, error)

Get returns one job by id; the returned instance is bound to this client so job.Save(ctx) and job.Delete(ctx) work.

func (*JobsManagement) List added in v3.0.114

func (j *JobsManagement) List(ctx context.Context, input ListJobsInput) ([]*Job, error)

List returns the jobs for the authenticated account. Offset pagination via PageNumber / PageSize (ADR-014).

func (*JobsManagement) New added in v3.0.114

func (j *JobsManagement) New(
	id string,
	name string,
	schedule string,
	configuration HttpConfig,
	opts ...JobOption,
) *Job

New returns an unsaved Job bound to this client. Call (*Job).Save(ctx) to create it.

id is the caller-supplied unique identifier for the job. Unique within the account and immutable; the service returns 409 if another live job already uses this id.

func (*JobsManagement) Run added in v3.0.114

func (j *JobsManagement) Run(ctx context.Context, id string) (*Run, error)

Run triggers one immediate MANUAL run of the job and returns it.

func (*JobsManagement) Runs added in v3.0.114

func (j *JobsManagement) Runs() *RunsClient

Runs returns the run history and run-action sub-client.

func (*JobsManagement) Usage added in v3.0.114

func (j *JobsManagement) Usage(ctx context.Context) (*Usage, error)

Usage returns the current-period usage counters for the account.

type JsonFlagHandle

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

JsonFlagHandle is a typed handle for a JSON flag.

func (*JsonFlagHandle) Get

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

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

OnChange registers a flag-specific change listener.

type ListEventTypesInput added in v3.0.69

type ListEventTypesInput struct {
	// FilterResourceType, when set, returns only event types seen with that
	// specific resource type.
	FilterResourceType string
	// PageNumber is the 1-based page index. Zero defers to the server default.
	PageNumber int
	// PageSize is items per page. Zero defers to the server default.
	PageSize int
	// MetaTotal asks the server to populate total / total_pages.
	MetaTotal bool
}

ListEventTypesInput is the filter + pagination input for AuditEventTypes.List.

type ListEventsInput added in v3.0.10

type ListEventsInput struct {
	// EventType filters by exact event type slug.
	EventType string
	// ResourceType filters by exact resource type.
	ResourceType string
	// ResourceID filters by exact resource id.
	ResourceID string
	// ActorType filters by exact actor type. Matches the literal string
	// stored on the event.
	ActorType string
	// ActorID filters by exact actor id. Matches the literal string
	// stored on the event — any identifier scheme works.
	ActorID string
	// OccurredAtRange filters by occurred_at using the platform's range
	// syntax (e.g. "[2026-01-01T00:00:00Z,*)" — ADR-014).
	OccurredAtRange string
	// Search performs a case-insensitive substring match against
	// resource_id.
	Search string
	// PageSize is items per page. Zero defers to the server default.
	PageSize int
	// PageAfter is the opaque cursor returned as NextCursor by the
	// previous call. Empty fetches the first page.
	PageAfter string
}

ListEventsInput passes filters and pagination to AuditEvents.List.

type ListEventsPage added in v3.0.10

type ListEventsPage struct {
	// Events is the slice of audit events on this page.
	Events []AuditEvent
	// NextCursor is the opaque token to pass as PageAfter on the next
	// call. Empty when this is the last page.
	NextCursor string
}

ListEventsPage is one page of audit events. NextCursor is the opaque token to pass back as ListEventsInput.PageAfter on the next call; empty string means this is the last page.

type ListForwardersInput added in v3.0.16

type ListForwardersInput struct {
	// ForwarderType filters to a single destination type. Zero-valued
	// returns every type.
	ForwarderType ForwarderType
	// PageNumber is the 1-based page index. Zero defers to the server
	// default (page 1).
	PageNumber int
	// PageSize is items per page. Zero defers to the server default
	// (1000, max 1000).
	PageSize int
	// MetaTotal asks the server to populate total / total_pages in the
	// returned Pagination. Costs an extra COUNT query.
	MetaTotal bool
}

ListForwardersInput is the filter + pagination input for List.

type ListForwardersPage added in v3.0.16

type ListForwardersPage struct {
	// Forwarders is the slice of forwarders on this page, each bound
	// to the management client so Save / Delete work directly.
	Forwarders []Forwarder
	// Pagination describes the page boundaries and totals (if
	// requested via MetaTotal).
	Pagination Pagination
}

ListForwardersPage is one page of forwarders.

type ListJobsInput added in v3.0.114

type ListJobsInput struct {
	// Enabled filters by enabled/disabled state. Nil returns both.
	Enabled *bool
	// PageNumber is the 1-based page index. Zero defers to the server
	// default (page 1).
	PageNumber int
	// PageSize is items per page. Zero defers to the server default.
	PageSize int
}

ListJobsInput passes filters and pagination to JobsManagement.List.

type ListOption added in v3.0.49

type ListOption func(*listOptions)

ListOption configures a paginated list call. Pass options to any Management list method to request a specific page or page size:

loggers, err := mgmt.Loggers().List(ctx, smplkit.WithPageSize(50))

Omit all options to let the server apply its defaults (page 1, page size 1000). The wrapper does not loop on the caller's behalf — see each list method's docs for the slice it returns.

func WithPageNumber added in v3.0.49

func WithPageNumber(n int) ListOption

WithPageNumber requests a specific 1-based page from a list endpoint. Values < 1 are rejected by the server with a 400.

func WithPageSize added in v3.0.49

func WithPageSize(n int) ListOption

WithPageSize requests a specific page size from a list endpoint. The server caps this at 1000; values outside [1, 1000] are rejected with a 400.

type ListResourceTypesInput added in v3.0.34

type ListResourceTypesInput struct {
	// PageNumber is the 1-based page index. Zero defers to the server default.
	PageNumber int
	// PageSize is items per page. Zero defers to the server default.
	PageSize int
	// MetaTotal asks the server to populate total / total_pages.
	MetaTotal bool
}

ListResourceTypesInput is the pagination input for AuditResourceTypes.List.

type ListRunsInput added in v3.0.114

type ListRunsInput struct {
	// Job scopes the listing to a single job's run history. Empty returns
	// runs across all jobs.
	Job string
	// PageSize is runs per page. Zero defers to the server default.
	PageSize int
	// After is the opaque cursor returned by the previous call. Empty
	// fetches the first page.
	After string
}

ListRunsInput passes filters and cursor pagination to RunsClient.List.

type LiveConfig

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

LiveConfig is a live, dict-like, read-only proxy for a config's resolved values. Returned by ConfigClient.Get. Every read goes through the client's resolved-config cache, so WebSocket updates are picked up automatically.

Customer mutation paths are absent: there is no Set / Put / Delete method on LiveConfig. To mutate configs use the management surface:

client.Manage().Config().Get(ctx, id) // active-record model with Save / Delete

func (*LiveConfig) Get

func (lc *LiveConfig) Get(key string) (interface{}, bool)

Get returns a single resolved value by key. The second return is false if the key is absent. Mirrors Python's `proxy[key]` / `proxy.get(key)` dict-like access.

func (*LiveConfig) Has

func (lc *LiveConfig) Has(key string) bool

Has reports whether a resolved value exists for the given key.

func (*LiveConfig) ID

func (lc *LiveConfig) ID() string

ID returns the config ID this proxy reads from.

func (*LiveConfig) Keys

func (lc *LiveConfig) Keys() []string

Keys returns a snapshot of the resolved key set in unspecified order.

func (*LiveConfig) Len

func (lc *LiveConfig) Len() int

Len returns the number of resolved keys.

func (*LiveConfig) OnChange

func (lc *LiveConfig) OnChange(cb func(*ConfigChangeEvent))

OnChange registers a listener that fires when any item in this config changes. Mirrors Python's `proxy.on_change(fn)` listener-form sugar (rule 11 — the proxy-scoped form of OnChange).

func (*LiveConfig) OnChangeKey

func (lc *LiveConfig) OnChangeKey(key string, cb func(*ConfigChangeEvent))

OnChangeKey registers a listener that fires only when the named item in this config changes. Mirrors `proxy.on_change(item_key=...)`.

func (*LiveConfig) Value

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

Value returns a defensive copy of the latest resolved values.

type LogGroup

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

func (g *LogGroup) ClearAllEnvironmentLevels()

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

func (*LogGroup) ClearEnvironmentLevel

func (g *LogGroup) ClearEnvironmentLevel(env string)

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

func (*LogGroup) ClearLevel

func (g *LogGroup) ClearLevel()

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

func (*LogGroup) Save

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

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

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

func (*LogGroup) SetLevel

func (g *LogGroup) SetLevel(level LogLevel)

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

func (*LogGroup) TypedEnvironments

func (g *LogGroup) TypedEnvironments() map[string]LoggerEnvironment

TypedEnvironments returns a typed, read-only view of per-environment configuration on a LogGroup.

type LogGroupOption

type LogGroupOption func(*LogGroup)

LogGroupOption configures an unsaved LogGroup returned by LoggingClient.NewGroup.

func WithLogGroupName

func WithLogGroupName(name string) LogGroupOption

WithLogGroupName sets the display name for a log group.

func WithLogGroupParent

func WithLogGroupParent(groupID string) LogGroupOption

WithLogGroupParent sets the parent group UUID.

type LogGroupsManagement

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

LogGroupsManagement is the mgmt.log_groups namespace — CRUD against log groups. Split from the older combined LoggingManagement to keep loggers and log groups in distinct namespaces (rule 2).

Obtain one via client.Manage().LogGroups().

func (*LogGroupsManagement) Delete

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

Delete removes a log group by ID.

func (*LogGroupsManagement) Get

Get retrieves a log group by ID.

func (*LogGroupsManagement) List

func (m *LogGroupsManagement) List(ctx context.Context, opts ...ListOption) ([]*LogGroup, error)

List returns one page of log groups for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*LogGroupsManagement) New

func (m *LogGroupsManagement) New(id string, opts ...LogGroupOption) *LogGroup

New returns an unsaved LogGroup with the given ID. Call group.Save(ctx) to persist.

type LogLevel

type LogLevel string

LogLevel represents a smplkit canonical log level.

const (
	// LogLevelTrace is the most verbose level; finer-grained than DEBUG.
	LogLevelTrace LogLevel = "TRACE"
	// LogLevelDebug emits diagnostic detail useful while debugging.
	LogLevelDebug LogLevel = "DEBUG"
	// LogLevelInfo is the default level for routine informational messages.
	LogLevelInfo LogLevel = "INFO"
	// LogLevelWarn signals a non-fatal condition that warrants attention.
	LogLevelWarn LogLevel = "WARN"
	// LogLevelError signals a failure that the caller should handle.
	LogLevelError LogLevel = "ERROR"
	// LogLevelFatal signals a non-recoverable failure.
	LogLevelFatal LogLevel = "FATAL"
	// LogLevelSilent suppresses all output.
	LogLevelSilent LogLevel = "SILENT"
)

Supported LogLevel values, declared in increasing order of severity to match Go's log/slog convention (where higher-severity levels have larger numeric values). LogLevelSilent is the cut-off above any real severity and suppresses all output.

type Logger

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

func (l *Logger) ClearAllEnvironmentLevels()

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

func (*Logger) ClearBaseLevel deprecated

func (l *Logger) ClearBaseLevel()

ClearBaseLevel clears the logger's base level.

Deprecated: Use ClearLevel("") for the unified per-env verb.

func (*Logger) ClearEnvironmentLevel

func (l *Logger) ClearEnvironmentLevel(env string)

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

func (*Logger) ClearLevel

func (l *Logger) ClearLevel(environment string)

ClearLevel clears the level. environment="" clears the logger's base level (causing it to inherit from its parent); non-empty clears the per-env override. Mirrors Python's clear_level(*, environment=None).

func (*Logger) Delete

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

Delete removes the logger from the server. Equivalent to mgmt.Loggers().Delete(ctx, l.ID).

func (*Logger) Save

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

Save persists the logger to the server. PUT has upsert semantics: the server creates the logger if it does not exist. The Logger instance is updated with the server response.

func (*Logger) SetBaseLevel deprecated

func (l *Logger) SetBaseLevel(level LogLevel)

SetBaseLevel sets the logger's base level (no environment scoping).

Deprecated: Use SetLevel(level, "") for the unified per-env verb that mirrors the Python SDK's set_level(level, *, environment=None).

func (*Logger) SetEnvironmentLevel

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

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

func (*Logger) SetLevel

func (l *Logger) SetLevel(level LogLevel, environment string)

SetLevel sets the level. environment="" updates the logger's base level; non-empty scopes to that environment. Mirrors Python's logger.set_level(level, *, environment=None).

func (*Logger) TypedEnvironments

func (l *Logger) TypedEnvironments() map[string]LoggerEnvironment

TypedEnvironments returns a typed, read-only view of per-environment configuration on a Logger. Each value's Level() is a *LogLevel — nil when no override is set for that environment.

type LoggerChangeEvent

type LoggerChangeEvent struct {
	// ID is the normalized logger id whose effective level just moved.
	ID string
	// Level is the newly-applied effective level.
	Level *LogLevel
	// Source identifies the trigger ("websocket", "manual").
	Source string
}

LoggerChangeEvent describes a logger whose effective level was just re-applied. The SDK fires one event per logger per trigger — never a batch / summary event and never a deletion-flavored event. If a trigger removes a logger from server-side tracking, the deleted key itself fires nothing; dependents whose effective level moves fire normal change events through this same payload.

type LoggerEnvironment

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

LoggerEnvironment is the per-environment configuration on a Logger or LogGroup — currently just an optional level override. Frozen.

Mirrors Python's smplkit.logging.models.LoggerEnvironment.

func NewLoggerEnvironment

func NewLoggerEnvironment(level *LogLevel) LoggerEnvironment

NewLoggerEnvironment constructs a LoggerEnvironment. Used by the SDK when parsing server responses.

func (LoggerEnvironment) Level

func (e LoggerEnvironment) Level() *LogLevel

Level returns the per-env level override, or nil if no override is set (in which case inheritance applies).

type LoggerOption

type LoggerOption func(*Logger)

LoggerOption configures an unsaved Logger returned by LoggingClient.New.

func WithLoggerManaged

func WithLoggerManaged(managed bool) LoggerOption

WithLoggerManaged sets whether smplkit controls this logger's level.

func WithLoggerName

func WithLoggerName(name string) LoggerOption

WithLoggerName sets the display name for a logger.

type LoggerSource

type LoggerSource struct {
	// ID is the normalized logger name (e.g. "sqlalchemy.engine").
	ID string
	// Service overrides the client's own service name.
	// Nil means use the client's service.
	Service *string
	// Environment overrides the client's own environment.
	// Nil means use the client's environment.
	Environment *string
	// ResolvedLevel is the effective log level observed in the process.
	ResolvedLevel *LogLevel
}

LoggerSource describes a logger observed in a remote service process. Used with LoggingManagement.RegisterSources to seed source discovery data (e.g. for sample-data loading or cross-service migration) without running the actual service.

func NewLoggerSource

func NewLoggerSource(id string, opts ...LoggerSourceOption) LoggerSource

NewLoggerSource creates a LoggerSource with the given logger ID and options.

type LoggerSourceOption

type LoggerSourceOption func(*LoggerSource)

LoggerSourceOption configures a LoggerSource.

func WithLoggerSourceEnvironment

func WithLoggerSourceEnvironment(env string) LoggerSourceOption

WithLoggerSourceEnvironment sets an explicit environment for the source.

func WithLoggerSourceResolvedLevel

func WithLoggerSourceResolvedLevel(level LogLevel) LoggerSourceOption

WithLoggerSourceResolvedLevel sets the effective log level for the source.

func WithLoggerSourceService

func WithLoggerSourceService(service string) LoggerSourceOption

WithLoggerSourceService sets an explicit service name for the source.

type LoggersManagement

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

LoggersManagement is the mgmt.loggers namespace — CRUD against single loggers (no log groups). Mirrors Python's mgmt.loggers (rule 2 of the cross-SDK overhaul, where loggers and log groups live in distinct flat namespaces).

Obtain one via client.Manage().Loggers().

func (*LoggersManagement) Delete

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

Delete removes a logger by ID.

func (*LoggersManagement) Flush added in v3.0.4

func (m *LoggersManagement) Flush(ctx context.Context) error

Flush sends any pending logger discoveries to the server immediately. Discoveries are buffered by the runtime LoggingClient as adapter hooks fire and on explicit RegisterLogger calls; they are normally drained on a 5-second interval. Call this when you need them sent right away.

Returns nil immediately when no runtime LoggingClient is attached (the management-only client built via NewManagementClient has no discovery buffer — call LoggingManagement.RegisterSources instead to post sources directly).

Mirrors Python's client.manage.loggers.flush().

func (*LoggersManagement) Get

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

Get retrieves a logger by ID. Returns NotFoundError if no match.

func (*LoggersManagement) List

func (m *LoggersManagement) List(ctx context.Context, opts ...ListOption) ([]*Logger, error)

List returns one page of loggers for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*LoggersManagement) New

func (m *LoggersManagement) New(id string) *Logger

New returns an unsaved Logger with the given ID. Call logger.Save(ctx) to persist. The display name defaults to id (rule 9: drop the name kwarg when name and id would normally be identical) and managed defaults to true (every customer using the management API to create a logger is doing so to manage it).

type LoggingClient

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

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

func (*LoggingClient) Flush added in v3.0.4

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

Flush sends any pending logger discoveries to the server immediately via the bulk-register endpoint. Discoveries are buffered as adapter hooks fire (e.g. slog WithGroup creating a sub-handler) and on explicit RegisterLogger calls; they are normally flushed on a 5-second interval. Call this when you need them sent right away — e.g. before exiting a short-lived script. Returns nil immediately when the buffer is empty.

func (*LoggingClient) Install

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

Install hooks the SDK into the application's logging machinery: it runs adapter discovery, fetches managed-logger definitions from the platform, applies resolved levels, and opens the live-updates WebSocket so subsequent server-side level changes propagate.

Safe to call multiple times; only the first call takes effect. There is no companion Stop() — close the parent Client instead.

Mirrors Python's client.logging.install() (rule 4 of the cross-SDK overhaul). The pre-existing Start name is retained as a deprecated shim that simply forwards to Install.

func (*LoggingClient) Management

func (c *LoggingClient) Management() *LoggingManagement

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

func (*LoggingClient) OnChange

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

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

func (*LoggingClient) OnChangeKey

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

OnChangeKey registers a key-scoped change listener.

func (*LoggingClient) Refresh added in v3.0.4

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

Refresh re-fetches managed logger and log-group definitions from the server, re-applies resolved levels to every adapter-known logger, and fires change/deletion listeners (with Source = "manual") for any logger whose effective level changed since the previous fetch.

Use this when the customer wants to bypass the WebSocket and force a fresh sync — e.g. after a known burst of server-side edits, or when running short-lived scripts that don't keep the WS open. Mirrors Python's client.logging.refresh().

func (*LoggingClient) RegisterAdapter

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

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

func (*LoggingClient) RegisterLogger

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 deprecated

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

Start is a deprecated alias for Install.

Deprecated: Use Install.

type LoggingManagement

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

LoggingManagement provides CRUD operations for logger and log group resources. Obtain one via Client.Manage().Loggers() (for the canonical split surface) or LoggingClient.Management() (for the older combined surface).

Owns its generated API client directly; the runtime back-reference is set only when wired into a runtime Client.

func (*LoggingManagement) Delete

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

Delete removes a logger by its ID.

func (*LoggingManagement) DeleteGroup

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

DeleteGroup removes a log group by its ID.

func (*LoggingManagement) Get

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

Get retrieves a logger by its ID.

func (*LoggingManagement) GetGroup

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

GetGroup retrieves a log group by its ID.

func (*LoggingManagement) List

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

List returns one page of loggers for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages. The wrapper does not loop — callers that want every logger should iterate until a short page is returned.

func (*LoggingManagement) ListGroups

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

ListGroups returns one page of log groups for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages. The wrapper does not loop — callers that want every log group should iterate until a short page is returned.

func (*LoggingManagement) New

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

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

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

func (*LoggingManagement) RegisterSources

func (m *LoggingManagement) RegisterSources(ctx context.Context, sources []LoggerSource) error

RegisterSources registers a batch of logger sources observed in external services. This is useful for seeding source-discovery data without running the actual service process — e.g. for sample-data loading or cross-service migration.

type ManagementClient

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

ManagementClient is the management-plane sub-client. Obtain one via Client.Manage() (or via NewManagementClient for a standalone management client with zero construction side effects — no service registration, no metrics, no websocket).

The flat namespaces mirror the Python SDK's SmplManagementClient:

mgmt.Contexts()         // context entity CRUD
mgmt.ContextTypes()     // context-type schemas
mgmt.Environments()     // environments
mgmt.Services()         // services
mgmt.AccountSettings()  // account-level settings
mgmt.Config()           // config CRUD (was client.Config().Management())
mgmt.Flags()            // flag CRUD (was client.Flags().Management())
mgmt.Loggers()          // logger CRUD (split from the old logging mgmt)
mgmt.LogGroups()        // log-group CRUD (split from the old logging mgmt)
mgmt.Audit()            // audit forwarder CRUD
mgmt.Jobs()             // scheduled-job CRUD + runs

func NewManagementClient

func NewManagementClient(cfg ManagementConfig, opts ...ClientOption) (*ManagementClient, error)

NewManagementClient creates a new management-only smplkit client.

Construction has zero side effects: no service registration, no metrics thread, no websocket, no logger discovery, no synchronous outbound HTTP calls. Use this client for setup scripts, CI/CD jobs, admin tools, and anywhere else the goal is CRUD against the platform — not runtime instrumentation.

Mirrors Python's SmplManagementClient (rule 1 of the cross-SDK overhaul). The Go implementation owns its sub-management surfaces directly — no runtime-Client skeleton is constructed.

func (*ManagementClient) AccountSettings

func (m *ManagementClient) AccountSettings() *AccountSettingsManagement

AccountSettings returns the sub-client for account settings get/save.

func (*ManagementClient) Audit added in v3.0.34

func (m *ManagementClient) Audit() *AuditManagement

Audit returns the sub-client for audit forwarder CRUD (mgmt.audit).

func (*ManagementClient) Close

func (m *ManagementClient) Close() error

Close releases HTTP resources held by this management client. No-op for the management client returned from a runtime Client — close the runtime Client instead so its WebSocket / metrics / context flush all unwind in order. For a standalone management client built via NewManagementClient, Close has nothing to release (the underlying http.Client is owned by net/http and pooled there) but is provided for symmetry and to give customers a clean defer point.

func (*ManagementClient) Config

func (m *ManagementClient) Config() *ConfigManagement

Config returns the sub-client for config CRUD (mgmt.config). Mirrors Python's mgmt.config namespace.

func (*ManagementClient) ContextTypes

func (m *ManagementClient) ContextTypes() *ContextTypesManagement

ContextTypes returns the sub-client for context type CRUD operations.

func (*ManagementClient) Contexts

func (m *ManagementClient) Contexts() *ContextsManagement

Contexts returns the sub-client for context registration and read/delete operations.

func (*ManagementClient) Environments

func (m *ManagementClient) Environments() *EnvironmentsManagement

Environments returns the sub-client for environment CRUD operations.

func (*ManagementClient) Flags

func (m *ManagementClient) Flags() *FlagsManagement

Flags returns the sub-client for flag CRUD (mgmt.flags).

func (*ManagementClient) Jobs added in v3.0.114

func (m *ManagementClient) Jobs() *JobsManagement

Jobs returns the Smpl Jobs management sub-client (mgmt.Jobs()).

func (*ManagementClient) LogGroups

func (m *ManagementClient) LogGroups() *LogGroupsManagement

LogGroups returns the sub-client for log-group CRUD (mgmt.log_groups).

func (*ManagementClient) Loggers

func (m *ManagementClient) Loggers() *LoggersManagement

Loggers returns the sub-client for logger CRUD (mgmt.loggers). Split from the older combined LoggingManagement so loggers and log groups live in distinct namespaces.

func (*ManagementClient) Services added in v3.0.88

func (m *ManagementClient) Services() *ServicesManagement

Services returns the sub-client for service CRUD operations.

type ManagementConfig

type ManagementConfig struct {
	// Profile selects an INI section in ~/.smplkit (defaults to "default").
	Profile string
	// APIKey authenticates with the smplkit platform.
	APIKey string
	// BaseDomain is the base domain for API requests (default "smplkit.com").
	BaseDomain string
	// Scheme is the URL scheme (default "https").
	Scheme string
	// Debug enables debug output in the SDK.
	Debug bool
}

ManagementConfig holds the construction-time configuration for a management-only client. Mirrors smplkit.Config but drops the runtime fields (Environment, Service) that don't apply to management work.

All fields are optional. When omitted, the SDK resolves them from SMPLKIT_* environment variables or the ~/.smplkit profile.

type NotFoundError

type NotFoundError struct {
	// Base is the embedded base Error carrying the HTTP status, message,
	// raw response body, and any parsed JSON:API error details.
	Base Error
}

NotFoundError is raised when a requested resource does not exist.

func (*NotFoundError) Error

func (e *NotFoundError) Error() string

Error implements the error interface.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type NumberFlagHandle

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

NumberFlagHandle is a typed handle for a numeric flag.

func (*NumberFlagHandle) Get

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

Get evaluates the flag and returns a typed float64 value.

func (*NumberFlagHandle) OnChange

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

OnChange registers a flag-specific change listener.

type Pagination added in v3.0.47

type Pagination struct {
	// Page is the 1-based page number that served the response.
	Page int
	// Size is the page size that served the response.
	Size int
	// Total is the total number of matching items across all pages.
	// Populated only when the request set MetaTotal=true.
	Total *int
	// TotalPages is the total number of pages at the requested page size.
	// Populated only when the request set MetaTotal=true.
	TotalPages *int
}

Pagination is the offset-pagination meta block returned on every standard list response (ADR-014). Page and Size always reflect the parameters that served the response. Total and TotalPages are populated only when the request set MetaTotal=true.

type PaymentRequiredError added in v3.0.34

type PaymentRequiredError struct {
	// Base is the embedded base Error carrying the HTTP status, message,
	// raw response body, and any parsed JSON:API error details.
	Base Error
}

PaymentRequiredError is raised when the server rejects a request with a 402 — typically because the account's subscription plan doesn't include the required entitlement. Surfaced as a typed error so callers that care about plan-gated paths can errors.As on it; no curated method in the SDK anticipates 402 specifically.

func (*PaymentRequiredError) Error added in v3.0.34

func (e *PaymentRequiredError) Error() string

Error implements the error interface.

func (*PaymentRequiredError) Unwrap added in v3.0.34

func (e *PaymentRequiredError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type ResourceTypeListPage added in v3.0.34

type ResourceTypeListPage struct {
	// ResourceTypes is the slice of resource types on this page.
	ResourceTypes []AuditResourceType
	// Pagination describes the page boundaries and totals (if requested).
	Pagination Pagination
}

ResourceTypeListPage is one page of resource-type slugs.

type Rule

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

func NewRule(description string) *Rule

NewRule creates a new rule builder with the given description.

func (*Rule) Build

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

Build finalizes and returns the rule as a plain map.

Python's Rule(description, *, environment="...") makes environment a required keyword arg at construction. Go has no kwargs, so the builder permits chained Environment(...) and only validates at the AddRule boundary — Flag.AddRule rejects any rule whose Build() output has no "environment" key. The validation is one frame away from the mistake, which is acceptable for the breaking-change tradeoff of keeping NewRule single-arg.

func (*Rule) Environment

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

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

func (*Rule) Serve

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

Serve sets the value returned when this rule matches.

func (*Rule) When

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

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

type Run added in v3.0.114

type Run struct {
	// ID is the server-assigned UUID for this run.
	ID string
	// Job is the id of the job this run belongs to.
	Job string
	// JobVersion is the job's version at the time the run executed.
	JobVersion *int
	// Trigger is why the run exists: "SCHEDULE", "MANUAL" (Run now), or
	// "RERUN".
	Trigger string
	// RerunOf is the source run's id; set only when Trigger is "RERUN".
	RerunOf *string
	// ScheduledFor is the intended fire time for a scheduled run; nil for
	// manual / rerun runs.
	ScheduledFor *time.Time
	// Status is the lifecycle state of the run (e.g. "PENDING",
	// "SUCCEEDED", "FAILED", "CANCELED").
	Status string
	// StartedAt is when execution started.
	StartedAt *time.Time
	// FinishedAt is when execution finished.
	FinishedAt *time.Time
	// PendingDurationMs is the milliseconds the run waited as PENDING
	// before starting.
	PendingDurationMs *int
	// RunDurationMs is the milliseconds the run spent executing.
	RunDurationMs *int
	// TotalDurationMs is the milliseconds from enqueue to finish.
	TotalDurationMs *int
	// FailureReason is why a FAILED run failed; nil otherwise.
	FailureReason *string
	// Error is free-text failure detail, if any.
	Error *string
	// Request is a snapshot of the request that was sent (header values
	// redacted). Forensics only; nil when not available.
	Request map[string]interface{}
	// Result is the outcome of the call (e.g. status, headers, body).
	// Nil when not available.
	Result map[string]interface{}
	// CreatedAt is when the run was enqueued (became PENDING).
	CreatedAt *time.Time
}

Run is one occurrence of a job executing (read-only).

type RunsClient added in v3.0.114

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

RunsClient is the mgmt.Jobs().Runs() surface: read-only run history plus the cancel / rerun run actions.

func (*RunsClient) Cancel added in v3.0.114

func (r *RunsClient) Cancel(ctx context.Context, runID string) (*Run, error)

Cancel cancels a pending run and returns its updated state.

func (*RunsClient) Get added in v3.0.114

func (r *RunsClient) Get(ctx context.Context, runID string) (*Run, error)

Get returns one run by id.

func (*RunsClient) List added in v3.0.114

func (r *RunsClient) List(ctx context.Context, input ListRunsInput) ([]*Run, error)

List returns runs for the authenticated account, newest first. Cursor paginated (ADR-014): pass PageSize and the After cursor from the prior page. Pass Job to scope to a single job's history.

func (*RunsClient) Rerun added in v3.0.114

func (r *RunsClient) Rerun(ctx context.Context, runID string) (*Run, error)

Rerun re-runs a prior run, spawning a new RERUN run.

type Service added in v3.0.88

type Service struct {
	// ID is the service slug (e.g. "user_service").
	ID string
	// Name is the display name.
	Name string
	// CreatedAt is the server creation timestamp (nil for unsaved instances).
	CreatedAt *time.Time
	// UpdatedAt is the last-modified timestamp.
	UpdatedAt *time.Time
	// contains filtered or unexported fields
}

Service represents a smplkit service resource — a backend application or microservice in the customer's stack that contexts can be evaluated against.

Mutate fields and call Save(ctx) to persist.

func (*Service) Delete added in v3.0.88

func (s *Service) Delete(ctx context.Context) error

Delete removes this service from the server. Equivalent to mgmt.Services().Delete(ctx, s.ID).

func (*Service) Save added in v3.0.88

func (s *Service) Save(ctx context.Context) error

Save creates or updates the service on the server. The instance is updated with server-returned fields on success. PUT semantics: creates if CreatedAt is nil, otherwise updates.

type ServicesManagement added in v3.0.88

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

ServicesManagement provides CRUD operations for service resources. Obtain one via ManagementClient.Services().

func (*ServicesManagement) Delete added in v3.0.88

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

Delete removes a service by ID.

func (*ServicesManagement) Get added in v3.0.88

func (m *ServicesManagement) Get(ctx context.Context, id string) (*Service, error)

Get retrieves a single service by ID.

func (*ServicesManagement) List added in v3.0.88

func (m *ServicesManagement) List(ctx context.Context, opts ...ListOption) ([]*Service, error)

List returns one page of services for the account.

Without options the server applies its defaults (page 1, page size 1000). Use WithPageNumber / WithPageSize to walk additional pages.

func (*ServicesManagement) New added in v3.0.88

func (m *ServicesManagement) New(id string, name string) *Service

New returns an unsaved Service. Call svc.Save(ctx) to persist.

type SmplConflictError deprecated

type SmplConflictError = ConflictError

SmplConflictError is a deprecated alias for ConflictError.

Deprecated: Use ConflictError.

type SmplConnectionError deprecated

type SmplConnectionError = ConnectionError

SmplConnectionError is a deprecated alias for ConnectionError.

Deprecated: Use ConnectionError.

type SmplError deprecated

type SmplError = Error

SmplError is a deprecated alias for Error.

Deprecated: Use Error.

type SmplNotFoundError deprecated

type SmplNotFoundError = NotFoundError

SmplNotFoundError is a deprecated alias for NotFoundError.

Deprecated: Use NotFoundError.

type SmplTimeoutError deprecated

type SmplTimeoutError = TimeoutError

SmplTimeoutError is a deprecated alias for TimeoutError.

Deprecated: Use TimeoutError.

type SmplValidationError deprecated

type SmplValidationError = ValidationError

SmplValidationError is a deprecated alias for ValidationError.

Deprecated: Use ValidationError.

type StringFlagHandle

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

StringFlagHandle is a typed handle for a string flag.

func (*StringFlagHandle) Get

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

Get evaluates the flag and returns a typed string value.

func (*StringFlagHandle) OnChange

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

OnChange registers a flag-specific change listener.

type TimeoutError

type TimeoutError struct {
	// Base is the embedded base Error carrying the HTTP status, message,
	// raw response body, and any parsed JSON:API error details.
	Base Error
}

TimeoutError is raised when an operation exceeds its timeout.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

Error implements the error interface.

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

type Usage added in v3.0.114

type Usage struct {
	// Period is the usage period this report covers, as "YYYY-MM" (UTC).
	Period string
	// RunsUsed is the runs metered so far this period.
	RunsUsed int
	// RunsIncluded is the runs included in the plan this period (-1 means
	// unlimited).
	RunsIncluded int
	// ActiveJobs is the number of currently-enabled jobs.
	ActiveJobs int
	// ActiveJobsLimit is the maximum enabled jobs the plan allows (-1
	// means unlimited).
	ActiveJobsLimit int
}

Usage is the current-period usage against the account's plan allotments (read-only).

type ValidationError

type ValidationError struct {
	// Base is the embedded base Error carrying the HTTP status, message,
	// raw response body, and any parsed JSON:API error details.
	Base Error
}

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

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

func (*ValidationError) Unwrap

func (e *ValidationError) Unwrap() error

Unwrap returns the embedded Error so errors.Is/errors.As walk the chain.

Directories

Path Synopsis
internal
debug
Package debug provides the SMPLKIT_DEBUG diagnostic facility.
Package debug provides the SMPLKIT_DEBUG diagnostic facility.
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/audit
Package audit provides primitives to interact with the openapi HTTP API.
Package audit provides primitives to interact with the openapi HTTP API.
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/jobs
Package jobs provides primitives to interact with the openapi HTTP API.
Package jobs 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