devcycle

package module
v2.9.2 Latest Latest
Warning

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

Go to latest
Published: Mar 22, 2023 License: MIT Imports: 29 Imported by: 3

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("DVC_SERVER_KEY")
	user := devcycle.DVCUser{UserId: "test"}

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

	client, _ := devcycle.NewDVCClient(sdkKey, &dvcOptions)

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.

Documentation

Overview

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

* DevCycle Bucketing API * * Documents the DevCycle Bucketing API which provides and API interface to User Bucketing and for generated SDKs. * * API version: 1.0.0 * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git)

Index

Constants

View Source
const (
	EventType_VariableEvaluated    = "variableEvaluated"
	EventType_AggVariableEvaluated = "aggVariableEvaluated"
	EventType_VariableDefaulted    = "variableDefaulted"
	EventType_AggVariableDefaulted = "aggVariableDefaulted"
)
View Source
const VERSION = "2.9.2"

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

Functions

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 APIResponse

type APIResponse struct {
	*http.Response `json:"-"`
	Message        string `json:"message,omitempty"`
	// Operation is the name of the swagger operation.
	Operation string `json:"operation,omitempty"`
	// RequestURL is the request URL. This value is always available, even if the
	// embedded *http.Response is nil.
	RequestURL string `json:"url,omitempty"`
	// Method is the HTTP method used for the request.  This value is always
	// available, even if the embedded *http.Response is nil.
	Method string `json:"method,omitempty"`
	// Payload holds the contents of the response body (which may be nil or empty).
	// This is provided here as the raw response.Body() reader will have already
	// been drained.
	Payload []byte `json:"-"`
}

func NewAPIResponse

func NewAPIResponse(r *http.Response) *APIResponse

func NewAPIResponseWithError

func NewAPIResponseWithError(errorMessage string) *APIResponse

type AdvancedOptions added in v2.7.0

type AdvancedOptions struct {
	// controls the maximum number of pre-allocated memory blocks used for WASM execution. This influences the maximum
	// string length that can be fit inside of preallocated memory
	// Can be set to -1 to disable pre-allocated memory blocks entirely.
	// This takes \sum_{k=5}^{n+5} 2^k memory usage
	MaxMemoryAllocationBuckets int
	MaxWasmWorkers             int
}

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 struct {
	Batch []UserEventsBatchRecord `json:"batch"`
}

type BucketedUserConfig

type BucketedUserConfig struct {
	Project              Project                     `json:"project"`
	Environment          Environment                 `json:"environment"`
	Features             map[string]Feature          `json:"features"`
	FeatureVariationMap  map[string]string           `json:"featureVariationMap"`
	VariableVariationMap map[string]FeatureVariation `json:"variableVariationMap"`
	Variables            map[string]ReadOnlyVariable `json:"variables"`
	KnownVariableKeys    []float64                   `json:"knownVariableKeys"`
	// contains filtered or unexported fields
}

type BucketingPool added in v2.9.0

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

func NewBucketingPool added in v2.9.0

func NewBucketingPool(ctx context.Context, wasmMain *WASMMain, sdkKey string, options *DVCOptions) (*BucketingPool, error)

func (*BucketingPool) Close added in v2.9.0

func (p *BucketingPool) Close()

func (*BucketingPool) ProcessAll added in v2.9.0

func (p *BucketingPool) ProcessAll(
	operationName string,
	process func(object *BucketingPoolObject) error,
) (err error)

ProcessAll will func the "process" handler function on every object in the pool. It will block until the operation has completed for every object, or there was an error. It naively grabs the longest idle object from the pool each time and checks if it has seen it before. If it has, it will immediately return it and try again.

func (*BucketingPool) SetClientCustomData added in v2.9.0

func (p *BucketingPool) SetClientCustomData(customData []byte) error

func (*BucketingPool) SetConfig added in v2.9.0

func (p *BucketingPool) SetConfig(config []byte) error

func (*BucketingPool) VariableForUser added in v2.9.0

func (p *BucketingPool) VariableForUser(paramsBuffer []byte) (*proto.SDKVariable_PB, error)

type BucketingPoolFactory added in v2.9.0

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

func MakeBucketingPoolFactory added in v2.9.0

func MakeBucketingPoolFactory(wasmMain *WASMMain, sdkKey string, options *DVCOptions, pool *BucketingPool) *BucketingPoolFactory

