shipd

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2026 License: Apache-2.0 Imports: 27 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

shipd Go SDK

A Go 1.23+ server SDK. Streaming uses github.com/coder/websocket. Evaluates flags locally from an environment snapshot. One client is safe to share across goroutines; pass an evaluation context for each request.

Install

go get github.com/alasti-company/shipd-go

Use

package main

import (
    "context"
    "log"
    "os"
    "time"

    shipd "github.com/alasti-company/shipd-go"
)

func main() {
    client, err := shipd.New(shipd.Options{
        SDKKey: os.Getenv("SHIPD_SDK_KEY"),
        Defaults: map[string]any{
            "new-checkout":     false,
            "search-variant":   "control",
            "max-retries":      3,
            "checkout-payload": map[string]any{"mode": "strict"},
        },
    })
    if err != nil {
        log.Fatal(err)
    }
    defer client.Shutdown(context.Background())

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    err = client.Ready(ctx)
    cancel()
    if err != nil {
        log.Printf("Using flag defaults while the SDK retries: %v", err)
    }

    user := shipd.EvaluationContext{
        UserID:     "usr_8f2k19",
        Attributes: map[string]any{"plan": "pro"},
    }
    log.Println("New checkout:", client.IsEnabled("new-checkout", user))
    log.Println("Search variant:", client.GetVariant("search-variant", user))
    log.Println("Max retries:", client.GetNumber("max-retries", user))
    log.Println("Checkout payload:", client.GetJSON("checkout-payload", user))
}

Behavior

  • Initial asynchronous GET /sdk/v1/snapshot; polls every 30 seconds using ETags.
  • Evaluation makes no network calls. Failed requests keep the last valid snapshot.
  • Before the first snapshot, or for an unknown flag, configured defaults apply. Built-in defaults are false, "control", 0, and an empty JSON object.
  • Disabled flags use the snapshot's default. Weighted rules without a bucket identity are skipped. Weighted fallthrough without an identity uses the snapshot default.
  • Supports all attribute operators, percentage rollouts, AND/OR groups, compiled audiences, explicit audience IDs, and weighted variations.
  • FNV-1a bucketing uses UTF-16 code units, matching TypeScript rollout cohorts.
  • Malformed snapshots and unsupported schema versions are rejected as a whole. Delayed responses never replace a snapshot with a lower version.
  • JSON results are detached from client state; decoded numbers are float64.
  • Optional ticket-authenticated WebSocket updates (Stream: true) retain polling as a fallback and retry when the HTTP snapshot lags a notification.
  • Optional durable snapshot cache (SnapshotCache) supports offline starts and ETags.
  • Default Context merges below per-call attributes; explicitly empty SegmentIDs replaces default audiences. UserIDPresent permits an explicitly empty user ID.
  • Revision and Subscribe expose snapshot changes. Identify records telemetry without changing the evaluation identity on this shared server client.

Evaluate returns Result with Value, Reason, RuleID, and SnapshotVersion. Evaluation continues to work after Close using the last snapshot/defaults. LastError exposes the most recent request error; a successful refresh or flush clears it. Ready(ctx) returns nil once a snapshot (or Bootstrap) loads, or the initial fetch error as soon as that attempt fails; polling keeps trying unless disabled.

Options

Option Default / behavior
SDKKey Required server SDK key
Defaults JSON-compatible values by flag key; copied on construction
RefreshInterval 30 * time.Second; zero selects default
ReadyTimeout 5 * time.Second; negative returns immediately with defaults
Context Default evaluation context; per-call values win
Cache Optional SnapshotCache adapter with Load and Save
Stream false; enable WebSocket updates using short-lived edge tickets
OnError Callback for fetch, stream, cache, and event delivery errors
AnonymousID Optional anonymous correlation ID sent with evaluation events
AutomaticTraits false; opt into edge location traits under explicit context
AutomaticTraitSeed Location trait seed above edge traits, below explicit context
DisableFetchTimeout false; disable per-request timeout, retaining context deadlines
FetchTimeout 10 * time.Second; bounds the whole request, including body reads
DisablePolling false; initial fetch still runs; use Refresh(ctx) manually
DisableEvents false; disables evaluation and identify telemetry
FlushAt 50; flush once this many events are buffered (max 200, <0 off)
FlushInterval 5 * time.Second; periodic event flush; negative disables it
Bootstrap Snapshot JSON served until a newer fetch; client is ready at once
Overrides UnsafeEndpoint replaces the edge; dev/test only (gets SDK key)
HTTPClient Optional custom Do(*http.Request) implementation

