Skip to content
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

feat(3742): Feature Flag Values with Scope Based on threshold #5051

Merged
merged 5 commits into from
Dec 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
11 changes: 10 additions & 1 deletion packages/remote-feature-flag-controller/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.2.0]

### Added

- Added support for threshold-based feature flag scoping ([#5051](https://github.com/MetaMask/core/pull/5051))
- Enables percentage-based feature flag distribution across user base
- Uses deterministic random group assignment based on metaMetricsId

## [1.1.0]

### Added
Expand All @@ -26,6 +34,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Initial release of the RemoteFeatureFlagController. ([#4931](https://github.com/MetaMask/core/pull/4931))
- This controller manages the retrieval and caching of remote feature flags. It fetches feature flags from a remote API, caches them, and provides methods to access and manage these flags. The controller ensures that feature flags are refreshed based on a specified interval and handles cases where the controller is disabled or the network is unavailable.

[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/[email protected]
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/[email protected]
[1.2.0]: https://github.com/MetaMask/core/compare/@metamask/[email protected]...@metamask/[email protected]
[1.1.0]: https://github.com/MetaMask/core/compare/@metamask/[email protected]...@metamask/[email protected]
[1.0.0]: https://github.com/MetaMask/core/releases/tag/@metamask/[email protected]
3 changes: 2 additions & 1 deletion packages/remote-feature-flag-controller/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@
"dependencies": {
"@metamask/base-controller": "^7.0.2",
"@metamask/utils": "^10.0.0",
"cockatiel": "^3.1.2"
"cockatiel": "^3.1.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"@lavamoat/allow-scripts": "^3.0.4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,17 @@ export type FeatureFlags = {
[key: string]: Json;
};

export type FeatureFlagScope = {
type: string;
value: number;
};

export type FeatureFlagScopeValue = {
name: string;
scope: FeatureFlagScope;
value: Json;
};

export type ApiDataResponse = FeatureFlags[];

export type ServiceResponse = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
RemoteFeatureFlagController,
controllerName,
DEFAULT_CACHE_DURATION,
getDefaultRemoteFeatureFlagControllerState,
} from './remote-feature-flag-controller';
import type {
RemoteFeatureFlagControllerActions,
Expand All @@ -13,14 +14,36 @@ import type {
RemoteFeatureFlagControllerStateChangeEvent,
} from './remote-feature-flag-controller';
import type { FeatureFlags } from './remote-feature-flag-controller-types';
import * as userSegmentationUtils from './utils/user-segmentation-utils';

const MOCK_FLAGS: FeatureFlags = {
feature1: true,
feature2: { chrome: '<109' },
feature3: [1, 2, 3],
};

const MOCK_FLAGS_TWO = { different: true };

const MOCK_FLAGS_WITH_THRESHOLD = {
...MOCK_FLAGS,
testFlagForThreshold: [
{
name: 'groupA',
scope: { type: 'threshold', value: 0.3 },
value: 'valueA',
},
{
name: 'groupB',
scope: { type: 'threshold', value: 0.5 },
value: 'valueB',
},
{ name: 'groupC', scope: { type: 'threshold', value: 1 }, value: 'valueC' },
],
};

const MOCK_METRICS_ID = 'f9e8d7c6-b5a4-4210-9876-543210fedcba';
const MOCK_METRICS_ID_2 = '987fcdeb-51a2-4c4b-9876-543210fedcba';

/**
* Creates a controller instance with default parameters for testing
* @param options - The controller configuration options
Expand All @@ -36,6 +59,7 @@ function createController(
state: Partial<RemoteFeatureFlagControllerState>;
clientConfigApiService: AbstractClientConfigApiService;
disabled: boolean;
getMetaMetricsId: Promise<string | undefined>;
}> = {},
) {
return new RemoteFeatureFlagController({
Expand All @@ -44,6 +68,7 @@ function createController(
clientConfigApiService:
options.clientConfigApiService ?? buildClientConfigApiService(),
disabled: options.disabled,
getMetaMetricsId: options.getMetaMetricsId,
});
}

Expand Down Expand Up @@ -239,6 +264,61 @@ describe('RemoteFeatureFlagController', () => {
});
});

describe('threshold feature flags', () => {
it('processes threshold feature flags based on provided metaMetricsId', async () => {
const clientConfigApiService = buildClientConfigApiService({
remoteFeatureFlags: MOCK_FLAGS_WITH_THRESHOLD,
});
const controller = createController({
clientConfigApiService,
getMetaMetricsId: Promise.resolve(MOCK_METRICS_ID),
});
await controller.updateRemoteFeatureFlags();

expect(
controller.state.remoteFeatureFlags.testFlagForThreshold,
).toStrictEqual({
name: 'groupC',
value: 'valueC',
});
});

it('preserves non-threshold feature flags unchanged', async () => {
const clientConfigApiService = buildClientConfigApiService({
remoteFeatureFlags: MOCK_FLAGS_WITH_THRESHOLD,
});
const controller = createController({
clientConfigApiService,
getMetaMetricsId: Promise.resolve(MOCK_METRICS_ID),
});
await controller.updateRemoteFeatureFlags();

const { testFlagForThreshold, ...nonThresholdFlags } =
controller.state.remoteFeatureFlags;
expect(nonThresholdFlags).toStrictEqual(MOCK_FLAGS);
});

it('uses a fallback metaMetricsId if none is provided', async () => {
jest
.spyOn(userSegmentationUtils, 'generateFallbackMetaMetricsId')
.mockReturnValue(MOCK_METRICS_ID_2);
const clientConfigApiService = buildClientConfigApiService({
remoteFeatureFlags: MOCK_FLAGS_WITH_THRESHOLD,
});
const controller = createController({
clientConfigApiService,
});
await controller.updateRemoteFeatureFlags();

expect(
controller.state.remoteFeatureFlags.testFlagForThreshold,
).toStrictEqual({
name: 'groupA',
value: 'valueA',
});
});
});

describe('enable and disable', () => {
it('enables the controller and makes a network request to fetch', async () => {
const clientConfigApiService = buildClientConfigApiService();
Expand Down Expand Up @@ -273,6 +353,15 @@ describe('RemoteFeatureFlagController', () => {
expect(controller.state.remoteFeatureFlags).toStrictEqual(MOCK_FLAGS);
});
});

describe('getDefaultRemoteFeatureFlagControllerState', () => {
it('should return default state', () => {
expect(getDefaultRemoteFeatureFlagControllerState()).toStrictEqual({
remoteFeatureFlags: {},
cacheTimestamp: 0,
});
});
});
});

type RootAction = RemoteFeatureFlagControllerActions;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ import type { AbstractClientConfigApiService } from './client-config-api-service
import type {
FeatureFlags,
ServiceResponse,
FeatureFlagScopeValue,
} from './remote-feature-flag-controller-types';
import {
generateDeterministicRandomNumber,
isFeatureFlagWithScopeValue,
generateFallbackMetaMetricsId,
} from './utils/user-segmentation-utils';

// === GENERAL ===

Expand Down Expand Up @@ -97,6 +103,8 @@ export class RemoteFeatureFlagController extends BaseController<

#inProgressFlagUpdate?: Promise<ServiceResponse>;

#getMetaMetricsId?: Promise<string | undefined>;

/**
* Constructs a new RemoteFeatureFlagController instance.
*
Expand All @@ -106,17 +114,20 @@ export class RemoteFeatureFlagController extends BaseController<
* @param options.clientConfigApiService - The service instance to fetch remote feature flags.
* @param options.fetchInterval - The interval in milliseconds before cached flags expire. Defaults to 1 day.
* @param options.disabled - Determines if the controller should be disabled initially. Defaults to false.
* @param options.getMetaMetricsId - Promise that resolves to a metaMetricsId.
*/
constructor({
messenger,
state,
clientConfigApiService,
fetchInterval = DEFAULT_CACHE_DURATION,
disabled = false,
getMetaMetricsId,
}: {
messenger: RemoteFeatureFlagControllerMessenger;
state?: Partial<RemoteFeatureFlagControllerState>;
clientConfigApiService: AbstractClientConfigApiService;
getMetaMetricsId?: Promise<string | undefined>;
fetchInterval?: number;
disabled?: boolean;
}) {
Expand All @@ -133,6 +144,7 @@ export class RemoteFeatureFlagController extends BaseController<
this.#fetchInterval = fetchInterval;
this.#disabled = disabled;
this.#clientConfigApiService = clientConfigApiService;
this.#getMetaMetricsId = getMetaMetricsId;
}

/**
Expand Down Expand Up @@ -172,7 +184,7 @@ export class RemoteFeatureFlagController extends BaseController<
this.#inProgressFlagUpdate = undefined;
}

this.#updateCache(serverData.remoteFeatureFlags);
await this.#updateCache(serverData.remoteFeatureFlags);
}

/**
Expand All @@ -181,15 +193,55 @@ export class RemoteFeatureFlagController extends BaseController<
* @param remoteFeatureFlags - The new feature flags to cache.
* @private
*/
#updateCache(remoteFeatureFlags: FeatureFlags) {
async #updateCache(remoteFeatureFlags: FeatureFlags) {
const processedRemoteFeatureFlags = await this.#processRemoteFeatureFlags(
remoteFeatureFlags,
);
this.update(() => {
return {
remoteFeatureFlags,
remoteFeatureFlags: processedRemoteFeatureFlags,
cacheTimestamp: Date.now(),
};
});
}

async #processRemoteFeatureFlags(
remoteFeatureFlags: FeatureFlags,
): Promise<FeatureFlags> {
const processedRemoteFeatureFlags: FeatureFlags = {};
const metaMetricsId =
(await this.#getMetaMetricsId) || generateFallbackMetaMetricsId();
const thresholdValue = generateDeterministicRandomNumber(metaMetricsId);

for (const [
remoteFeatureFlagName,
remoteFeatureFlagValue,
] of Object.entries(remoteFeatureFlags)) {
let processedValue = remoteFeatureFlagValue;

if (Array.isArray(remoteFeatureFlagValue) && thresholdValue) {
const selectedGroup = remoteFeatureFlagValue.find(
(featureFlag): featureFlag is FeatureFlagScopeValue => {
if (!isFeatureFlagWithScopeValue(featureFlag)) {
return false;
}

return thresholdValue <= featureFlag.scope.value;
},
);
if (selectedGroup) {
processedValue = {
name: selectedGroup.name,
value: selectedGroup.value,
};
}
}

processedRemoteFeatureFlags[remoteFeatureFlagName] = processedValue;
}
return processedRemoteFeatureFlags;
}

/**
* Enables the controller, allowing it to make network requests.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { validate as uuidValidate, version as uuidVersion } from 'uuid';

import {
generateDeterministicRandomNumber,
isFeatureFlagWithScopeValue,
generateFallbackMetaMetricsId,
} from './user-segmentation-utils';

const MOCK_METRICS_IDS = [
NicolasMassart marked this conversation as resolved.
Show resolved Hide resolved
'123e4567-e89b-4456-a456-426614174000',
'987fcdeb-51a2-4c4b-9876-543210fedcba',
'a1b2c3d4-e5f6-4890-abcd-ef1234567890',
'f9e8d7c6-b5a4-4210-9876-543210fedcba',
];

const MOCK_FEATURE_FLAGS = {
VALID: {
name: 'test-flag',
value: true,
scope: {
type: 'threshold',
value: 0.5,
},
},
INVALID_NO_SCOPE: {
name: 'test-flag',
value: true,
},
INVALID_VALUES: ['string', 123, true, null, []],
};

describe('user-segmentation-utils', () => {
describe('generateDeterministicRandomNumber', () => {
it('generates consistent numbers for the same input', () => {
const result1 = generateDeterministicRandomNumber(MOCK_METRICS_IDS[0]);
const result2 = generateDeterministicRandomNumber(MOCK_METRICS_IDS[0]);

expect(result1).toBe(result2);
});

it('generates numbers between 0 and 1', () => {
MOCK_METRICS_IDS.forEach((id) => {
const result = generateDeterministicRandomNumber(id);
expect(result).toBeGreaterThanOrEqual(0);
expect(result).toBeLessThanOrEqual(1);
});
});

it('generates different numbers for different inputs', () => {
const result1 = generateDeterministicRandomNumber(MOCK_METRICS_IDS[0]);
const result2 = generateDeterministicRandomNumber(MOCK_METRICS_IDS[1]);

expect(result1).not.toBe(result2);
});
});

describe('isFeatureFlagWithScopeValue', () => {
it('returns true for valid feature flag with scope', () => {
expect(isFeatureFlagWithScopeValue(MOCK_FEATURE_FLAGS.VALID)).toBe(true);
});

it('returns false for null', () => {
expect(isFeatureFlagWithScopeValue(null)).toBe(false);
});

it('returns false for non-objects', () => {
MOCK_FEATURE_FLAGS.INVALID_VALUES.forEach((value) => {
expect(isFeatureFlagWithScopeValue(value)).toBe(false);
});
});

it('returns false for objects without scope', () => {
expect(
isFeatureFlagWithScopeValue(MOCK_FEATURE_FLAGS.INVALID_NO_SCOPE),
).toBe(false);
});
});

describe('generateFallbackMetaMetricsId', () => {
it('returns a valid uuidv4', () => {
const result = generateFallbackMetaMetricsId();
expect(uuidValidate(result)).toBe(true);
expect(uuidVersion(result)).toBe(4);
});
});
});
Loading
Loading