Skip to content

Commit

Permalink
v1.1.0 (#4)
Browse files Browse the repository at this point in the history
* feature/v1.1.0: update README.md and test units

---------

Co-authored-by: deleteLater <[email protected]>
  • Loading branch information
dsun0720 and deleteLater authored Apr 13, 2023
1 parent ddd6a9d commit 0c90a1a
Show file tree
Hide file tree
Showing 7 changed files with 266 additions and 125 deletions.
274 changes: 181 additions & 93 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,64 +1,81 @@
# Go server Side SDK
# FeatBit Server-Side SDK for Go

## Introduction

This is the Go Server Side SDK for the feature management platform FeatBit. It is intended for use in a multi-user Go
server applications.
This is the Go Server-Side SDK for the 100% open-source feature flags management
platform [FeatBit](https://github.com/featbit/featbit).

This SDK has two main purposes:
The FeatBit Server-Side SDK for Go is designed primarily for use in multi-user systems such as web servers and
applications.

- Store the available feature flags and evaluate the feature flag variation for a given user
- Send feature flag usage and custom events for the insights and A/B/n testing.
## Data synchronization

## Data synchonization
We use websocket to make the local data synchronized with the FeatBit server, and then store them in memory by
default. Whenever there is any change to a feature flag or its related data, this change will be pushed to the SDK and
the average synchronization time is less than 100 ms. Be aware the websocket connection may be interrupted due to
internet outage, but it will be resumed automatically once the problem is gone.

We use websocket to make the local data synchronized with the server, and then store them in memory by default.Whenever
there is any change to a feature flag or its related data, this change will be pushed to the SDK, the average
synchronization time is less than **100** ms. Be aware the websocket connection may be interrupted due to internet
outage, but it will be resumed automatically once the problem is gone.
If you want to use your own data source, see [Offline Mode](#offline-mode).

## Offline mode support
## Get Started

In the offline mode, SDK DOES not exchange any data with your feature management platform
Go Server Side SDK is based on go 1.13, so you need to install go 1.13 or above.

In the following situation, the SDK would work when there is no internet connection: it has been initialized in
using `featbit.FBClient.InitializeFromExternalJson()`

To open the offline mode:

```go
config := featbit.DefaultFBConfig
featbit.Offline = true

// or

config := featbit.FBConfig{Offline: true}
### Installation

```
go get github.com/featbit/featbit-go-sdk
```

## Evaluation of a feature flag

SDK will initialize all the related data(feature flags, segments etc.) in the bootstrapping and receive the data updates
in real time, as mentioned in the above.

After initialization, the SDK has all the feature flags in the memory and all evaluation is done locally and
synchronously, the average evaluation time is < **10** ms.
### Quick Start
> Note that the _**envSecret**_, _**streamUrl**_ and _**eventUrl**_ are required to initialize the SDK.
## Installation
The following code demonstrates basic usage of the SDK.

```go
package main

import (
"fmt"
"github.com/featbit/featbit-go-sdk"
"github.com/featbit/featbit-go-sdk/interfaces"
)

func main() {
envSecret := "<replace-with-your-env-secret>"
streamingUrl := "ws://localhost:5100"
eventUrl := "http://localhost:5100"

client, err := featbit.NewFBClient(envSecret, streamingUrl, eventUrl)

defer func() {
if client != nil {
// ensure that the SDK shuts down cleanly and has a chance to deliver events to FeatBit before the program exits
_ = client.Close()
}
}()

if err == nil && client.IsInitialized() {
user, _ := interfaces.NewUserBuilder("<replace-with-your-user-key>").UserName("<replace-with-your-user-name>").Build()
_, ed, _ := client.BoolVariation("<replace-with-your-feature-flag-key>", user, false)
fmt.Printf("flag %s, returns %s for user %s, reason: %s \n", ed.KeyName, ed.Variation, user.GetKey(), ed.Reason)
} else {
fmt.Println("SDK initialization failed")
}
}
```
go get github.com/featbit/featbit-go-sdk
```

## SDK
### Examples

- [Go Demo](https://github.com/featbit/featbit-samples/blob/main/samples/dino-game/demo-golang/go_demo.go)

### FBClient

Applications SHOULD instantiate a single instance for the lifetime of the application. In the case where an application
Applications **SHOULD instantiate a single FBClient instance** for the lifetime of the application. In the case where an application
needs to evaluate feature flags from different environments, you may create multiple clients, but they should still be
retained for the lifetime of the application rather than created per request or per thread.

### Bootstrapping
#### Bootstrapping

The bootstrapping is in fact the call of constructor of `featbit.FBClient`, in which the SDK will be initialized, using
streaming from your feature management platform.
Expand All @@ -70,11 +87,23 @@ you will receive the client in an uninitialized state where feature flags will r
continue trying to connect in the background unless there has been an `net.DNSError` or you close the
client. You can detect whether initialization has succeeded by calling `featbit.FBClient.IsInitialized()`.

```go
If `featbit.FBClient.IsInitialized()` returns True, it means the `featbit.FBClient` has succeeded at some point in connecting to feature flag center and
has received feature flag data.

If `featbit.FBClient.IsInitialized()` returns false, it means the client has not yet connected to feature flag center, or has permanently
failed. In this state, feature flag evaluations will always return default values. Another state that will cause this to return false is if the interfaces.DataStorage is empty.
It's strongly recommended to create at least one feature flag in your environment before using the SDK.

client, _ := featbit.NewFBClient(envSecret, streamingUrl, eventUrl)
if !client.IsInitialized() {
// do whatever is appropriate if initialization has timed out
`featbit.FBClient.IsInitialized()` is optional, but it is recommended that you use it to avoid to get default values when the SDK is not yet initialized.

```go
config := featbit.FBConfig{StartWait: 10 * time.Second}
// DO NOT forget to close the client when you don't need it anymore
client, err := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, config)
if err == nil && client.IsInitialized() {
// the client is ready
} else {
// the client is not ready
}

```
Expand All @@ -84,25 +113,25 @@ point, you can use `featbit.FBClient.GetDataUpdateStatusProvider()`, which provi

```go
config := featbit.FBConfig{StartWait: 0}
client, _ := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, config)
// later...
// DO NOT forget to close the client when you don't need it anymore
client, err := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, config)
if err != nil {
return
}
ok := client.GetDataSourceStatusProvider().WaitForOKState(10 * time.Second)
if !ok {
// do whatever is appropriate if initialization has timed out
if ok {
// the client is ready
} else {
// the client is not ready
}

```

Note that the _**sdkKey(envSecret)**_ is mandatory.

### FBClient, FBConfig and Components
### FBConfig and Components

In the most case, you don't need to care about `featbit.FBConfig` and the internal components, just initialize SDK like:
In most cases, you don't need to care about `featbit.FBConfig` and the internal components, just initialize SDK like:

```go

client, _ := featbit.NewFBClient(envSecret, streamingUrl, eventUrl)

client, err := featbit.NewFBClient(envSecret, streamingUrl, eventUrl)
```

`envSecret` _**sdkKey(envSecret)**_ is id of your project in FeatBit feature flag center
Expand All @@ -111,20 +140,6 @@ client, _ := featbit.NewFBClient(envSecret, streamingUrl, eventUrl)

`eventURL`: URL of your feature management platform to send analytics events

If you would like to run in the offline mode or change the timeout:

```go
config := featbit.DefaultFBConfig
featbit.Offline = true
featbit.StartWait = 0

// or
config := featbit.FBConfig{StartWait: 0, Offline: true}

client, _ := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, config)

```

`StartWait`: how long the constructor will block awaiting a successful data sync. Setting this to a zero or negative
duration will not block and cause the constructor to return immediately.

Expand All @@ -139,15 +154,15 @@ HTTP Proxy, TLS etc.
`factories.NetworkBuilder` is the default `NetworkFactory`

```go

factory := factories.NewNetworkBuilder()
factory.ProxyUrl("http://username:[email protected]:65233")

config := featbit.DefaultFBConfig
config.NetworkFactory = factory
client, err := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, *config)
// or
config := featbit.FBConfig{NetworkFactory: factory}

