devcycle

package module
v2.14.0 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2024 License: MIT Imports: 26 Imported by: 2

README

DevCycle Go Server SDK.

This SDK supports both cloud bucketing (requests outbound to https://bucketing-api.devcycle.com) as well as local bucketing (requests to a local bucketing engine self-contained in this SDK).

Installation

go get "github.com/devcyclehq/go-server-sdk/v2"
package main
import "github.com/devcyclehq/go-server-sdk/v2"

Getting Started

    sdkKey := os.Getenv("DEVCYCLE_SERVER_SDK_KEY")
	user := devcycle.User{UserId: "test"}

	options := devcycle.Options{
		EnableEdgeDB:                 false,
		EnableCloudBucketing:         false,
		EventFlushIntervalMS:         0,
		ConfigPollingIntervalMS:      10 * time.Second,
		RequestTimeout:               10 * time.Second,
		DisableAutomaticEventLogging: false,
		DisableCustomEventLogging:    false,
	}

	client, _ := devcycle.NewClient(sdkKey, &options)

Usage

To find usage documentation, visit our docs.

Testing

This SDK is supported by our test harness, a test suite shared between all DevCycle SDKs for consistency.

Unit tests can be run with the standard Go testing tools, or with make test. They are run automatically on PRs with the Go race detector enabled. To reproduce this locally, run with RACE=1 make test. Some race detector errors might only show up on Github actions due to differences in how quickly tests are executed.

Configuration

Configuration of the SDK is done through the Options struct.

Logging

By default, logging is disabled to avoid overhead and noise in your logs. To enable it for debugging the SDK, set the devcycle_debug_logging build tag when compiling your project:

go build -tags devcycle_debug_logging ...
Cloud Bucketing

The following options are available when you are using the SDK in Cloud Bucketing mode.

Option Type Description Default
EnableCloudBucketing bool Sets the SDK to Cloud Bucketing mode false
EnableEdgeDB bool Turns on EdgeDB support for Cloud Bucketing false
BucketingAPIURI string The base URI for communicating with the DevCycle Cloud Bucketing service. Can be set if you need to proxy traffic through your own server https://bucketing-api.devcycle.com
Logger util.Logger Allows you to set a custom logger to manage output from the SDK. The default logger will write to stdout and stderr nil
Local Bucketing

The following options are available when you are using the SDK in Local Bucketing mode.

Option Type Description Default
OnInitializedChannel chan bool A callback channel to get notified when the SDK is fully initialized and ready to use nil
EventFlushIntervalMS time.Duration How frequently events are flushed to the backend.
value must be between 500ms and 60s
30000
ConfigPollingIntervalMS time.Duration How frequently the SDK will attempt to reload the feature config.
value must be > 1s
10000
RequestTimeout time.Duration Maximum time to spend retrieving project configurations.
value must be > 5s
5000
DisableAutomaticEventLogging bool Turn off tracking of automated variable events false
DisableCustomEventLogging bool Turns off tracking of custom events submitted via the client.Track() false
MaxEventQueueSize int Maximum size of the event queue before new events get dropped. Higher values can impact memory usage of the SDK.
value must be > 0 and <= 50000.
10000
FlushEventQueueSize int Maximum size of the queue used to prepare events for submission to DevCycle. Higher values can impact memory usage of the SDK.
value must be > 0 and <= 50000.
1000
ConfigCDNURI string The base URI for retrieving your project configuration from DevCycle. Can be set if you need to proxy traffic through your own server https://config-cdn.devcycle.com
EventsAPIURI string The base URI for sending events to DevCycle for analytics tracking. Can be set if you need to proxy traffic through your own server https://events.devcycle.com
Logger util.Logger Allows you to set a custom logger to manage output from the SDK. The default logger will write to stdout and stderr nil

OpenFeature Support

This SDK provides an implementation of the OpenFeature Provider interface. Use the OpenFeatureProvider() method on the DevCycle SDK client to obtain a provider for OpenFeature.

devcycleClient, err := devcycle.NewClient("DEVCYCLE_SERVER_SDK_KEY", &options)
err = openfeature.SetProvider(devcycleClient.OpenFeatureProvider())

Linting

We run golangci/golangci-lint on every PR to catch common errors. You can run the linter locally via the Makefile with:

make lint

Lint failures on PRs will show comments on the "Files changed" tab inline with the code, not on the main Conversation tab.

Documentation

Index

Constants

View Source
const CONFIG_RETRIES = 1
View Source
const DEVCYCLE_USER_ID_KEY = "userId"
View Source
const NATIVE_SDK = true
View Source
const VERSION = "2.14.0"

Variables

View Source
var (
	// ContextOAuth2 takes a oauth2.TokenSource as authentication for the request.
	ContextOAuth2 = contextKey("token")

	// ContextBasicAuth takes BasicAuth as authentication for the request.
	ContextBasicAuth = contextKey("basic")

	// ContextAccessToken takes a string oauth2 access token as authentication for the request.
	ContextAccessToken = contextKey("accesstoken")

	// ContextAPIKey takes an APIKey as authentication for the request
	ContextAPIKey = contextKey("apikey")
)
View Source
var DEFAULT_USER_TIME = time.Time{}

This value will always be set to zero as the user.CreatedDate is not actually used in native bucketing

View Source
var ErrInvalidDefaultValue = errors.New("the default value for variable is not of type Boolean, Number, String, or JSON")
View Source
var ErrQueueFull = bucketing.ErrQueueFull

Functions

func GeneratePlatformData added in v2.9.5

func GeneratePlatformData() *api.PlatformData

func SetLogger added in v2.3.0

func SetLogger(log Logger)

Types

type APIKey

type APIKey struct {
	Key    string
	Prefix string
}

APIKey provides API key based authentication to a request passed via context using ContextAPIKey

type AdvancedOptions added in v2.7.0

type AdvancedOptions struct {
	OverridePlatformData *api.PlatformData
}

type BaseVariable added in v2.9.5

type BaseVariable = api.BaseVariable

type BasicAuth

type BasicAuth struct {
	UserName string `json:"userName,omitempty"`
	Password string `json:"password,omitempty"`
}

BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth

type BatchEventsBody

type BatchEventsBody = api.BatchEventsBody

type BucketedUserConfig

type BucketedUserConfig = api.BucketedUserConfig

type Client added in v2.10.0

type Client struct {
	DevCycleOptions *Options
	// contains filtered or unexported fields
}

DevCycle Client In most cases there should be only one, shared, Client.

func NewClient added in v2.10.0

func NewClient(sdkKey string, options *Options) (*Client, error)

NewClient creates a new API client. optionally pass a custom http.Client to allow for advanced features such as caching.

func NewDVCClient deprecated

func NewDVCClient(sdkKey string, options *Options) (*Client, error)

Deprecated: Use devcycle.NewClient instead

func (*Client) AllFeatures added in v2.10.0

func (c *Client) AllFeatures(user User) (map[string]Feature, error)

Get all features by key for user data

  • @param body

@return map[string]Feature

func (*Client) AllVariables added in v2.10.0

func (c *Client) AllVariables(user User) (map[string]ReadOnlyVariable, error)

func (*Client) ChangeBasePath added in v2.10.0

func (c *Client) ChangeBasePath(path string)

Change base path to allow switching to mocks

func (*Client) Close added in v2.10.0

func (c *Client) Close() (err error)

Close the client and flush any pending events. Stop any ongoing tickers

func (*Client) EventQueueMetrics added in v2.10.0

func (c *Client) EventQueueMetrics() (int32, int32, int32)

func (*Client) FlushEvents added in v2.10.0

func (c *Client) FlushEvents() error

func (*Client) GetRawConfig added in v2.10.9

func (c *Client) GetRawConfig() (config []byte, etag string, err error)

func (*Client) IsLocalBucketing added in v2.11.0

func (c *Client) IsLocalBucketing() bool

func (*Client) OpenFeatureProvider added in v2.11.0

func (c *Client) OpenFeatureProvider() DevCycleProvider

Convenience method for creating a DevCycleProvider from a Client

func (*Client) SetClientCustomData added in v2.10.0

func (c *Client) SetClientCustomData(customData map[string]interface{}) error

func (*Client) SetOptions added in v2.10.0

func (c *Client) SetOptions(dvcOptions Options)

func (*Client) Track added in v2.10.0

func (c *Client) Track(user User, event Event) (bool, error)

func (*Client) Variable added in v2.10.0

func (c *Client) Variable(userdata User, key string, defaultValue interface{}) (result Variable, err error)

Variable - Get variable by key for user data

  • @param body

  • @param key Variable key

  • @param defaultValue Default value

    -@return Variable

func (*Client) VariableValue added in v2.10.0

func (c *Client) VariableValue(userdata User, key string, defaultValue interface{}) (interface{}, error)

VariableValue - Get variable value by key for user data

  • @param body

  • @param key Variable key

  • @param defaultValue Default value

    -@return interface{}

type ClientImpl added in v2.11.0

type ClientImpl interface {
	Variable(userdata User, key string, defaultValue interface{}) (Variable, error)
	IsLocalBucketing() bool
}

type ConfigReceiver added in v2.9.4

type ConfigReceiver interface {
	StoreConfig([]byte, string, string, string) error
	GetRawConfig() []byte
	GetETag() string
	GetLastModified() string
	HasConfig() bool
}

type DVCClient deprecated

type DVCClient = Client

Deprecated: Use devcycle.Client instead

type DVCEvent deprecated

type DVCEvent = api.Event

Deprecated: Use devcycle.Event instead

type DVCOptions deprecated

type DVCOptions = Options

Deprecated: Use devcycle.Options instead

type DVCUser deprecated

type DVCUser = api.User

Deprecated: Use devcycle.User instead

type DevCycleProvider added in v2.11.0

type DevCycleProvider struct {
	Client ClientImpl
}

DevCycleProvider implements the FeatureProvider interface and provides functions for evaluating flags

func (DevCycleProvider) BooleanEvaluation added in v2.11.0

func (p DevCycleProvider) BooleanEvaluation(ctx context.Context, flag string, defaultValue bool, evalCtx openfeature.FlattenedContext) openfeature.BoolResolutionDetail

BooleanEvaluation returns a boolean flag

func (DevCycleProvider) FloatEvaluation added in v2.11.0

func (p DevCycleProvider) FloatEvaluation(ctx context.Context, flag string, defaultValue float64, evalCtx openfeature.FlattenedContext) openfeature.FloatResolutionDetail

FloatEvaluation returns a float flag

func (DevCycleProvider) Hooks added in v2.11.0

func (p DevCycleProvider) Hooks() []openfeature.Hook

Hooks returns hooks

func (DevCycleProvider) IntEvaluation added in v2.11.0

func (p DevCycleProvider) IntEvaluation(ctx context.Context, flag string, defaultValue int64, evalCtx openfeature.FlattenedContext) openfeature.IntResolutionDetail

IntEvaluation returns an int flag

func (DevCycleProvider) Metadata added in v2.11.0

func (p DevCycleProvider) Metadata() openfeature.Metadata

Metadata returns the metadata of the provider

func (DevCycleProvider) ObjectEvaluation added in v2.11.0

func (p DevCycleProvider) ObjectEvaluation(ctx context.Context, flag string, defaultValue interface{}, evalCtx openfeature.FlattenedContext) openfeature.InterfaceResolutionDetail

ObjectEvaluation returns an object flag

func (DevCycleProvider) StringEvaluation added in v2.11.0

func (p DevCycleProvider) StringEvaluation(ctx context.Context, flag string, defaultValue string, evalCtx openfeature.FlattenedContext) openfeature.StringResolutionDetail

StringEvaluation returns a string flag

type DiscardLogger added in v2.3.0

type DiscardLogger = util.DiscardLogger

type EnvironmentConfigManager

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

func NewEnvironmentConfigManager added in v2.9.4

func NewEnvironmentConfigManager(
	sdkKey string,
	localBucketing ConfigReceiver,
	options *Options,
	cfg *HTTPConfiguration,
) (e *EnvironmentConfigManager)

func (*EnvironmentConfigManager) Close

func (e *EnvironmentConfigManager) Close()

func (*EnvironmentConfigManager) GetETag added in v2.12.0

func (e *EnvironmentConfigManager) GetETag() string

func (*EnvironmentConfigManager) GetLastModified added in v2.14.0

func (e *EnvironmentConfigManager) GetLastModified() string

func (*EnvironmentConfigManager) GetRawConfig added in v2.12.0

func (e *EnvironmentConfigManager) GetRawConfig() []byte

func (*EnvironmentConfigManager) HasConfig

func (e *EnvironmentConfigManager) HasConfig() bool

func (*EnvironmentConfigManager) StartPolling added in v2.9.4

func (e *EnvironmentConfigManager) StartPolling(
	interval time.Duration,
)

type ErrorResponse

type ErrorResponse = api.ErrorResponse

Aliases for the types in the api package

type Event added in v2.10.0

type Event = api.Event

type EventFlushCallback added in v2.10.0

type EventFlushCallback func(payloads map[string]FlushPayload) (*FlushResult, error)

type EventManager added in v2.10.0

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

EventManager is responsible for flushing the event queue and reporting events to the server. It wraps an InternalEventQueue which is implemented either natively by the bucketing package or in WASM.

func NewEventManager added in v2.10.0

func NewEventManager(options *Options, localBucketing InternalEventQueue, cfg *HTTPConfiguration, sdkKey string) (eventQueue *EventManager, err error)

func (*EventManager) Close added in v2.10.0

func (e *EventManager) Close() (err error)

func (*EventManager) FlushEvents added in v2.10.0

func (e *EventManager) FlushEvents() (err error)

func (*EventManager) Metrics added in v2.10.0

func (e *EventManager) Metrics() (int32, int32, int32)

func (*EventManager) QueueEvent added in v2.10.0

func (e *EventManager) QueueEvent(user User, event Event) error

func (*EventManager) QueueVariableDefaultedEvent added in v2.10.1

func (e *EventManager) QueueVariableDefaultedEvent(variableKey string, defaultReason string) error

type EventQueueOptions

type EventQueueOptions = api.EventQueueOptions

type Feature

type Feature = api.Feature

type FeatureVariation

type FeatureVariation = api.FeatureVariation

type FlushPayload

type FlushPayload = api.FlushPayload

type FlushResult added in v2.8.0

type FlushResult struct {
	SuccessPayloads          []string
	FailurePayloads          []string
	FailureWithRetryPayloads []string
}

type GenericError

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

GenericError Provides access to the body, error and model on returned errors.

func (GenericError) Body

func (e GenericError) Body() []byte

Body returns the raw bytes of the response

func (GenericError) Error

func (e GenericError) Error() string

Error returns non-empty string if there was an error.

func (GenericError) Model

func (e GenericError) Model() interface{}

Model returns the unpacked model of the error

type HTTPConfiguration

type HTTPConfiguration struct {
	BasePath          string            `json:"basePath,omitempty"`
	ConfigCDNBasePath string            `json:"configCDNBasePath,omitempty"`
	EventsAPIBasePath string            `json:"eventsAPIBasePath,omitempty"`
	Host              string            `json:"host,omitempty"`
	Scheme            string            `json:"scheme,omitempty"`
	DefaultHeader     map[string]string `json:"defaultHeader,omitempty"`
	UserAgent         string            `json:"userAgent,omitempty"`
	HTTPClient        *http.Client
}

func NewConfiguration

func NewConfiguration(options *Options) *HTTPConfiguration

func (*HTTPConfiguration) AddDefaultHeader

func (c *HTTPConfiguration) AddDefaultHeader(key string, value string)

type InternalEventQueue added in v2.10.0

type InternalEventQueue interface {
	QueueEvent(user User, event Event) error
	QueueVariableDefaulted(variableKey, defaultReason string) error
	FlushEventQueue(EventFlushCallback) error
	UserQueueLength() (int, error)
	Metrics() (int32, int32, int32)
}

type LocalBucketing added in v2.9.5

type LocalBucketing interface {
	ConfigReceiver
	InternalEventQueue
	GenerateBucketedConfigForUser(user User) (ret *BucketedUserConfig, err error)
	SetClientCustomData(map[string]interface{}) error
	GetClientUUID() string
	Variable(user User, key string, variableType string) (variable Variable, err error)
	Close()
}

type Logger added in v2.3.0

type Logger = util.Logger

Aliases to support customizing logging

type NativeLocalBucketing added in v2.10.2

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

func NewNativeLocalBucketing added in v2.10.2

func NewNativeLocalBucketing(sdkKey string, platformData *api.PlatformData, options *Options) (*NativeLocalBucketing, error)

func (*NativeLocalBucketing) Close added in v2.10.2

func (n *NativeLocalBucketing) Close()

func (*NativeLocalBucketing) FlushEventQueue added in v2.10.2

func (n *NativeLocalBucketing) FlushEventQueue(callback EventFlushCallback) error

func (*NativeLocalBucketing) GenerateBucketedConfigForUser added in v2.10.2

func (n *NativeLocalBucketing) GenerateBucketedConfigForUser(user User) (ret *BucketedUserConfig, err error)

func (*NativeLocalBucketing) GetClientUUID added in v2.12.0

func (n *NativeLocalBucketing) GetClientUUID() string

func (*NativeLocalBucketing) GetETag added in v2.12.0

func (n *NativeLocalBucketing) GetETag() string

func (*NativeLocalBucketing) GetLastModified added in v2.14.0

func (n *NativeLocalBucketing) GetLastModified() string

func (*NativeLocalBucketing) GetRawConfig added in v2.12.0

func (n *NativeLocalBucketing) GetRawConfig() []byte

func (*NativeLocalBucketing) GetRayId added in v2.13.0

func (n *NativeLocalBucketing) GetRayId() string

func (*NativeLocalBucketing) HasConfig added in v2.12.0

func (n *NativeLocalBucketing) HasConfig() bool

func (*NativeLocalBucketing) Metrics added in v2.10.2

func (n *NativeLocalBucketing) Metrics() (int32, int32, int32)

func (*NativeLocalBucketing) QueueEvent added in v2.10.2

func (n *NativeLocalBucketing) QueueEvent(user User, event Event) error

func (*NativeLocalBucketing) QueueVariableDefaulted added in v2.12.0

func (n *NativeLocalBucketing) QueueVariableDefaulted(variableKey, defaultReason string) error

func (*NativeLocalBucketing) SetClientCustomData added in v2.10.2

func (n *NativeLocalBucketing) SetClientCustomData(customData map[string]interface{}) error

func (*NativeLocalBucketing) StoreConfig added in v2.10.2

func (n *NativeLocalBucketing) StoreConfig(configJSON []byte, eTag, rayId, lastModified string) error

func (*NativeLocalBucketing) UserQueueLength added in v2.10.2

func (n *NativeLocalBucketing) UserQueueLength() (int, error)

func (*NativeLocalBucketing) Variable added in v2.10.2

func (n *NativeLocalBucketing) Variable(user User, variableKey string, variableType string) (Variable, error)

type Options added in v2.10.0

type Options struct {
	EnableEdgeDB                 bool          `json:"enableEdgeDb,omitempty"`
	EnableCloudBucketing         bool          `json:"enableCloudBucketing,omitempty"`
	EventFlushIntervalMS         time.Duration `json:"eventFlushIntervalMS,omitempty"`
	ConfigPollingIntervalMS      time.Duration `json:"configPollingIntervalMS,omitempty"`
	RequestTimeout               time.Duration `json:"requestTimeout,omitempty"`
	DisableAutomaticEventLogging bool          `json:"disableAutomaticEventLogging,omitempty"`
	DisableCustomEventLogging    bool          `json:"disableCustomEventLogging,omitempty"`
	MaxEventQueueSize            int           `json:"maxEventsPerFlush,omitempty"`
	FlushEventQueueSize          int           `json:"minEventsPerFlush,omitempty"`
	ConfigCDNURI                 string
	EventsAPIURI                 string
	OnInitializedChannel         chan bool
	BucketingAPIURI              string
	Logger                       util.Logger
	AdvancedOptions
}

func (*Options) CheckDefaults added in v2.10.0

func (o *Options) CheckDefaults()

type PlatformData

type PlatformData = api.PlatformData

type ReadOnlyVariable

type ReadOnlyVariable = api.ReadOnlyVariable

type SDKEvent

type SDKEvent struct {
	Success             bool   `json:"success"`
	Message             string `json:"message"`
	Error               error  `json:"error"`
	FirstInitialization bool   `json:"firstInitialization"`
}

type User added in v2.10.0

type User = api.User

type UserDataAndEventsBody

type UserDataAndEventsBody = api.UserDataAndEventsBody

type Variable

type Variable = api.Variable

Directories

Path Synopsis
* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs.
* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs.
example

Jump to

Keyboard shortcuts

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