acore

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Mar 13, 2023 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultBatchSize = 250

This constant sets the default batch size used by client instances if none was explicitly set.

View Source
const DefaultEndpoint = "https://t.commonfate.io"
View Source
const DefaultInterval = 5 * time.Second

This constant sets the default flush interval used by client instances if none was explicitly set.

View Source
const SIZE_DEFAULT = 50_000

Variables

View Source
var (
	// This error is returned by methods of the `Client` interface when they are
	// called after the client was already closed.
	ErrClosed = errors.New("the client was already closed")

	// This error is used to notify the application that too many requests are
	// already being sent and no more messages can be accepted.
	ErrTooManyRequests = errors.New("too many requests are already in-flight")

	// This error is used to notify the client callbacks that a message send
	// failed because the JSON representation of a message exceeded the upper
	// limit.
	ErrMessageTooBig = errors.New("the message exceeds the maximum allowed size")
)

Functions

This section is empty.

Types

type APIMessage

type APIMessage interface{}

type Alias

type Alias struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string

	Alias      string
	DistinctId string
	Timestamp  time.Time
}

This type represents object sent in a alias call

func (Alias) APIfy

func (msg Alias) APIfy() APIMessage

func (Alias) Validate

func (msg Alias) Validate() error

type AliasInApi

type AliasInApi struct {
	Type           string    `json:"type"`
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	Properties AliasInApiProperties `json:"properties"`

	Event string `json:"event"`
}

type AliasInApiProperties

type AliasInApiProperties struct {
	DistinctId string `json:"distinct_id"`
	Alias      string `json:"alias"`
	Lib        string `json:"$lib"`
	LibVersion string `json:"$lib_version"`
}

type Backo

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

func DefaultBacko

func DefaultBacko() *Backo

Creates a backo instance with the following defaults:

base: 100 milliseconds
factor: 2
jitter: 0
cap: 10 seconds

func NewBacko

func NewBacko(base time.Duration, factor uint8, jitter float64, cap time.Duration) *Backo

Creates a backo instance with the given parameters

func (*Backo) Duration

func (backo *Backo) Duration(attempt int) time.Duration

Duration returns the backoff interval for the given attempt.

func (*Backo) NewTicker

func (b *Backo) NewTicker() *Ticker

func (*Backo) Sleep

func (backo *Backo) Sleep(attempt int)

Sleep pauses the current goroutine for the backoff interval for the given attempt.

type Callback

type Callback interface {

	// This method is called for every message that was successfully sent to
	// the API.
	Success(APIMessage)

	// This method is called for every message that failed to be sent to the
	// API and will be discarded by the client.
	Failure(APIMessage, error)
}

Values implementing this interface are used by analytics clients to notify the application when a message send succeeded or failed.

Callback methods are called by a client's internal goroutines, there are no guarantees on which goroutine will trigger the callbacks, the calls can be made sequentially or in parallel, the order doesn't depend on the order of messages were queued to the client.

Callback methods must return quickly and not cause long blocking operations to avoid interferring with the client's internal work flow.

type Capture

type Capture struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string

	DistinctId string
	Event      string
	Timestamp  time.Time
	Properties Properties
	Groups     Groups
}

This type represents object sent in a capture call

func (Capture) APIfy

func (msg Capture) APIfy() APIMessage

func (Capture) Validate

func (msg Capture) Validate() error

type CaptureInApi

type CaptureInApi struct {
	Type           string    `json:"type"`
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	DistinctId string     `json:"distinct_id"`
	Event      string     `json:"event"`
	Properties Properties `json:"properties"`
}

type Client

type Client interface {
	io.Closer

	// Queues a message to be sent by the client when the conditions for a batch
	// upload are met.
	// This is the main method you'll be using, a typical flow would look like
	// this:
	//
	//	client := analytics.New(writeKey)
	//	...
	//	client.Enqueue(analytics.Track{ ... })
	//	...
	//	client.Close()
	//
	// The method returns an error if the message queue not be queued, which
	// happens if the client was already closed at the time the method was
	// called or if the message was malformed.
	Enqueue(Message) error

	// EndpointURL returns the configured analytics endpoint
	EndpointURL() string
}

This interface is the main API exposed by the analytics package. Values that satsify this interface are returned by the client constructors provided by the package and provide a way to send messages via the HTTP API.

func New

func New() Client

Instantiate a new client that uses the write key passed as first argument to send messages to the backend. The client is created with the default configuration.

func NewTestWithConfig

func NewTestWithConfig(t *testing.T, config Config, tc TestConfig) Client

func NewWithConfig

func NewWithConfig(config Config) (cli Client, err error)

Instantiate a new client that uses the write key and configuration passed as arguments to send messages to the backend. The function will return an error if the configuration contained impossible values (like a negative flush interval for example). When the function returns an error the returned client will always be nil.

type Config

