Giter Site home page Giter Site logo

unleash / unleash-client-go Goto Github PK

View Code? Open in Web Editor NEW
130.0 6.0 53.0 385 KB

Unleash client SDK for Go

Home Page: https://docs.getunleash.io

License: Apache License 2.0

Go 99.78% Makefile 0.22%
go feature-flags toggles feature feature-toggles unleash feature-management hacktoberfest

unleash-client-go's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

unleash-client-go's Issues

Features read from file cannot be cast to Feature

Hello,

I think I found a bug in the current feature storage and repository implementation:
When features are read from the backup/cache file and were not (yet) fetched from the server, every feature evaluates to false/disabled.

This is because, when features are read from file, they are decoded to a generic map[string]interface{} structure,
because the type of the data holding variable is a map[string]interface{} and the decoder doesn't know to which type it should
decode the json to.

type defaultStorage struct {
appName string
path string
data map[string]interface{}
}

func (ds *defaultStorage) Load() error {
if file, err := os.Open(ds.path); err != nil {
return err
} else {
dec := json.NewDecoder(file)
if err := dec.Decode(&ds.data); err != nil {
return err
}
}
return nil
}

The repository then tries to cast this generic structure to a Feature struct (L146), which does not work, eventually returning a nil value although a valid feature exists.

func (r *repository) getToggle(key string) *api.Feature {
r.RLock()
defer r.RUnlock()
if toggle, found := r.options.storage.Get(key); found {
if feature, ok := toggle.(api.Feature); ok {
return &feature
}
}
return nil
}

To reproduce this behavior, you can:

  1. Create a client with a custom backup path
  2. Let the client persist features fetched from the server into the schema json file
  3. Stop the server
  4. Restart the client and let it read the features from the file
  5. Query an enabled toggle

The feature toggle will evaluate to false

Library flexibility

Currently there is a strong binding to unleash Context in all the library.
The main problem is that unleash Context is a struct that is already predefined for all unleash users.
I propose to redefine the context as an interface{} type with some API that can support current library and predefined strategies.
This way the user of the library can make much more flexible and power full use of context and custom strategies.

I can help implement the change if my suggestion accepted.

infinitely blocked in metrics.count with gitlab

Describe the bug

