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(flags/v8): Add Unleash integration #14948

Open
wants to merge 23 commits into
base: v8
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 14 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../../../utils/fixtures';

import { envelopeRequestParser, shouldSkipFeatureFlagsTest, waitForErrorRequest } from '../../../../../utils/helpers';

const FLAG_BUFFER_SIZE = 100; // Corresponds to constant in featureFlags.ts, in browser utils.

sentryTest('Basic test with eviction, update, and no async tasks', async ({ getLocalTestUrl, page }) => {
if (shouldSkipFeatureFlagsTest()) {
sentryTest.skip();
}

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

const url = await getLocalTestUrl({ testDir: __dirname, skipDsnRouteHandler: true });
await page.goto(url);

await page.evaluate(bufferSize => {
const client = new (window as any).UnleashClient();

client.isEnabled('feat1');
client.isEnabled('strFeat');
client.isEnabled('noPayloadFeat');
client.isEnabled('jsonFeat');
client.isEnabled('noVariantFeat');
client.isEnabled('disabledFeat');

for (let i = 7; i <= bufferSize; i++) {
client.isEnabled(`feat${i}`);
}
client.isEnabled(`feat${bufferSize + 1}`); // eviction
client.isEnabled('noPayloadFeat'); // update (move to tail)
}, FLAG_BUFFER_SIZE);

const reqPromise = waitForErrorRequest(page);
await page.locator('#error').click();
const req = await reqPromise;
const event = envelopeRequestParser(req);

const expectedFlags = [{ flag: 'strFeat', result: true }];
expectedFlags.push({ flag: 'jsonFeat', result: true });
expectedFlags.push({ flag: 'noVariantFeat', result: true });
expectedFlags.push({ flag: 'disabledFeat', result: false });
for (let i = 7; i <= FLAG_BUFFER_SIZE; i++) {
expectedFlags.push({ flag: `feat${i}`, result: false });
}
expectedFlags.push({ flag: `feat${FLAG_BUFFER_SIZE + 1}`, result: false });
expectedFlags.push({ flag: 'noPayloadFeat', result: true });

expect(event.contexts?.flags?.values).toEqual(expectedFlags);
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import * as Sentry from '@sentry/browser';

window.UnleashClient = class {
constructor() {
this._featureToVariant = {
strFeat: { name: 'variant1', enabled: true, feature_enabled: true, payload: { type: 'string', value: 'test' } },
noPayloadFeat: { name: 'eu-west', enabled: true, feature_enabled: true },
jsonFeat: {
name: 'paid-orgs',
enabled: true,
feature_enabled: true,
payload: {
type: 'json',
value: '{"foo": {"bar": "baz"}, "hello": [1, 2, 3]}',
},
},

// Enabled feature with no configured variants.
noVariantFeat: { name: 'disabled', enabled: false, feature_enabled: true },

// Disabled feature.
disabledFeat: { name: 'disabled', enabled: false, feature_enabled: false },
};

// Variant returned for features that don't exist.
// `feature_enabled` may be defined in prod, but we want to test the undefined case.
this._fallbackVariant = {
name: 'disabled',
enabled: false,
};
}

isEnabled(toggleName) {
const variant = this._featureToVariant[toggleName] || this._fallbackVariant;
return variant.feature_enabled || false;
}

getVariant(toggleName) {
return this._featureToVariant[toggleName] || this._fallbackVariant;
}
};

window.Sentry = Sentry;
window.sentryUnleashIntegration = Sentry.unleashIntegration(window.UnleashClient);

Sentry.init({
dsn: 'https://[email protected]/1337',
sampleRate: 1.0,
integrations: [window.sentryUnleashIntegration],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
document.getElementById('error').addEventListener('click', () => {
throw new Error('Button triggered error');
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="error">Throw Error</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../../../utils/fixtures';

import { envelopeRequestParser, shouldSkipFeatureFlagsTest, waitForErrorRequest } from '../../../../../utils/helpers';

import type { Scope } from '@sentry/browser';

sentryTest('Flag evaluations in forked scopes are stored separately.', async ({ getLocalTestUrl, page }) => {
if (shouldSkipFeatureFlagsTest()) {
sentryTest.skip();
}

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

const url = await getLocalTestUrl({ testDir: __dirname, skipDsnRouteHandler: true });
await page.goto(url);

const forkedReqPromise = waitForErrorRequest(page, event => !!event.tags && event.tags.isForked === true);
const mainReqPromise = waitForErrorRequest(page, event => !!event.tags && event.tags.isForked === false);

await page.evaluate(() => {
const Sentry = (window as any).Sentry;
const errorButton = document.querySelector('#error') as HTMLButtonElement;
const unleash = new (window as any).UnleashClient();

unleash.isEnabled('strFeat');

Sentry.withScope((scope: Scope) => {
unleash.isEnabled('disabledFeat');
unleash.isEnabled('strFeat');
scope.setTag('isForked', true);
if (errorButton) {
errorButton.click();
}
});

unleash.isEnabled('noPayloadFeat');
Sentry.getCurrentScope().setTag('isForked', false);
errorButton.click();
return true;
});

const forkedReq = await forkedReqPromise;
const forkedEvent = envelopeRequestParser(forkedReq);

const mainReq = await mainReqPromise;
const mainEvent = envelopeRequestParser(mainReq);

expect(forkedEvent.contexts?.flags?.values).toEqual([
{ flag: 'disabledFeat', result: false },
{ flag: 'strFeat', result: true },
]);

expect(mainEvent.contexts?.flags?.values).toEqual([
{ flag: 'strFeat', result: true },
{ flag: 'noPayloadFeat', result: true },
]);
});
1 change: 1 addition & 0 deletions packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,4 @@ export {
} from './integrations/featureFlags';
export { launchDarklyIntegration, buildLaunchDarklyFlagUsedHandler } from './integrations/featureFlags/launchdarkly';
export { openFeatureIntegration, OpenFeatureIntegrationHook } from './integrations/featureFlags/openfeature';
export { unleashIntegration } from './integrations/featureFlags/unleash';
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { unleashIntegration } from './integration';
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { Client, Event, EventHint, IntegrationFn } from '@sentry/core';

import { defineIntegration } from '@sentry/core';
import { copyFlagsFromScopeToEvent, insertFlagToScope } from '../../../utils/featureFlags';
import type { UnleashClient, UnleashClientClass } from './types';

/**
* Sentry integration for capturing feature flag evaluations from the Unleash SDK.
*
* See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.
*
* @example
* ```
* import { UnleashClient } from 'unleash-proxy-client';
* import * as Sentry from '@sentry/browser';
*
* const unleashIntegration = Sentry.unleashIntegration(UnleashClient);
aliu39 marked this conversation as resolved.
Show resolved Hide resolved
*
* Sentry.init({
* dsn: '___PUBLIC_DSN___',
* integrations: [unleashIntegration],
* });
*
* const unleash = new UnleashClient(...);
* unleash.start();
*
* unleash.isEnabled('my-feature');
* unleash.getVariant('other-feature');
* Sentry.captureException(new Error('something went wrong'));
* ```
*/
export const unleashIntegration = defineIntegration((unleashClientClass: UnleashClientClass) => {
return {
name: 'Unleash',

processEvent(event: Event, _hint: EventHint, _client: Client): Event {
return copyFlagsFromScopeToEvent(event);
},

setupOnce() {
const unleashClientPrototype = unleashClientClass.prototype as UnleashClient;

const sentryIsEnabled = {
apply: (
target: (this: UnleashClient, toggleName: string) => boolean,
thisArg: UnleashClient,
args: [toggleName: string],
) => {
const result = Reflect.apply(target, thisArg, args);
insertFlagToScope(args[0], result);
return result;
},
};
// eslint-disable-next-line @typescript-eslint/unbound-method
const originalIsEnabled = unleashClientPrototype.isEnabled;
unleashClientPrototype.isEnabled = new Proxy(originalIsEnabled, sentryIsEnabled);
aliu39 marked this conversation as resolved.
Show resolved Hide resolved
},
};
}) satisfies IntegrationFn;
16 changes: 16 additions & 0 deletions packages/browser/src/integrations/featureFlags/unleash/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export interface IVariant {
name: string;
enabled: boolean;
feature_enabled?: boolean;
payload?: {
type: string;
value: string;
};
}

export interface UnleashClient {
isEnabled(this: UnleashClient, featureName: string): boolean;
getVariant(this: UnleashClient, featureName: string): IVariant;
}

export type UnleashClientClass = new (...args: unknown[]) => UnleashClient;
Loading