client, err := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, config)
```

`DataStorageFactory` sets the implementation of `interfaces.DataStorage` to be used for holding feature flags and
Expand All @@ -165,12 +180,9 @@ If Developers would like to know what the implementation is, they can read the G

It's not recommended to change the default factories in the `featbit.FBConfig`

### Evaluation
### FBUser

SDK calculates the value of a feature flag for a given user, and returns a flag value/an object that describes the way
that the value was determined.

`FBUser`: A collection of attributes that can affect flag evaluation, usually corresponding to a user of your
A collection of attributes that can affect flag evaluation, usually corresponding to a user of your
application.
This object contains built-in properties(`key`, `userName`). The `key` and `userName` are required.
The `key` must uniquely identify each user; this could be a username or email address for authenticated users, or an ID
Expand All @@ -179,32 +191,99 @@ The `userName` is used to search your user quickly.
You may also define custom properties with arbitrary names and values.

```go
client, _ := featbit.NewFBClient(envSecret, streamingUrl, eventUrl)

// FBUser creation
user, _ := NewUserBuilder("key").UserName("name").Custom("property", "value").Build()

// be sure that SDK is initialized
// this is not required
if(client.isInitialized()){
// Flag value
// returns a string variation
variation, detail, _ := client.Variation("flag key", user, "Not Found");

// get all variations for a given user in your project
AllFlagStates states = client.AllLatestFlagsVariations(user);
variation, detail, _ = states.GetStringVariation("flag key", user, "Not Found");
user, err := NewUserBuilder("key").UserName("name").Custom("property", "value").Build()
```

### Evaluation

SDK calculates the value of a feature flag for a given user, and returns a flag value and `interfaces.EvalDetail` that describes the way
that the value was determined.

SDK will initialize all the related data(feature flags, segments etc.) in the bootstrapping and receive the data updates
in real time, as mentioned in [Bootstrapping](#bootstrapping).

After initialization, the SDK has all the feature flags in the memory and all evaluation is done _**locally and
synchronously**_, the average evaluation time is < _**10**_ ms.

If evaluation called before Go SDK client initialized, or you set the wrong flag key or user for the evaluation, SDK will return
the default value you set.

SDK supports String, Boolean, and Number and Json as the return type of flag values:

- Variation(for string)
- BoolVariation
- IntVariation
- DoubleVariation
- JsonVariation

```go
// be sure that SDK is initialized before evaluation
// DO not forget to close client when you are done with it
if client.isInitialized() {
// Flag value
// returns a string variation
variation, detail, _ := client.Variation("flag key", user, "Not Found")
}
```

If evaluation called before Go SDK client initialized, or you set the wrong flag key or user for the evaluation, SDK
will return the default value you set.
`featbit.FBClient.AllLatestFlagsVariations(user)` returns all variations for a given user. You can retrieve the flag value or details
for a specific flag key:

- GetStringVariation
- GetBoolVariation
- GetIntVariation
- GetDoubleVariation
- GetJsonVariation

SDK supports String, Boolean, and Number and Json as the return type of flag values, see GoDocs for more details.
```go
// be sure that SDK is initialized before evaluation
// DO not forget to close client when you are done with it
if client.isInitialized() {
// get all variations for a given user in your project
allState, _ := client.AllLatestFlagsVariations(user)
variation, detail, _ := allState.GetStringVariation("flag key", "Not Found")
}
```

### Offline Mode

In some situations, you might want to stop making remote calls to FeatBit. Here is how:

```go
config := featbit.DefaultFBConfig
featbit.Offline = true
featbit.StartWait = 1 * time.Millisecond
client, err := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, *config)
// or
config := FBConfig{Offline: true, StartWait: 1 * time.Millisecond}
client, err := featbit.MakeCustomFBClient(envSecret, streamingUrl, eventUrl, config)

