devcycle

package module
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 7, 2023 License: MIT Imports: 24 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.6.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")
)

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

  • @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
}

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(sdkKey string, options *DVCOptions, cfg *HTTPConfiguration) (err error)

func (*DevCycleLocalBucketing) SetClientCustomData added in v2.2.0

func (d *DevCycleLocalBucketing) SetClientCustomData(customData string) error

func (*DevCycleLocalBucketing) SetPlatformData

func (d *DevCycleLocalBucketing) SetPlatformData(platformData string) error

func (*DevCycleLocalBucketing) StoreConfig

func (d *DevCycleLocalBucketing) StoreConfig(config string) error

func (*DevCycleLocalBucketing) VariableForUser added in v2.6.0

func (d *DevCycleLocalBucketing) VariableForUser(user []byte, key string, variableType VariableTypeCode) (ret Variable, err error)

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

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