Overrides.StreamEndpoint defaults to https://ws.useshipd.com; development and tests can supply an HTTP(S) or WS(S) gateway URL. The SDK key is used only to mint tickets over HTTP; the WebSocket receives the short-lived ticket.

The default HTTP client rejects redirects. Custom HTTP clients control their own redirect behavior. No automatic geographic traits are inferred for server keys.

Events and shutdown

Events flush every FlushInterval (five seconds) and as soon as FlushAt (50) events are buffered. The buffer retains at most 200 entries, dropping oldest entries on overflow (DroppedEvents counts them); failed batches are retried on the next interval. SnapshotVersion reports the loaded version without recording an event. Events carry flag values, user IDs, reasons, snapshot versions, anonymous correlation IDs, and up to 100 scalar evaluation traits. Diagnostic events also report errors, version changes, and fetch/propagation timings. Set DisableEvents: true to disable telemetry.

Identify queues identity traits for shipd audience insights; it does not change the context used for evaluation:

err := client.Identify(shipd.Identity{
    UserID: "usr_8f2k19",
    Traits: map[string]any{"plan": "pro"},
})

Traits must be strings, finite numbers, booleans, or nil. Identify supports at most 100 traits and follows the edge's identifier and string length limits.

Stop accepting requests, then call Shutdown with a bounded context. It delivers pending events and closes the client, and returns the flush error if delivery fails:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
err := client.Shutdown(ctx)
cancel()

Events recorded after Shutdown starts are not delivered. Close stops immediately without delivering events. Both are idempotent, cancel in-flight requests, and wait for background work.

Snapshot errors can be matched with errors.Is: ErrMalformedSnapshot and ErrUnsupportedSchema. ErrClosed reports use after close. A custom HTTP client must honor request context cancellation for shutdown and request timeouts to work.

Evaluation values that exceed the event payload limit are omitted from telemetry. Identify events that exceed the payload limit return a validation error. Flush splits batches to respect the edge limit of 100 events and 256 KiB per request.

Definitions and generated accessors

Author definitions with config.ShipdConfig from github.com/alasti-company/shipd-go/config in shipd.config.go. The shared CLI reads this Go source directly and automatically generates Go accessors after push and pull. Run shipd types gen to regenerate locally.

Install the CLI with npm install -g @shipdit/cli (Node.js 22.12+), then run shipd login, shipd diff, and shipd push. Your Go application does not need Node.js at runtime. Validate definitions in your own tests with Config.Validate().

Rules in code

Use FlagDefinition.Targeting to declare an environment's enabled state, ordered rules, and fallthrough. A nil Targeting preserves dashboard rules and enabled state; an explicit empty Rules slice clears rules. Optional FlagDefinition.Traits declares this flag's accepted evaluation inputs.

Run shipd diff before shipd push to review changes. Production targeting changes follow the dashboard draft and approval workflow; flag definitions and trait contracts update project-wide immediately. Use shipd pull to download published dashboard state. Pull regenerates the source file, replacing comments and helper code, so review the diff before committing.

Generated accessors include per-flag trait structs. Their fields are pointers so that zero values differ from missing inputs. Context(userID) returns an error when required fields are nil; it preserves explicit false, 0, and empty strings.

See the Go SDK guide, configuration examples, and sync conflict guide.

TypeScript parity

See PARITY.md for the shipdit@0.6.0 server feature map, API conventions, browser-only exclusions, and reproducible cross-language checks.

Subscribe and OnError callbacks run outside the state mutex and may evaluate flags. Return promptly; do not call blocking lifecycle methods (Refresh, Flush, Close, Shutdown) from callbacks. Callback panics are contained. Cache adapters must honor context cancellation and should namespace storage by SDK key and edge endpoint so environments never share a cache entry.

Documentation

Overview

Package shipd evaluates shipd flags locally using periodically refreshed snapshots.

Index

Constants

View Source
const (
	SnapshotSchemaVersion  = 1
	StreamProtocolVersion  = 1
	ControlPlaneAPIVersion = 1
	DefaultStreamEndpoint  = "https://ws.useshipd.com"
	// DefaultEndpoint is the edge origin used unless Overrides.UnsafeEndpoint is set.
	DefaultEndpoint = "https://edge.useshipd.com"
	SDKVersion      = "0.2.0" // x-release-please-version

)

Variables