func (*BucketingPoolFactory) ActivateObject added in v2.9.0

func (f *BucketingPoolFactory) ActivateObject(ctx context.Context, object *pool.PooledObject) error

func (*BucketingPoolFactory) DestroyObject added in v2.9.0

func (f *BucketingPoolFactory) DestroyObject(ctx context.Context, object *pool.PooledObject) error

func (*BucketingPoolFactory) MakeObject added in v2.9.0

func (f *BucketingPoolFactory) MakeObject(ctx context.Context) (*pool.PooledObject, error)

func (*BucketingPoolFactory) PassivateObject added in v2.9.0

func (f *BucketingPoolFactory) PassivateObject(ctx context.Context, object *pool.PooledObject) error

func (*BucketingPoolFactory) ValidateObject added in v2.9.0

func (f *BucketingPoolFactory) ValidateObject(ctx context.Context, object *pool.PooledObject) bool

type BucketingPoolObject added in v2.9.0

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

func (*BucketingPoolObject) FlushEvents added in v2.9.0

func (o *BucketingPoolObject) FlushEvents() ([]FlushPayload, error)

func (*BucketingPoolObject) HandleFlushResults added in v2.9.0

func (o *BucketingPoolObject) HandleFlushResults(result *FlushResult) (err error)

func (*BucketingPoolObject) Initialize added in v2.9.0

func (o *BucketingPoolObject) Initialize(wasmMain *WASMMain, sdkKey string, options *DVCOptions) (err error)

func (*BucketingPoolObject) SetClientCustomData added in v2.9.0

func (o *BucketingPoolObject) SetClientCustomData(clientCustomData *[]byte) (err error)

func (*BucketingPoolObject) StoreConfig added in v2.9.0

func (o *BucketingPoolObject) StoreConfig(config *[]byte) (err error)

type DVCClient

type DVCClient struct {
	DevCycleOptions *DVCOptions
	// contains filtered or unexported fields
}

DVCClient In most cases there should be only one, shared, DVCClient.

func NewDVCClient

func NewDVCClient(sdkKey string, options *DVCOptions) (*DVCClient, error)

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

func (*DVCClient) AllFeatures

func (c *DVCClient) AllFeatures(user DVCUser) (map[string]Feature, error)

DVCClientService Get all features by key for user data

  • @param body

@return map[string]Feature

func (*DVCClient) AllVariables

func (c *DVCClient) AllVariables(user DVCUser) (map[string]ReadOnlyVariable, error)

func (*DVCClient) ChangeBasePath

func (c *DVCClient) ChangeBasePath(path string)

Change base path to allow switching to mocks

func (*DVCClient) Close

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

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

func (*DVCClient) FlushEvents

func (c *DVCClient) FlushEvents() error

func (*DVCClient) SetClientCustomData added in v2.2.0

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

func (*DVCClient) SetOptions

func (c *DVCClient) SetOptions(dvcOptions DVCOptions)

func (*DVCClient) Track

func (c *DVCClient) Track(user DVCUser, event DVCEvent) (bool, error)

func (*DVCClient) Variable

func (c *DVCClient) Variable(userdata DVCUser, key string, defaultValue interface{}) (Variable, error)

DVCClientService Get variable by key for user data using Protobuf encoding

  • @param body

  • @param key Variable key

    -@return Variable

type DVCEvent

type DVCEvent struct {
	Type_       string                 `json:"type"`
	Target      string                 `json:"target,omitempty"`
	CustomType  string                 `json:"customType,omitempty"`
	UserId      string                 `json:"user_id"`
	ClientDate  time.Time              `json:"clientDate"`
	Value       float64                `json:"value,omitempty"`
	FeatureVars map[string]string      `json:"featureVars"`
	MetaData    map[string]interface{} `json:"metaData,omitempty"`
}

type DVCOptions

type DVCOptions 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                       Logger
	UseDebugWASM                 bool
	AdvancedOptions
}

func (*DVCOptions) CheckDefaults

func (o *DVCOptions) CheckDefaults()

type DVCUser