type Config struct {

	// The endpoint to which the client connect and send their messages, set to
	// `DefaultEndpoint` by default.
	Endpoint string

	// The flushing interval of the client. Messages will be sent when they've
	// been queued up to the maximum batch size or when the flushing interval
	// timer triggers.
	Interval time.Duration

	// The HTTP transport used by the client, this allows an application to
	// redefine how requests are being sent at the HTTP level (for example,
	// to change the connection pooling policy).
	// If none is specified the client uses `http.DefaultTransport`.
	Transport http.RoundTripper

	// The logger used by the client to output info or error messages when that
	// are generated by background operations.
	// If none is specified the client uses a standard logger that outputs to
	// `os.Stderr`.
	Logger Logger

	// The callback object that will be used by the client to notify the
	// application when messages sends to the backend API succeeded or failed.
	Callback Callback

	// The maximum number of messages that will be sent in one API call.
	// Messages will be sent when they've been queued up to the maximum batch
	// size or when the flushing interval timer triggers.
	// Note that the API will still enforce a 500KB limit on each HTTP request
	// which is independent from the number of embedded messages.
	BatchSize int

	// When set to true the client will send more frequent and detailed messages
	// to its logger.
	Verbose bool

	// The retry policy used by the client to resend requests that have failed.
	// The function is called with how many times the operation has been retried
	// and is expected to return how long the client should wait before trying
	// again.
	// If not set the client will fallback to use a default retry policy.
	RetryAfter func(int) time.Duration
	// contains filtered or unexported fields
}

Instances of this type carry the different configuration options that may be set when instantiating a client.

Each field's zero-value is either meaningful or interpreted as using the default value defined by the library.

type ConfigError

type ConfigError struct {

	// A human-readable message explaining why the configuration field's value
	// is invalid.
	Reason string

	// The name of the configuration field that was carrying an invalid value.
	Field string

	// The value of the configuration field that caused the error.
	Value interface{}
}

Returned by the `NewWithConfig` function when the one of the configuration fields was set to an impossible value (like a negative duration).

func (ConfigError) Error

func (e ConfigError) Error() string

type FieldError

type FieldError struct {

	// The human-readable representation of the type of structure that wasn't
	// initialized properly.
	Type string

	// The name of the field that wasn't properly initialized.
	Name string

	// The value of the field that wasn't properly initialized.
	Value interface{}
}

Instances of this type are used to represent errors returned when a field was no initialize properly in a structure passed as argument to one of the functions of this package.

func (FieldError) Error

func (e FieldError) Error() string

type GroupIdentify

type GroupIdentify struct {
	Type string
	Key  string

	DistinctId string
	Timestamp  time.Time
	Properties Properties
}

func (GroupIdentify) APIfy

func (msg GroupIdentify) APIfy() APIMessage

func (GroupIdentify) Validate

func (msg GroupIdentify) Validate() error

type GroupIdentifyInApi

type GroupIdentifyInApi struct {
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	Event      string     `json:"event"`
	DistinctId string     `json:"distinct_id"`
	Properties Properties `json:"properties"`
}

type Groups

type Groups map[string]interface{}

func NewGroups

func NewGroups() Groups

func (Groups) Set

func (p Groups) Set(name string, value interface{}) Groups

type Identify

type Identify struct {
	// This field is exported for serialization purposes and shouldn't be set by
	// the application, its value is always overwritten by the library.
	Type string

	DistinctId string
	Timestamp  time.Time
	Properties Properties
	Groups     Groups
}

This type represents object sent in an identify call

func (Identify) APIfy

func (msg Identify) APIfy() APIMessage

func (Identify) Validate

func (msg Identify) Validate() error

type IdentifyInApi

type IdentifyInApi struct {
	Type           string    `json:"type"`
	Library        string    `json:"library"`
	LibraryVersion string    `json:"library_version"`
	Timestamp      time.Time `json:"timestamp"`

	Event      string     `json:"event"`
	DistinctId string     `json:"distinct_id"`
	Properties Properties `json:"properties"`
	Set        Properties `json:"$set"`
}

type Logger

type Logger interface {

	// Analytics clients call this method to log regular messages about the
	// operations they perform.
	// Messages logged by this method are usually tagged with an `INFO` log
	// level in common logging libraries.
	Logf(format string, args ...interface{})

	// Analytics clients call this method to log errors they encounter while
	// sending events to the backend servers.
	// Messages logged by this method are usually tagged with an `ERROR` log
	// level in common logging libraries.
	Errorf(format string, args ...interface{})
}

Instances of types implementing this interface can be used to define where the analytics client logs are written.

func StdLogger

func StdLogger(logger *log.Logger) Logger

This function instantiate an object that statisfies the analytics.Logger interface and send logs to standard logger passed as argument.

type Message

type Message interface {

	// Validate validates the internal structure of the message, the method must return
	// nil if the message is valid, or an error describing what went wrong.
	Validate() error
	APIfy() APIMessage
	// contains filtered or unexported methods
}

This interface is used to represent analytics objects that can be sent via a client.

Types like analytics.Capture, analytics.Alias, etc... implement this interface and therefore can be passed to the analytics.Client.Send method.

type NoopClient

type NoopClient struct{}

NoopClient implements acore.Client but does nothing.

func (*NoopClient) Close

func (c *NoopClient) Close() error

func (*NoopClient) EndpointURL

func (c *NoopClient) EndpointURL() string

func (*NoopClient) Enqueue

func (c *NoopClient) Enqueue(Message) error

type Properties

type Properties map[string]interface{}

This type is used to represent properties in messages that support it. It is a free-form object so the application can set any value it sees fit but a few helper method are defined to make it easier to instantiate properties with common fields. Here's a quick example of how this type is meant to be used:

analytics.Page{
	DistinctId: "0123456789",
	Properties: analytics.NewProperties()
		.Set("revenue", 10.0)
		.Set("currency", "USD"),
}

func NewProperties

func NewProperties() Properties

func (Properties) Set

func (p Properties) Set(name string, value interface{}) Properties

type TestConfig

type TestConfig struct {
	Now func() time.Time
	UID func() string
}

type Ticker

type Ticker struct {
	C <-chan time.Time
	// contains filtered or unexported fields
}

func (*Ticker) Stop

func (t *Ticker) Stop()

Jump to

Keyboard shortcuts

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