View Source
var (
	// ErrMalformedSnapshot reports a snapshot that failed validation. The client
	// keeps its last valid snapshot.
	ErrMalformedSnapshot = errors.New("shipd: malformed snapshot ignored")
	// ErrUnsupportedSchema reports a snapshot schema newer than this SDK. Upgrade
	// the SDK; the client keeps its last valid snapshot.
	ErrUnsupportedSchema = errors.New("shipd: unsupported snapshot schema version")
)
View Source
var ErrClosed = errors.New("shipd: client is closed")

ErrClosed is returned by Ready, Refresh, Flush, and Identify after Close or Shutdown. Evaluation keeps working after close.

Functions

This section is empty.

Types

type CachedSnapshot added in v0.2.0

type CachedSnapshot struct {
	Snapshot []byte
	ETag     string
}

CachedSnapshot is the last valid wire snapshot and its HTTP entity tag.

type Client

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

Client is safe for concurrent use. Keep one client per environment per process.

func New

func New(options Options) (*Client, error)

New starts an initial asynchronous fetch and background polling. Construction errors concern configuration only; network errors are available via LastError.

func (*Client) AnonymousID added in v0.2.0

func (c *Client) AnonymousID() string

AnonymousID returns the configured correlation identifier. Servers never rotate it.

func (*Client) Close

func (c *Client) Close() error

Close stops polling, cancels requests, and waits for background work without flushing events; use Shutdown to deliver them first. Evaluation after Close still serves the last snapshot/defaults. Close implements io.Closer.

func (*Client) DroppedEvents

func (c *Client) DroppedEvents() uint64

DroppedEvents reports how many diagnostic events were discarded because the buffer was full, for example while the edge was unreachable.

func (*Client) Evaluate

func (c *Client) Evaluate(key string, ctx EvaluationContext) Result

Evaluate returns details and records a bounded diagnostic event including the user ID and up to 100 scalar traits. DisableEvents suppresses telemetry.

func (*Client) Flush

func (c *Client) Flush(ctx context.Context) (err error)

Flush sends pending events. Failed batches are retained for a later retry; the buffer retains at most 200 events, dropping the oldest on overflow (see DroppedEvents). The client also flushes once FlushAt events are buffered.

func (*Client) GetJSON

func (c *Client) GetJSON(key string, ctx EvaluationContext) any

GetJSON evaluates a JSON flag for ctx and returns a copy the caller may modify. Objects decode as map[string]any and numbers as float64. It falls back to the configured default, then to an empty object.

func (*Client) GetNumber

func (c *Client) GetNumber(key string, ctx EvaluationContext) float64

GetNumber evaluates a number flag for ctx. JSON numbers are float64. It falls back to the configured default, then to 0.

func (*Client) GetVariant

func (c *Client) GetVariant(key string, ctx EvaluationContext) string

GetVariant evaluates a variant flag for ctx. It falls back to the configured default, then to "control".

func (*Client) Identify

func (c *Client) Identify(identity Identity) error

Identify queues an identify event. Flush delivers it. Traits must be scalar JSON values or nil, matching the edge identify contract.

func (*Client) IsEnabled

func (c *Client) IsEnabled(key string, ctx EvaluationContext) bool

IsEnabled evaluates a boolean flag for ctx. It never makes a network request. Before a snapshot loads, for an unknown key, or when the flag serves a non-boolean value, it returns the configured default or false.

func (*Client) LastError

func (c *Client) LastError() error

LastError reports the most recent background/request failure. A successful refresh or flush clears it. Evaluation never requires this method to succeed.

func (*Client) Ready

func (c *Client) Ready(ctx context.Context) (err error)

Ready waits for the initial snapshot fetch. It returns nil once a valid snapshot (or Bootstrap) is loaded, or the initial fetch error as soon as that attempt fails; evaluation then serves defaults and polling may still recover. A bounded context is recommended.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context) (err error)

Refresh fetches a snapshot now. Requests are serialized so an old ETag cannot race a newer snapshot. Failures preserve the complete last valid snapshot.

func (*Client) Reset added in v0.2.0

func (c *Client) Reset()

Reset is a no-op on server clients, which hold no mutable per-user identity.

func (*Client) Revision added in v0.2.0

func (c *Client) Revision() uint64

Revision is the monotonic generation of snapshot or automatic trait changes.

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

Shutdown flushes pending events within ctx, then closes the client. It returns the flush error, if any; the client is closed either way. Events recorded after Shutdown starts are not delivered. Use it for graceful shutdown with a bounded context. Repeated calls are safe.

func (*Client) SnapshotVersion

func (c *Client) SnapshotVersion() (version int64, ok bool)