```

When you put the SDK in offline mode, no insight message is sent to the server and all feature flag evaluations return
fallback values because there are no feature flags or segments available. If you want to use your own data source,
SDK allows users to populate feature flags and segments data from a JSON string. Here is an example: [fbclient_test_data.json](fixtures/fbclient_test_data.json).

The format of the data in flags and segments is defined by FeatBit and is subject to change. Rather than trying to
construct these objects yourself, it's simpler to request existing flags directly from the FeatBit server in JSON format
and use this output as the starting point for your file. Here's how:

```shell
# replace http://localhost:5100 with your evaluation server url
curl -H "Authorization: <your-env-secret>" http://localhost:5100/api/public/sdk/server/latest-all > featbit-bootstrap.json
```

Then you can use this file to initialize the SDK in offline mode:

```go
// first load data from file and then
ok, _ := client.InitializeFromExternalJson(string(jsonBytes))
```

### Experiments (A/B/n Testing)

We support automatic experiments for pageviews and clicks, you just need to set your experiment on FeatBit platform,
We support automatic experiments for page-views and clicks, you just need to set your experiment on FeatBit platform,
then you should be able to see the result in near real time after the experiment is started.

In case you need more control over the experiment data sent to our server, we offer a method to send custom event.
Expand All @@ -220,3 +299,12 @@ Make sure `featbit.FBClient.TrackPercentageMetric()` or `featbit.FBClient.TrackN
otherwise the custom event may not be included into the experiment result.


## Getting support

- If you have a specific question about using this sdk, we encourage you
to [ask it in our slack](https://join.slack.com/t/featbit/shared_invite/zt-1ew5e2vbb-x6Apan1xZOaYMnFzqZkGNQ).
- If you encounter a bug or would like to request a
feature, [submit an issue](https://github.com/featbit/featbit-go-sdk/issues/new).

## See Also
- [Connect To Go Sdk](https://docs.featbit.co/docs/getting-started/4.-connect-an-sdk/server-side-sdks/go-sdk)
7 changes: 2 additions & 5 deletions eval_result.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,11 +113,8 @@ func (er *evalResult) checkType(requiredType string) bool {
case FlagBoolType:
return requiredType == FlagBoolType || requiredType == FlagStringType
case FlagNumericType:
if requiredType == FlagBoolType {
_, err := strconv.ParseFloat(er.fv, 64)
return err == nil
}
return true
_, err := strconv.ParseFloat(er.fv, 64)
return err == nil
case FlagJsonType, FlagStringType:
if requiredType == FlagBoolType {
_, err := strconv.ParseBool(er.fv)
Expand Down
Loading

0 comments on commit 0c90a1a

Please sign in to comment.