Skip to content

feat: Init web-sdk go-feature-flag #474

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 29 commits into from
Jul 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
4382eb0
Init web-sdk go-feature-flag
thomaspoignant Jul 19, 2023
4ff5f02
Fix PR CI Issue
thomaspoignant Jul 19, 2023
3fd1d8b
Merge branch 'main' into add-web-goff
thomaspoignant Jul 19, 2023
298745e
Fix CI failure
thomaspoignant Jul 20, 2023
b6a0035
Fix jest configuration
thomaspoignant Jul 20, 2023
f48f076
Remove unused errors
thomaspoignant Jul 20, 2023
08e0826
Code style
thomaspoignant Jul 20, 2023
584748b
Add readme
thomaspoignant Jul 20, 2023
8fbeaee
Merge branch 'main' into add-web-goff
thomaspoignant Jul 20, 2023
8ed2a9d
Send information in the emit function
thomaspoignant Jul 20, 2023
26aca58
Merge remote-tracking branch 'origin/main' into add-web-goff
thomaspoignant Jul 23, 2023
d51ca77
Addin myself has a code owner of this new component
thomaspoignant Jul 25, 2023
241260b
Fix doc mentioning flagd + change event type to match the example
thomaspoignant Jul 25, 2023
c7a9590
address review comment from Todd
thomaspoignant Jul 26, 2023
632735e
add retry mechanism to reload the flags
thomaspoignant Jul 27, 2023
af6c468
Merge branch 'main' into add-web-goff
thomaspoignant Jul 27, 2023
47d5188
Removing the experimental mention
thomaspoignant Jul 27, 2023
2ee79cd
manage apiKey for the websocket
thomaspoignant Jul 27, 2023
204bda2
Merge branch 'main' into add-web-goff
thomaspoignant Jul 27, 2023
5f38c79
removing axios
thomaspoignant Jul 27, 2023
9499f84
Emit events when context is changing
thomaspoignant Jul 27, 2023
bce42db
fix log
thomaspoignant Jul 28, 2023
cafc245
Merge branch 'main' into add-web-goff
thomaspoignant Jul 28, 2023
ef673e8
Add prefix for logs
thomaspoignant Jul 28, 2023
91e3680
Fixing the version of SDK to 0.4.0
thomaspoignant Jul 28, 2023
ecc62ee
Merge branch 'main' into add-web-goff
beeme1mr Jul 28, 2023
432d6c3
Merge branch 'main' into add-web-goff
beeme1mr Jul 28, 2023
b206192
Fix test suite
thomaspoignant Jul 31, 2023
224a402
Merge branch 'main' into add-web-goff
thomaspoignant Jul 31, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/component_owners.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ components:
- toddbaert
libs/providers/go-feature-flag:
- thomaspoignant
libs/providers/go-feature-flag-web:
- thomaspoignant
libs/providers/in-memory:
- moredip
- beeme1mr
Expand Down
3 changes: 2 additions & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,6 @@
"libs/providers/env-var": "0.1.1",
"libs/providers/in-memory": "0.2.0",
"libs/providers/config-cat": "0.3.0",
"libs/providers/launchdarkly-client": "0.1.2"
"libs/providers/launchdarkly-client": "0.1.2",
"libs/providers/go-feature-flag-web": "0.1.0"
}
18 changes: 18 additions & 0 deletions libs/providers/go-feature-flag-web/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts", "*.tsx", "*.js", "*.jsx"],
"rules": {}
},
{
"files": ["*.ts", "*.tsx"],
"rules": {}
},
{
"files": ["*.js", "*.jsx"],
"rules": {}
}
]
}
82 changes: 82 additions & 0 deletions libs/providers/go-feature-flag-web/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
# go-feature-flag-web Provider for OpenFeature
## About this provider
[GO Feature Flag](https://gofeatureflag.org) provider allows you to connect to your GO Feature Flag instance with the `@openfeature/web-sdk`.

The main difference between this provider and [`@openfeature/go-feature-flag-provider`](https://www.npmjs.com/package/@openfeature/go-feature-flag-provider) is that it uses a **static evaluation context**.
This provider is more sustainable for client-side implementation.

If you want to know more about this pattern, I encourage you to read this [blog post](https://openfeature.dev/blog/catering-to-the-client-side/).

## What is GO Feature Flag?
GO Feature Flag is a simple, complete and lightweight self-hosted feature flag solution 100% Open Source.
Our focus is to avoid any complex infrastructure work to use GO Feature Flag.

This is a complete feature flagging solution with the possibility to target only a group of users, use any types of flags, store your configuration in various location and advanced rollout functionality. You can also collect usage data of your flags and be notified of configuration changes.

## Install the provider

```shell
npm install @openfeature/go-feature-flag-web-provider @openfeature/web-sdk
```

## How to use the provider?
```typescript
const evaluationCtx: EvaluationContext = {
targetingKey: 'user-key',
email: '[email protected]',
name: 'John Doe',
};

const goFeatureFlagWebProvider = new GoFeatureFlagWebProvider({
endpoint: endpoint,
// ...
}, logger);

await OpenFeature.setContext(evaluationCtx); // Set the static context for OpenFeature
OpenFeature.setProvider(goFeatureFlagWebProvider); // Attach the provider to OpenFeature
const client = await OpenFeature.getClient();

// You can now use the client to use your flags
if(client.getBooleanValue('my-new-feature', false)){
//...
}

// You can add handlers to know what happen in the provider
client.addHandler(ProviderEvents.Ready, () => { ... });
client.addHandler(ProviderEvents.Error, () => { //... });
client.addHandler(ProviderEvents.Stale, () => { //... });
client.addHandler(ProviderEvents.ConfigurationChanged, () => { //... });
```

### Available options
| Option name | Type | Default | Description |
|-------------------------------|--------|----------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| endpoint | string | | endpoint is the URL where your GO Feature Flag server is located. |
| apiTimeout | number | 0 = no timeout | (optional) timeout is the time in millisecond we wait for an answer from the server. |
| apiKey | string | | (optional) If GO Feature Flag is configured to authenticate the requests, you should provide an API Key to the provider. Please ask the administrator of the relay proxy to provide an API Key. |
| websocketRetryInitialDelay | number | 100 | (optional) initial delay in millisecond to wait before retrying to connect the websocket |
| websocketRetryDelayMultiplier | number | 2 | (optional) multiplier of websocketRetryInitialDelay after each failure _(example: 1st connection retry will be after 100ms, second after 200ms, third after 400ms ...)_ |
| websocketMaxRetries | number | 10 | (optional) maximum number of retries before considering the websocket unreachable |

### Reconnection
If the connection to the GO Feature Flag instance fails, the provider will attempt to reconnect with an exponential back-off.
The `websocketMaxRetries` can be specified to customize reconnect behavior.

### Event streaming
The `GoFeatureFlagWebProvider` receives events from GO Feature Flag with changes.
Combined with the event API in the web SDK, this allows for subscription to flag value changes in clients.

```typescript
client.addHandler(ProviderEvents.ConfigurationChanged, (ctx: EventDetails) => {
// do something when the configuration has changed.
// ctx.flagsChanged contains the list of changed flags.
});
```

## Contribute

### Building
Run `nx package providers-go-feature-flag-web` to build the library.

### Running unit tests
Run `nx test providers-go-feature-flag-web` to execute the unit tests via [Jest](https://jestjs.io).
3 changes: 3 additions & 0 deletions libs/providers/go-feature-flag-web/babel.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"presets": [["minify", { "builtIns": false }]]
}
16 changes: 16 additions & 0 deletions libs/providers/go-feature-flag-web/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/* eslint-disable */
export default {
displayName: 'providers-go-feature-flag-web',
preset: '../../../jest.preset.js',
globals: {
'ts-jest': {
tsconfig: '<rootDir>/tsconfig.spec.json',
},
},
transform: {
'^.+\\.[tj]s$': 'ts-jest',
},
testEnvironment: 'jsdom',
moduleFileExtensions: ['ts', 'js', 'html'],
coverageDirectory: '../../../coverage/libs/providers/go-feature-flag-web',
};
21 changes: 21 additions & 0 deletions libs/providers/go-feature-flag-web/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

12 changes: 12 additions & 0 deletions libs/providers/go-feature-flag-web/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@openfeature/go-feature-flag-web-provider",
"version": "0.0.1",
"type": "commonjs",
"scripts": {
"publish-if-not-exists": "cp $NPM_CONFIG_USERCONFIG .npmrc && if [ \"$(npm show $npm_package_name@$npm_package_version version)\" = \"$(npm run current-version -s)\" ]; then echo 'already published, skipping'; else npm publish --access public; fi",
"current-version": "echo $npm_package_version"
},
"peerDependencies": {
"@openfeature/web-sdk": "^0.4.0"
}
}
76 changes: 76 additions & 0 deletions libs/providers/go-feature-flag-web/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
{
"name": "providers-go-feature-flag-web",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "libs/providers/go-feature-flag-web/src",
"projectType": "library",
"targets": {
"publish": {
"executor": "nx:run-commands",
"options": {
"command": "npm run publish-if-not-exists",
"cwd": "dist/libs/providers/go-feature-flag-web"
},
"dependsOn": [
{
"projects": "self",
"target": "package"
}
]
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["libs/providers/go-feature-flag-web/**/*.ts"]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "libs/providers/go-feature-flag-web/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
},
"package": {
"executor": "@nx/rollup:rollup",
"outputs": ["{options.outputPath}"],
"options": {
"project": "libs/providers/go-feature-flag-web/package.json",
"outputPath": "dist/libs/providers/go-feature-flag-web",
"entryFile": "libs/providers/go-feature-flag-web/src/index.ts",
"tsConfig": "libs/providers/go-feature-flag-web/tsconfig.lib.json",
"buildableProjectDepsInPackageJsonType": "dependencies",
"compiler": "tsc",
"generateExportsField": true,
"umdName": "go-feature-flag-web",
"external": "all",
"format": ["cjs", "esm"],
"assets": [
{
"glob": "package.json",
"input": "./assets",
"output": "./src/"
},
{
"glob": "LICENSE",
"input": "./",
"output": "./"
},
{
"glob": "README.md",
"input": "./libs/providers/go-feature-flag-web",
"output": "./"
}
]
}
}
},
"tags": []
}
1 change: 1 addition & 0 deletions libs/providers/go-feature-flag-web/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './lib/go-feature-flag-web-provider';
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import {EvaluationContext} from '@openfeature/js-sdk';
import {GoFeatureFlagEvaluationContext} from './model';
import {transformContext} from './context-transformer';
import {TargetingKeyMissingError} from "@openfeature/web-sdk";

describe('contextTransformer', () => {
it('should use the targetingKey as user key', () => {
const got = transformContext({
targetingKey: 'user-key',
} as EvaluationContext);
const want: GoFeatureFlagEvaluationContext = {
key: 'user-key',
custom: {},
};
expect(got).toEqual(want);
});

it('should specify the anonymous field base on attributes', () => {
const got = transformContext({
targetingKey: 'user-key',
anonymous: true,
} as EvaluationContext);
const want: GoFeatureFlagEvaluationContext = {
key: 'user-key',
custom: {
anonymous: true,
},
};
expect(got).toEqual(want);
});

it('should hash the context as key if no targetingKey provided', () => {
expect(() => {
transformContext({
anonymous: true,
firstname: 'John',
lastname: 'Doe',
email: '[email protected]',
} as EvaluationContext);
}).toThrow(TargetingKeyMissingError);
});

it('should fill custom fields if extra field are present', () => {
const got = transformContext({
targetingKey: 'user-key',
anonymous: true,
firstname: 'John',
lastname: 'Doe',
email: '[email protected]',
} as EvaluationContext);

const want: GoFeatureFlagEvaluationContext = {
key: 'user-key',
custom: {
firstname: 'John',
lastname: 'Doe',
email: '[email protected]',
anonymous: true,
},
};
expect(got).toEqual(want);
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import {EvaluationContext} from '@openfeature/js-sdk';
import {GoFeatureFlagEvaluationContext} from './model';
import {TargetingKeyMissingError} from "@openfeature/web-sdk";

/**
* transformContext takes the raw OpenFeature context returns a GoFeatureFlagEvaluationContext.
* @param context - the context used for flag evaluation.
* @returns {GoFeatureFlagEvaluationContext} the user against who we will evaluate the flag.
*/
export function transformContext(
context: EvaluationContext
): GoFeatureFlagEvaluationContext {
const {targetingKey, ...attributes} = context;
if (targetingKey === undefined || targetingKey === null || targetingKey === '') {
throw new TargetingKeyMissingError();
}
return {
key: targetingKey,
custom: attributes,
};
}
12 changes: 12 additions & 0 deletions libs/providers/go-feature-flag-web/src/lib/fetch-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* FetchError is a wrapper around the HTTP error returned by
* the method fetch.
* It allows to throw an error with the status code.
*/
export class FetchError extends Error{
status: number;
constructor(status:number) {
super(`Request failed with status code ${status}`);
this.status = status;
}
}
Loading