type DVCUser struct {
	// Unique id to identify the user
	UserId string `json:"user_id"`
	// User's email used to identify the user on the dashboard / target audiences
	Email string `json:"email,omitempty"`
	// User's name used to identify the user on the dashboard / target audiences
	Name string `json:"name,omitempty"`
	// User's language in ISO 639-1 format
	Language string `json:"language,omitempty"`
	// User's country in ISO 3166 alpha-2 format
	Country string `json:"country,omitempty"`
	// App Version of the running application
	AppVersion string `json:"appVersion,omitempty"`
	// App Build number of the running application
	AppBuild string `json:"appBuild,omitempty"`
	// User's custom data to target the user with, data will be logged to DevCycle for use in dashboard.
	CustomData map[string]interface{} `json:"customData,omitempty"`
	// User's custom data to target the user with, data will not be logged to DevCycle only used for feature bucketing.
	PrivateCustomData map[string]interface{} `json:"privateCustomData,omitempty"`
	// User's device model
	DeviceModel string `json:"deviceModel,omitempty"`
	// Date the user was created, Unix epoch timestamp format
	LastSeenDate time.Time `json:"lastSeenDate,omitempty"`
}

type DevCycleLocalBucketing

type DevCycleLocalBucketing struct {
	VariableTypeCodes VariableTypeCodes
	// contains filtered or unexported fields
}

func (*DevCycleLocalBucketing) GenerateBucketedConfigForUser

func (d *DevCycleLocalBucketing) GenerateBucketedConfigForUser(user string) (ret BucketedUserConfig, err error)

func (*DevCycleLocalBucketing) Initialize

func (d *DevCycleLocalBucketing) Initialize(wasmMain *WASMMain, sdkKey string, options *DVCOptions) (err error)

func (*DevCycleLocalBucketing) SetClientCustomData added in v2.2.0

func (d *DevCycleLocalBucketing) SetClientCustomData(customData []byte) error

func (*DevCycleLocalBucketing) SetPlatformData

func (d *DevCycleLocalBucketing) SetPlatformData(platformData []byte) error

func (*DevCycleLocalBucketing) StoreConfig

func (d *DevCycleLocalBucketing) StoreConfig(config []byte) error

func (*DevCycleLocalBucketing) VariableForUser_PB added in v2.7.0

func (d *DevCycleLocalBucketing) VariableForUser_PB(serializedParams []byte) (*proto.SDKVariable_PB, error)

* This is a helper function to call the variableForUserPB function in the WASM module. * It takes a serialized protobuf message as input and returns a serialized protobuf message as output.

type DiscardLogger added in v2.3.0

type DiscardLogger struct{}

func (DiscardLogger) Printf added in v2.3.0

func (DiscardLogger) Printf(_ string, _ ...any)

type EdgeDBSettings

type EdgeDBSettings struct {
	Enabled bool `json:"enabled"`
}

type Environment

type Environment struct {
	Id  string `json:"_id"`
	Key string `json:"key"`
}

type EnvironmentConfigManager

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

func (*EnvironmentConfigManager) Close

func (e *EnvironmentConfigManager) Close()

func (*EnvironmentConfigManager) HasConfig

func (e *EnvironmentConfigManager) HasConfig() bool

func (*EnvironmentConfigManager) Initialize

func (e *EnvironmentConfigManager) Initialize(
	sdkKey string,
	localBucketing *DevCycleLocalBucketing,
	bucketingObjectPool *BucketingPool,
	cfg *HTTPConfiguration,
) (err error)

type ErrorResponse

type ErrorResponse struct {
	// Error message
	Message string `json:"message"`
	// Additional error information detailing the error reasoning
	Data interface{} `json:"data,omitempty"`
}

type EventQueue

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

func (*EventQueue) Close

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

func (*EventQueue) FlushEvents

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

func (*EventQueue) Metrics added in v2.8.0

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

func (*EventQueue) QueueAggregateEvent

func (e *EventQueue) QueueAggregateEvent(config BucketedUserConfig, event DVCEvent) error

func (*EventQueue) QueueEvent

func (e *EventQueue) QueueEvent(user DVCUser, event DVCEvent) error

type EventQueueOptions

type EventQueueOptions struct {
	FlushEventsInterval          time.Duration `json:"flushEventsMS"`
	DisableAutomaticEventLogging bool          `json:"disableAutomaticEventLogging"`
	DisableCustomEventLogging    bool          `json:"disableCustomEventLogging"`
}

type Feature

