shipd

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 19 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 with no external dependencies. 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.
  • This release uses polling. It has no WebSocket stream, disk cache, remote identity overlay lookup. Supply traits per request.

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

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, and snapshot versions. Evaluation attributes are never included. 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.

Development and releases

Run the checks from this repository's root:

go vet ./...
go test -race ./...
(cd examples/config && go test -race ./...)
go test -run='^$' -bench='^BenchmarkFlagEvaluation$' -benchtime=1x

The SDK is released independently with semantic version tags at the repository root. After committing and pushing a release, publish its tag (for example):

git tag v0.1.0
git push origin v0.1.0
GOPROXY=https://proxy.golang.org go list -m github.com/alasti-company/shipd-go@v0.1.0

Published tags are immutable; release fixes under a new version.

Documentation

Overview

Package shipd evaluates shipd flags locally using periodically refreshed snapshots.

Index

Constants

View Source
const (
	SnapshotSchemaVersion = 1
	// DefaultEndpoint is the edge origin used unless Overrides.UnsafeEndpoint is set.
	DefaultEndpoint = "https://edge.useshipd.com"
	SDKVersion      = "0.1.0"
)

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 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) 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. Request attributes remain local; evaluation telemetry includes only the user ID.

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

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
	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 {
	SDKKey          string
	Defaults        map[string]any
	RefreshInterval 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 {
	// 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.

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