I am using Gitlab as unleash API, and I came across an error, where a request for an API-call against my microservice was timed out, since it never leaves the isEnabled func. After debugging I found out, that the metrics count in the defer is blocking infinitely.
https://github.com/Unleash/unleash-client-go/blob/v3/client.go#L243
Further it was really hard to figure this out as it is in the defer. I know, that I can disable the metrics, and that`s my fix for it, but imho this should not block. It should return an error instead or panic, but it was really hard to figure this out.

Steps to reproduce the bug

No response

Expected behavior

No blocking

Logs, error output, etc.

No response

Screenshots

No response

Additional context

No response

Unleash version

3.8.0

Subscription type

None

Hosting type

None

SDK information (language and version)

Go

Not able to set Environment in Client

Tried to set the environment value in initialization unleash.WithEnvironment("development")

but when I check if the feature flag isEnable() I got the value from the "default" environment

also tried passing the environment in the context but the same issue I can only read from the "default" environment

enable := unleash.IsEnabled(featureName, unleash.WithContext(ucontext.Context{Environment: "development"}))

I am using unleash server v4.6.5 (docker image) thas was released last week, but I notice that the go client has not been updated since last year, maybe there is an incompatibility with the new server version

feat: FlexibleRollout should support "custom" stickiness.

The Flexible Rollout strategy supports multiple options for stickiness, used to define how we guarantee consistency for a gradual rollout.

Today it support the following options:

  • default (Unleash chooses the first value present on the context in defined order userId, sessionId, random.)
  • userId
  • sessionId
  • random

We have now extended the protocol to support any field in the unleash context. In addition It can be any of the predefined context field, in addition to any custom properties the user has defined.

This means that the "stickiness" parameter in the strategy configuration can now be any field on the context, and the SDK should use the specified context field to calculate the "hash" which determine whether the activation strategy should evaluate to true or false.

How it looks in the UI:
image

Edge case:

  • If the specified context field is not specific the activation strategy should evaluate to false.

To guide the implementation we have:

  • added new client-specifications, see pr-11
  • implemented PoC in Node SDK see pr-201

feat: add support for fallback function

Today it is possible to define a fallback value which the IsEnabled will return if the feature toggle is not defined.

We want to also allow the user to send in a fallbackFunction instead of a fallback value (which will take precedence over fallback value).

The fallback function should get to arguments injected: toggleName and unleashContext.

Example on how it would work:

unleash.IsEnabled("foobar", unleash.WithFallbackFunction(myFunc))

If the user injects both a fallback value and fallbackFunction, like the example below, the result should be to only call the fallback function in the scenario that the toggle is not defined:

unleash.IsEnabled("foobar", unleash.WithFallback(true), unleash.WithFallbackFunction(myFunc))

Implement Global Segments

Describe the feature request

Just a feature that needs to be implemented - Global Segments. Unleash v4.13 supports enhanced responses for global segments, it would be great if this SDK can make use of this.

Background

Segments are effectively a way for Unleash users to define a list of constraints in such a way that makes them reusable across toggles without manually copying the constraint across to another toggle. Segments have two modes of operation, from the SDK's perspective, the inline mode will have no impact, segments will be remapped on the server side into constraints on the toggle information, no changes need to be . The second mode, global segments, requires that the SDK both opt in and handle the response differently. The handling should effectively result in unpacking the segments referenced in the feature strategies into a set of constraints. The changes required are described below.

Solution suggestions

Control Header

The SDK needs to pass up a Unleash-Client-Spec header with a semver value greater or equal to 4.2.0 (i.e. be greater or equal to the version of the unleash client spec tests where global segments are described) when hitting the get toggles endpoint on the Unleash server. This will enable the Unleash server to respond with the enhanced format

Example of the difference between enhanced and standard format:

Standard Format (default)

{
   "version": 2,
   "features": [  
       {
           "strategies": [
               {
                   "name": "flexibleRollout",
                   "constraints": [
                       {
                           "values": [
                               "31"
                           ],
                           "inverted": false,
                           "operator": "IN",
                           "contextName": "appName",
                           "caseInsensitive": false
                       }
                   ],          
                   "parameters": {
                       "groupId": "Test1",
                       "rollout": "100",
                       "stickiness": "default"
                   }
               }
           ],
           "name": "Test1"
       },
       {
           "strategies": [
               {
                   "name": "flexibleRollout",
                   "constraints": [
                       {
                           "values": [
                               "31"
                           ],
                           "inverted": false,
                           "operator": "IN",
                           "contextName": "appName",
                           "caseInsensitive": false
                       }
                   ],          
                   "parameters": {
                       "groupId": "Test2",
                       "rollout": "100",
                       "stickiness": "default"
                   }
               }
           ],
           "name": "Test2"
       }    
   ],
   "query": {
       "environment": "default"
   }
}

Enhanced Format (requires opt in)

{
   "version": 2,
   "features": [   
       {
           "strategies": [
               {
                   "name": "flexibleRollout",
                   "constraints": [],
                   "parameters": {
                       "groupId": "Test1",
                       "rollout": "100",
                       "stickiness": "default"
                   },
                   "segments": [
                       1
                   ]
               }
           ],
           "name": "Test1"
       },
       {
           "strategies": [
               {
                   "name": "flexibleRollout",
                   "constraints": [],
                   "parameters": {
                       "groupId": "Test2",
                       "rollout": "100",
                       "stickiness": "default"
                   },
                   "segments": [
                       1
                   ]
               }
           ],
           "name": "Test2"
       }     
   ],
   "query": {
       "environment": "default"
   },
   "segments": [
       {
           "id": 1,           
           "constraints": [
               {
                   "values": [
                       "31"
                   ],
                   "inverted": false,
                   "operator": "IN",
                   "contextName": "appName",
                   "caseInsensitive": false
               }
           ]           
       }
   ]
}

The relevant changes between the two formats are that in the enhanced format the segments are defined once as a global list and referenced within the strategy on the toggle by its ID. What's important to note is that the two above packets should be
handled identically, they reference the same toggle state.

Considerations

  • Global segments are intended to handle large datasets, how large has not been formally specified yet but expectations are around 1 000 to 10 000 segments across 1 000 toggles. As a result, time and space complexity of the implementations needs to be considered.
  • In the case of global segments, if the mapping from segment id to segment is incomplete i.e. a segment id is referenced in a toggle strategy that doesnโ€™t map back to the global segments list, then the toggle should be evaluated to false. This is enforced through one of the client specification tests in v4.2.0 of the client spec
  • A reference implementation is provided in node JS: Unleash/unleash-client-node#329 (note that this doesn't include the header, that can be seen here: Unleash/unleash-client-node#335)

`go get` for v3 doesn't work (mac OS X)

Trying to follow the go package install instructions of entering the following command.

go get github.com/Unleash/unleash-client-go/v3

However, this fails to find a package to install. Note that the following command does work.

go get github.com/Unleash/unleash-client-go/

This is on macOS X 10.14.4 with go version go1.12.1 darwin/amd64

Exact error message (with redacted username):

package github.com/Unleash/unleash-client-go/v3: cannot find package "github.com/Unleash/unleash-client-go/v3" in any of:
	/usr/local/Cellar/go/1.12.1/libexec/src/github.com/Unleash/unleash-client-go/v3 (from $GOROOT)
	/Users/$USER/go/src/github.com/Unleash/unleash-client-go/v3 (from $GOPATH)

Help wanted!

Are you a go expert? We plan to implement a Unleash client for Go programming language. My go knowledge is about zero, and any help would be appropriated!

Back-off strategy for calling Unleash

Describe the feature request

I'd like to see some kind of back-off strategy when it comes to calling the Unleash API. Basically a circuit breaker pattern or something to that extend. Right now the code seems to immediately retry calling Unleash after a failed attempt. I'd also be happy with a setting where I can determine the retry time-out.

Background

We recently had an issue where we couldn't reach Unleash. The unleash go client kept trying to call Unleash, about every 50 milliseconds (i.e. about 20 times per second). This lead to literally millions of error messages in our logs. Our DevOps guys were not happy.

Solution suggestions

You could implement a circuit-breaker pattern, or maybe just a configurable retry time-out.

feat: add support static context fields

In order to prepare the SDKS for strategy constraints we need to introduce two new fields in the Unleash Context

  • environment (default value is "default")
  • appName (already a required config parameter)

Both these static context fields should be configured at initialisation of the unleash SDK and be set as default values of the Unleash Context provided to the strategy implementations. The user is allowed to override these values in the context object at runtime (this is required to be backward compatible).

This support should be possible to add without breaking any contract and should be released as a minor version (3.3.x).

Internal only helpers.go makes custom gradual rollout strategies difficult/messy

I am currently writing some custom strategies that are simply gradual rollout strategies similar to the built in one for user IDs but these are keyed off of different data specific to my use case. I want to make sure that my gradual rollout strategy uses the same normalization, rounding, etc. that the built in gradual rollout strategies use.

However, that logic is defined inside of internal/strategies/helpers.go which means I don't get access to that by just importing. I have to copy & paste the helper.go code into my repo and remember to occasionally check to see if there's been any code changes to the helper.go file in this repo once in awhile. I believe this is less than ideal. I would appreciate it if these helper functions could be exported in some manner so as to make them available for import into custom strategies.

Is there a way to get all the feature flags for a project, not just one at a time?

Thanks so much for making this client available. Been using it on a project and we're running into an issue where calls to "IsEnabled" start to hang after our server has been running for a few days. We've got about 20 feature flags and loop through an array to fetch each of them every time a user signs into the web app. Restarting the server fixes the issue until it happens again.

I was reading over the feature-toggle docs and it says that querying for a specific feature toggle is not the intended way to use Unleash. Under the "Get specific feature toggle" section on that page it says:

Get specific feature toggle
Used to fetch details about a specific feature toggle. This is mainly provided to make it easy to debug the API and should not be used by the client implementations.

Does this client currently support the recommended way from this section of the same page, where it says:

This endpoint is the one all clients should use to fetch all available feature toggles from the unleash-server. The response returns all active feature toggles and their current strategy configuration.

It allows for certain filters:

tag - filters for features tagged with tag
project - filters for features belonging to project
namePrefix - filters for features beginning with prefix

Thanks for your all you do and in advance for any guidance!

Deadlock in Client.Close

Calling Client.Close leads to a deadlock due to a write to a nil channel in repository.go. With this diff

diff --git a/spec_test.go b/spec_test.go
index 9b47c90..f5354e5 100644
--- a/spec_test.go
+++ b/spec_test.go
@@ -70,6 +71,7 @@ func (td TestDefinition) Run(t *testing.T) {
                client, err := td.Mock()
                assert.NoError(t, err)
                t.Run(test.Description, test.RunWithClient(client))
+               client.Close()
                td.Unmock()
        }
 }

I get the backtrace

goroutine 20 [chan send (nil chan)]:
github.com/Unleash/unleash-client-go/v3.(*repository).Close(...)
	/home/frekui/code/unleash-client-go/repository.go:124
github.com/Unleash/unleash-client-go/v3.(*Client).Close(0xc0001412c0, 0xc00001c800, 0x1b)
	/home/frekui/code/unleash-client-go/client.go:264 +0x4a
github.com/Unleash/unleash-client-go/v3.TestDefinition.Run(0xc00001c7c0, 0x12, 0x1, 0xc0000cc540, 0x3, 0x4, 0xc000099440, 0x5, 0x6, 0xc0000e4900)
	/home/frekui/code/unleash-client-go/spec_test.go:74 +0x1be
testing.tRunner(0xc0000e4900, 0xc000138fa0)
	/usr/local/go/src/testing/testing.go:865 +0xc0
created by testing.(*T).Run
	/usr/local/go/src/testing/testing.go:916 +0x35a

when running the tests. It seems the Client.closed channel isn't initialized either.

Another deadlock in metrics

Hello everyone, I've found another deadlock in the metrics event loop. It happens if the unleash server (./client/metrics) returns 404. Erroneous config value was the culprit for me.

  1. The client attempts to send metrics but gets 404, so it tries to stop.

    if resp.StatusCode == http.StatusNotFound {
    m.warn(fmt.Errorf("%s return 404, stopping metrics", u.String()))
    m.stop()
    return
    }

  2. stop() sends true to m.stopped channel, and blocks.

    m.stopped <- true

  3. At this point, sync() is also blocked, since sendMetrics() is blocked. But sync() is the one that could free everything up by taking the value from m.stopped. Hence, deadlock.

    case <-m.timer.C:
    m.sendMetrics()
    case <-m.stopped:
    m.options.disableMetrics = true
    return
    }

Why is not options passed when calling GetVariant?

Hi

I've encountered an issue when trying to use variants.

When calling GetVariant I do it like this:

 unleash.GetVariant("feature-name", ucontext.Context{
		UserId: "user-id"
		Properties: map[string]string{
			"foo": "bar",
		},
	})

So then, inside the unleash sdk, client.go, this line is executed

func (uc *Client) GetVariant(feature string, options ...VariantOption) *api.Variant {
	defaultVariant := api.GetDefaultVariant()

	if !uc.isEnabled(feature) {
		return defaultVariant;
	}

When calling uc.isEnabled(feature) no options are passed. This causes my own defined Properties foo be lost and ultimately I only get the disabled variant back.

My question: Why are not the options passed to isEnabled?

Version of Unleash: github.com/Unleash/unleash-client-go/v3 v3.2.3

Is this still active?

Hello there,

Thank you for this great project. I was looking into the commits on this repo and it's been a while since the last one. Is this still an active project?
I had some problems with the metrics that were blocking because some channels were stuck. If you need any help in maintain it I would be glad to help.

failing spec tests

Hey,
It's been a while since I worked with Golang and I'm not familiar with testify.
maybe I'm missing something but when running go test (after running make and go mod download) it is failing on missing file testdata/client-specification/specifications/index.json

test failures with internal packages

Hello,

I'm facing the following error with go 1.10.1 when running the tests (in a docker container, for isolation concerns):

$  root@7f0b97cbb31a:/go/src/github/Unleash# git clone https://github.com/Unleash/unleash-client-go.git
Cloning into 'unleash-client-go'...
remote: Counting objects: 360, done.
remote: Total 360 (delta 0), reused 0 (delta 0), pack-reused 360
Receiving objects: 100% (360/360), 67.12 KiB | 0 bytes/s, done.
Resolving deltas: 100% (210/210), done.

$ root@7f0b97cbb31a:/go/src/github/Unleash# cd unleash-client-go/

$ root@7f0b97cbb31a:/go/src/github/Unleash/unleash-client-go# go get -v -t ./...
github.com/Unleash/unleash-client-go (download)
github.com/stretchr/testify (download)
Fetching https://gopkg.in/h2non/gock.v1?go-get=1
Parsing meta tags from https://gopkg.in/h2non/gock.v1?go-get=1 (status code 200)
get "gopkg.in/h2non/gock.v1": found meta tag get.metaImport{Prefix:"gopkg.in/h2non/gock.v1", VCS:"git", RepoRoot:"https://gopkg.in/h2non/gock.v1"} at https://gopkg.in/h2non/gock.v1?go-get=1
gopkg.in/h2non/gock.v1 (download)
metrics.go:7:2: use of internal package not allowed
client.go:5:2: use of internal package not allowed

I wonder if it would make sense to get rid of the internal packages, since they seem to cause troubles during the build. WDYT ?

Implement test-runner for client-specification.

So we I finally had the time to defining a set of client specifications, which defines what the expected result should be for a given set of feature toggles and a given Unleash context. The idea is that they shall ensure correct behaviour of clients across languages.

The specifications lives inside: https://github.com/Unleash/client-specification

The node and java client already implements support for automatically running the test cases as part of the CI validation.

Would be awesome if this client also could leverage the specifications. This will defenetly be used for v4, which will add new capabilities to the Unleash protocol.

Return variant and feature enabled from a single method

Describe the feature request

Currently there's no way with a single call to differentiate between a feature being disabled and no variants on the feature. Both of those cases return the default variant. Ideally there would be a call that returns (variant, enabled).

Background

We would like to make a single call and understand if a feature is enabled and what variant is applicable, if any. Instead we have to make 2 calls to understand the distinction. I'm surprised that this hasn't been brought up already and I'm curious how others are using this library in production with variants.

Solution suggestions

There are 2 potential solutions I see:

  1. Fixing the fallback options. Currently the descriptions of WithVariantFallback and WithVariantFallbackFunc are wrong. Those are actually used when a feature is not found. I filed this as #160. A new option could be added that is used to fallback when a feature is not found and the existing fallbacks could be correctly used when there are no variants on the feature. This would be a breaking change though, but I'm not sure how many people realize the existing options are not doing what they say they do.
  2. Add a new method that returns a variant and if it's enabled or not. This could also return a struct similar to the StrategyResult struct so it could be added to in the future if more things need to be returned.

Personally we're fine with either but the options being broken does seem like it should be fixed and might lend itself to just adding a new option.

Update link to GoDoc

[![Build Status](https://github.com/Unleash/unleash-client-go/actions/workflows/build.yml/badge.svg)](https://github.com/Unleash/unleash-client-go/actions/workflows/build.yml) [![GoDoc](https://godoc.org/github.com/Unleash/unleash-client-go?status.svg)](https://godoc.org/github.com/Unleash/unleash-client-go) [![Go Report Card](https://goreportcard.com/badge/github.com/Unleash/unleash-client-go)](https://goreportcard.com/report/github.com/Unleash/unleash-client-go)

Current link directs you to the old docs. Took me a while to find that there was a V3 doc site with all the new functionality.

(Feature Request) Enable passing api.Feature instead of a string to an alternative of IsEnabled

Describe the feature request

I would like a way to call a variant of IsEnabled that can accept an api.Feature without needing to pull it from the uc.repository.getToggle(feature) .

Background

I have been using this client in a way where I have the api.Feature that needs to be checked and having it retrieved from the repository is adding a few milliseconds of unnecessary latency.

Solution suggestions

I'm willing to add a variant function of IsEnabled that accepts api.Feature as the first parameter instead of a string.

Advantage:

  • Enable more flexibility or control when interfacing with the client.
  • More performant use of the IsEnabled function for those with access to the api.Feature from previous processing.

Drawbacks:

  • Would add another public function to the client that could confuse people. (I feel like this is a stretch of a drawback)

Proposal: be more strict about WithListener

Describe the feature request

I would like to make WithListener more strict about its parameter, requiring the consumer to implement some of the listener interfaces.

The rationale being: it's less work to implement a NOOP interface than it is to debug code that silently doesn't do what it's told.

Background

Currently, when using WithListener(), it is possible to introduce silent errors by not implementing any of the listener interfaces. The sync() goroutine will be started, but none of the listeners will be set.

This is presumably intentional, so that one can turn the sync on without having to actually implement anything (WithListener(struct{}{})), but it is also extremely error-prone.

The following snippet showcases how easy it is to miss this:

func init() {
	unleash.Initialize(
		unleash.WithListener(unleashListener{}),
	)
}

var _ unleash.RepositoryListener = (*unleashListener)(nil)

type unleashListener struct {}

func (*unleashListener) OnReady() {
	log.Print("ready")
}

Note the interface-mismatch: we test against a pointer (*unleashListener) but pass a copy (unleashListener{}).

Solution suggestions

We could trivially check if any listener interface is implemented in NewClient, but that would be a tricky compatibility breakage: old code would compile, but not run.

Maybe it would be better to break the API completely and change ConfigOption into the following?

type ConfigOption func(*configOption) error

With this, we could move a lot of the validation code currently living in NewClient to its respective option.

WDYT?

Missing testdata results in failed build

Environment:
Ubuntu Linux
go version go1.13.8 linux/amd64

Steps to reproduce:

$ git clone [email protected]:Unleash/unleash-client-go.git
$ cd unleash-client
$ make

Result:

unleash-client-go (v3)$ make
go vet ./...
go: downloading github.com/twmb/murmur3 v1.1.5
go: downloading github.com/stretchr/testify v1.2.2
go: downloading gopkg.in/h2non/gock.v1 v1.0.10
go: extracting github.com/stretchr/testify v1.2.2
go: extracting github.com/twmb/murmur3 v1.1.5
go: downloading github.com/pmezard/go-difflib v1.0.0
go: downloading github.com/stretchr/objx v0.1.1
go: downloading github.com/davecgh/go-spew v1.1.1
go: extracting github.com/pmezard/go-difflib v1.0.0
go: extracting github.com/stretchr/objx v0.1.1
go: extracting github.com/davecgh/go-spew v1.1.1
go: extracting gopkg.in/h2non/gock.v1 v1.0.10
go: finding github.com/twmb/murmur3 v1.1.5
go: finding github.com/stretchr/testify v1.2.2
go: finding gopkg.in/h2non/gock.v1 v1.0.10
go: finding github.com/pmezard/go-difflib v1.0.0
go: finding github.com/stretchr/objx v0.1.1
go: finding github.com/davecgh/go-spew v1.1.1
go test ./...
--- FAIL: TestClientSpecificationSuite (0.00s)
    --- FAIL: TestClientSpecificationSuite/TestClientSpecification (0.00s)
        spec_test.go:169: 
            	Error Trace:	spec_test.go:169
            	            				suite.go:88
            	Error:      	Received unexpected error:
            	            	open testdata/client-specification/specifications/index.json: no such file or directory
            	Test:       	TestClientSpecificationSuite/TestClientSpecification
        spec_test.go:175: 
            	Error Trace:	spec_test.go:175
            	            				suite.go:88
            	Error:      	Received unexpected error:
            	            	invalid argument
            	Test:       	TestClientSpecificationSuite/TestClientSpecification
FAIL
FAIL	github.com/Unleash/unleash-client-go/v3	2.839s
ok  	github.com/Unleash/unleash-client-go/v3/api	0.004s
ok  	github.com/Unleash/unleash-client-go/v3/context	0.015s
?   	github.com/Unleash/unleash-client-go/v3/internal/api	[no test files]
ok  	github.com/Unleash/unleash-client-go/v3/internal/constraints	0.005s
ok  	github.com/Unleash/unleash-client-go/v3/internal/strategies	0.905s
?   	github.com/Unleash/unleash-client-go/v3/strategy	[no test files]
FAIL
make: *** [Makefile:25: test] Error 1

feat: Custom stickiness for variants

This is kind of similar to #80 , but for variants.

The stickiness will be defined as a field on all the variants in the variants array, this to ensure we are not breaking our protocol. In the example we can see the stickiness is configured to "tenantId".

{"variants": [
     {
		"name": "yellow",
		"weight": 166,
		"weightType": "variable",
		"payload": {
			"type": "string",
			"value": "yellow submarine"
		},
		"overrides": [],
		"stickiness": "tenantId"
	}, {
		"name": "salmon",
		"weight": 166,
		"weightType": "variable",
		"payload": {
			"type": "string",
			"value": "salmon"
		},
		"overrides": [],
		"stickiness": "tenantId"
	}
]}

How it looks in Unleash Admin UI:
image

Edge cases:
If no stickiness is defined the SDK should assume "default" stickiness as today.

To guide the implementation we have:

  • added new client-specifications, see pr-11
  • implemented PoC in Node SDK see pr-202

Always getting flase

using the unleash node api, everything works,
when trying the same on the go api, i always get false on the IsEnabled function.

package main
import (
"fmt"
"time"
"github.com/Unleash/unleash-client-go"
)
func init() {
fmt.Println("init")
unleash.Initialize(
unleash.WithListener(&unleash.DebugListener{}),

            unleash.WithAppName("my-application"),
            unleash.WithUrl("http://unleash.herokuapp.com/api/"),
    )
    fmt.Println("end of init")

}
func main() {
fmt.Println("main")
i := 0
for i < 10 {
time.Sleep(time.Second * 10)
fmt.Printf("%v\n",unleash.IsEnabled("AwesomeFeature"))
i = i+1
}

}

Unable to get latest changes with go.mod

I am unable to pull in the latest changes, most notably for me the variant changes, using dependency management and go.mod. It continues to revert to the v3.1.1 tag applied a couple of years ago.

I have tried using a pseudo-version and pinning to the latest commit but am unable to do so with the v3 branch.

Can a new tag be applied to the latest changeset to aid in dependency management?

openfeature

Describe the feature request

Are there any plans to develop a https://openfeature.dev/ provider implementation for this SDK?

Background

We are evaluating different feature toggle implementations. Standardising on a common interface is important to our organisation. In the FT space we believe that openfeature will be that standard, similar to opentelemetry has become for telemetry, metrics and logs.

Solution suggestions

No response

Make Unleash Globally accessible

Unleash takes some time to initialize before I can actually run Unleash.IsEnabled, but I don't have a globally accessible method to do that. Right now my only option is to make a NewClient for every package and access the IsReady channel that way. I'm sure there is a more elegant solution for this. I'm thinking of having a global *Client object and accessing that through Unleash instead of initializing a NewClient every time. This way the user can initialize a global Client and add new ones as needed. In most cases one Client would be enough. At the least have a function to access the IsReady channel for the defaultClient instance.

Publicly expose the default Strategies for faster and more advanced Strategies.

Hi Unleash team,

I request to propose to you a change for the notion of "open-source development".
We have a use-case where we have to gradually rollout a feature to the users in some cities.
As the strategies linked in frontend are executed in an OR fashion, we want to execute them in an AND fashion.

Example:

class CityStrategy:
    def is_enabled(params, context):
          return context.properties["cities"] in params["cities"]

and combining it with gradual rollout strategy:

class GradualRolloutCityStrategy:
    def is_enabled(params, context):
          return CityStrategy().is_enabled(params, context) and GradualRolloutStartegy.is_enabled(params, context)

Ability to use pre-defined strategy will take flexibility and possibilities with unleash-go to the next level. What do you think?
Hoping to get this issue ingrained in the library.

NOTE: These are not actual code snippets. Added just for demonstration purposes.

Unleash client go efficiency

Current implementation requires finding client supported strategies for toggle defined strategies for each IsEnabled call

for _, s := range f.Strategies {
	foundStrategy := uc.getStrategy(s.Name)
	if foundStrategy == nil {
		// TODO: warnOnce missingStrategy
		continue
	}
	if constraints.Check(ctx, s.Constraints) && foundStrategy.IsEnabled(s.Parameters, ctx) {
		return true
	}
}

It very ineffective especially for lists, where for each toggle it parses one string to list of values and search for some value.
It will have a big input in hi hit ratios cases
I suggest to initialize the relevant strategies for each toggle once the toggle fetched from api.

Deadlock in metrics

There's a deadlock in how the go client handles metrics data, specifically when it handles the "sent" event. There are other issues in the codebase that were uncovered during debugging, so I'll list all of them here for now, but I'm happy to make a separate issue for each if necessary.

The deadlock happens when you don't pass in an "optional" event listener (WithListener) when initializing the client. The unbuffered sent channel receives a value

m.sent <- payload

, but b/c the event listener is nil, the receiver is never started
if uc.options.listener != nil {
if eListener, ok := uc.options.listener.(ErrorListener); ok {
uc.errorListener = eListener
}
if rListener, ok := uc.options.listener.(RepositoryListener); ok {
uc.repositoryListener = rListener
}
if mListener, ok := uc.options.listener.(MetricListener); ok {
uc.metricsListener = mListener
}
defer func() {
go uc.sync()
}()
}

, so the next time a payload is sent to the sent channel, it blocks.

There are some other issues related to this bug.

  1. WithDisableMetrics doesn't work, b/c the value doesn't get passed into metrics from the clinet.

    unleash-client-go/client.go

    Lines 163 to 171 in c586a9e

    metricsOptions{
    appName: uc.options.appName,
    instanceId: uc.options.instanceId,
    strategies: strategyNames,
    metricsInterval: uc.options.metricsInterval,
    url: *parsedUrl,
    httpClient: uc.options.httpClient,
    customHeaders: uc.options.customHeaders,
    },
  2. If you pass in the value down to metrics, you get a nil pointer exception b/c the timer is never initialized.
    if m.options.disableMetrics {
    return
    }
    m.timer = time.NewTimer(m.options.metricsInterval)
  3. Setting metrics interval to 0 doesn't work either since it now blocks on other channels.
    if m.options.metricsInterval > 0 {
    m.startTimer()
    m.registerInstance()
    go m.sync()
    }
  4. Metrics is too tightly coupled to the client. Proper dependency inversion would help here.

The only true workaround that works right now is to set a listener, even if it's a noop.

Happy to help out in anyway I can. Thanks!

Default backup path doesn't work on Linux

By default NewClient uses getTmpDirPath as the backup path. getTmpDirPath returns whatever os.TempDir returns. On Linux (tested on Ubuntu 18.04) os.TempDir returns a path without a trailing slash. In storage.go the final path is constructed using fmt.Sprintf("%sunleash-repo-schema-v1-%s.json", backupPath, appName) as there is no slash between the backup path and the rest of the path the file creation will typically fail with a permission denied error.

Expose admin API

Is there any plans to expose the admin/management API for creating and managing feature toggles?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.