type Feature struct {
	// unique database id
	Id string `json:"_id"`
	// Unique key by Project, can be used in the SDK / API to reference by 'key' rather than _id.
	Key string `json:"key"`
	// Feature type
	Type_ string `json:"type"`
	// Bucketed feature variation
	Variation string `json:"_variation"`
	// Bucketed feature variation key
	VariationKey string `json:"variationKey"`
	// Bucketed feature variation name
	VariationName string `json:"variationName"`
	// Evaluation reasoning
	EvalReason string `json:"evalReason,omitempty"`
}

type FeatureVariation

type FeatureVariation struct {
	Feature   string `json:"_feature"`
	Variation string `json:"_variation"`
}

type FlushPayload

type FlushPayload struct {
	PayloadId  string                  `json:"payloadId"`
	EventCount int                     `json:"eventCount"`
	Records    []UserEventsBatchRecord `json:"records"`
}

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 *DVCOptions) *HTTPConfiguration

func (*HTTPConfiguration) AddDefaultHeader

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

type Logger added in v2.3.0

type Logger interface {
	// Printf - Straight print passthrough
	Printf(format string, a ...any)
	// Infof - Info level print
	Infof(format string, a ...any)
	// Debugf - Debug level print, mostly used for information/tracing
	Debugf(format string, a ...any)
	// Warnf - Warn level print, something that might be a problem
	Warnf(format string, a ...any)
	// Errorf - Error level print - returns an error
	Errorf(format string, a ...any) error
}

type OptInColors

type OptInColors struct {
	Primary   string `json:"primary"`
	Secondary string `json:"secondary"`
}

type OptInSettings

type OptInSettings struct {
	Enabled     bool        `json:"enabled"`
	Title       string      `json:"title"`
	Description string      `json:"description"`
	ImageURL    string      `json:"imageURL"`
	Colors      OptInColors `json:"colors"`
}

type PayloadsAndChannel added in v2.8.0

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

type PlatformData

type PlatformData struct {
	SdkType         string `json:"sdkType"`
	SdkVersion      string `json:"sdkVersion"`
	PlatformVersion string `json:"platformVersion"`
	DeviceModel     string `json:"deviceModel"`
	Platform        string `json:"platform"`
	Hostname        string `json:"hostname"`
}

func (*PlatformData) Default

func (pd *PlatformData) Default() *PlatformData

type Project

type Project struct {
	Id               string          `json:"_id"`
	Key              string          `json:"key"`
	A0OrganizationId string          `json:"a0_organization"`
	Settings         ProjectSettings `json:"settings"`
}

type ProjectSettings

type ProjectSettings struct {
	EdgeDB EdgeDBSettings `json:"edgeDB"`
	OptIn  OptInSettings  `json:"optIn"`
}

type ReadOnlyVariable

type ReadOnlyVariable struct {

	// unique database id
	Id string `json:"_id"`
	// contains filtered or unexported fields
}

type SDKEvent

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

type UserDataAndEventsBody

type UserDataAndEventsBody struct {
	Events []DVCEvent        `json:"events,omitempty"`
	User   *dvcPopulatedUser `json:"user,omitempty"`
}

type UserEventsBatchRecord

type UserEventsBatchRecord struct {
	User   dvcPopulatedUser `json:"user"`
	Events []DVCEvent       `json:"events"`
}

type UserFeatureData

type UserFeatureData struct {
	User        DVCUser `json:"user"`
	FeatureVars map[string]string
}

type Variable

type Variable struct {

	// Default variable value can be a string, number, boolean, or JSON
	DefaultValue interface{} `json:"defaultValue"`
	// Identifies if variable was returned with the default value
	IsDefaulted bool `json:"isDefaulted"`
	// contains filtered or unexported fields
}

type VariableTypeCode added in v2.6.0

type VariableTypeCode int32

type VariableTypeCodes added in v2.6.0

type VariableTypeCodes struct {
	Boolean VariableTypeCode
	Number  VariableTypeCode
	String  VariableTypeCode
	JSON    VariableTypeCode
}

type WASMMain added in v2.7.0

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

func (*WASMMain) Initialize added in v2.7.0

func (d *WASMMain) Initialize(options *DVCOptions) (err error)

Directories

Path Synopsis
example
cloud command
local command

Jump to

Keyboard shortcuts

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