SnapshotVersion reports the loaded snapshot version without recording an evaluation. ok is false until the first valid snapshot arrives.

func (*Client) Subscribe added in v0.2.0

func (c *Client) Subscribe(listener func()) func()

Subscribe registers a change listener and returns an idempotent unsubscribe. Listeners run outside the state lock, may evaluate or unsubscribe, and must return promptly. Do not call blocking lifecycle methods from a listener. A callback already copied for delivery can run after unsubscribe returns.

type EvaluationContext

type EvaluationContext struct {
	UserID string
	// UserIDPresent distinguishes an explicitly empty UserID from an omitted one.
	// Nonempty UserID values are always present. Empty IDs do not provide a bucket.
	UserIDPresent bool
	Attributes    map[string]any
	SegmentIDs    []string
}

EvaluationContext is request-scoped. Attributes should contain strings, numbers, booleans, or nil. The client never changes the supplied context.

type HTTPClient

type HTTPClient interface {
	Do(*http.Request) (*http.Response, error)
}

HTTPClient is implemented by *http.Client.

type Identity

type Identity struct {
	UserID      string
	AnonymousID string
	Name        string
	Traits      map[string]any
}

Identity is sent to shipd for audience insights. It does not set a global evaluation context; server applications pass context separately per request.

type Options

type Options struct {
	// Context supplies defaults merged under each evaluation's context.
	Context EvaluationContext
	// Cache stores validated snapshots and ETags. Implementations must honor ctx.
	Cache SnapshotCache
	// OnError receives background errors. Callbacks must return promptly and must
	// not call blocking lifecycle methods (Refresh, Flush, Shutdown, Close).
	OnError func(error)
	// Stream enables ticket-authenticated WebSocket invalidations; polling remains active.
	Stream bool
	// AnonymousID correlates evaluation events with an anonymous browser session.
	AnonymousID string
	// AutomaticTraits opts into location traits supplied by the edge, below explicit context.
	AutomaticTraits    bool
	AutomaticTraitSeed map[string]string
	// DisableFetchTimeout allows requests to use only their caller/lifecycle deadline.
	DisableFetchTimeout bool
	SDKKey              string
	Defaults            map[string]any
	RefreshInterval     time.Duration
	// ReadyTimeout bounds Ready even when its caller supplies no deadline (default
	// 5 seconds). Negative returns immediately with defaults, like readyTimeoutMs: 0.
	ReadyTimeout   time.Duration
	FetchTimeout   time.Duration
	DisablePolling bool
	DisableEvents  bool
	// FlushAt flushes events once this many are buffered (default 50, at most 200).
	// A negative value flushes on FlushInterval only.
	FlushAt int
	// FlushInterval flushes buffered events periodically (default 5 seconds).
	// A negative value disables timed flushes; events then flush at FlushAt, on
	// Flush, or on Shutdown.
	FlushInterval time.Duration
	// Bootstrap is a snapshot (the JSON body of GET /sdk/v1/snapshot) served until
	// a newer one is fetched. It makes the client ready immediately; use it for
	// tests and offline starts. Invalid snapshots fail New.
	Bootstrap []byte
	// Overrides changes where the client connects. Production apps should not set it.
	Overrides Overrides
	// HTTPClient may supply a custom transport. Every request also has FetchTimeout.
	HTTPClient HTTPClient
}

Options configures one client per process. Zero durations select the defaults. Set DisablePolling to fetch only the initial snapshot (or refresh manually).

type Overrides

type Overrides struct {
	StreamEndpoint string
	// UnsafeEndpoint replaces the edge origin (https://edge.useshipd.com) that
	// receives your SDK key. Unsafe: for shipd development and tests only.
	UnsafeEndpoint string
}

Overrides changes where the client connects.

type Result

type Result struct {
	Key             string
	Value           any
	Reason          string
	RuleID          string
	SnapshotVersion *int64
}

Result describes a local evaluation. Value is a detached JSON-compatible value.

type SnapshotCache added in v0.2.0

type SnapshotCache interface {
	Load(context.Context) (*CachedSnapshot, error)
	Save(context.Context, CachedSnapshot) error
}

SnapshotCache is a durable cache adapter. Clients validate loaded data before use. Load may return nil when empty. Save receives a detached copy.

Directories

Path Synopsis
Package config defines shipd flags in Go.
Package config defines shipd flags in Go.
examples
basic command
basic/flags
Code generated by shipd types gen --language go; DO NOT EDIT.
Code generated by shipd types gen --language go; DO NOT EDIT.

Jump to

Keyboard shortcuts

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