Skip to content
Merged
Show file tree
Hide file tree
Changes from 17 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
71 changes: 71 additions & 0 deletions examples/express-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Examples for Microsoft Feature Management for JavaScript

These examples show how to use the Microsoft Feature Management in an express application.

## Prerequisites

The examples are compatible with [LTS versions of Node.js](https://github.com/nodejs/release#release-schedule).

## Setup & Run

1. Install the dependencies using `npm`:

```bash
npm install
```

1. Run the examples:

```bash
node server.mjs
```

1. Visit `http://localhost:3000/Beta` and use `userId` and `groups` query to specify the targeting context (e.g. /Beta?userId=Jeff or /Beta?groups=Admin).

- If you are not targeted, you will get the message "Page not found".

- If you are targeted, you will get the message "Welcome to the Beta page!".

## Targeting

The targeting mechanism uses the `exampleTargetingContextAccessor` to extract the targeting context from the request. This function retrieves the userId and groups from the query parameters of the request.

```javascript
const exampleTargetingContextAccessor = {
getTargetingContext: () => {
const req = requestAccessor.getStore();
const { userId, groups } = req.query;
return { userId: userId, groups: groups ? groups.split(",") : [] };
}
};
```

The `FeatureManager` is configured with this targeting context accessor:

```javascript
const featureManager = new FeatureManager(
featureProvider,
{
targetingContextAccessor: exampleTargetingContextAccessor
}
);
```

This allows you to get ambient targeting context while doing feature flag evaluation.

### Request Accessor

The `requestAccessor` is an instance of `AsyncLocalStorage` from the `async_hooks` module. It is used to store the request object in asynchronous local storage, allowing it to be accessed throughout the lifetime of the request. This is particularly useful for accessing request-specific data in asynchronous operations. For more information, please go to https://nodejs.org/api/async_context.html

```javascript
import { AsyncLocalStorage } from "async_hooks";
const requestAccessor = new AsyncLocalStorage();
```

Middleware is used to store the request object in the AsyncLocalStorage:

```javascript
server.use((req, res, next) => {
requestAccessor.run(req, next);
});
```
31 changes: 31 additions & 0 deletions examples/express-app/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"feature_management": {
"feature_flags": [
{
"id": "Beta",
"enabled": true,
"conditions": {
"client_filters": [
{
"name": "Microsoft.Targeting",
"parameters": {
"Audience": {
"Users": [
"Jeff"
],
"Groups": [
{
"Name": "Admin",
"RolloutPercentage": 100
}
],
"DefaultRolloutPercentage": 40
}
}
}
]
}
}
]
}
}
9 changes: 9 additions & 0 deletions examples/express-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"scripts": {
"start": "node server.mjs"
},
"dependencies": {
"@microsoft/feature-management": "../../src/feature-management",
"express": "^4.21.2"
}
}
58 changes: 58 additions & 0 deletions examples/express-app/server.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import fs from "fs/promises";
import { ConfigurationObjectFeatureFlagProvider, FeatureManager } from "@microsoft/feature-management";
// You can also use Azure App Configuration as the source of feature flags.
// For more information, please go to quickstart: https://learn.microsoft.com/azure/azure-app-configuration/quickstart-feature-flag-javascript

const config = JSON.parse(await fs.readFile("config.json"));
const featureProvider = new ConfigurationObjectFeatureFlagProvider(config);

// https://nodejs.org/api/async_context.html
import { AsyncLocalStorage } from "async_hooks";
const requestAccessor = new AsyncLocalStorage();
const exampleTargetingContextAccessor = {
getTargetingContext: () => {
const req = requestAccessor.getStore();
const { userId, groups } = req.query;
return { userId: userId, groups: groups ? groups.split(",") : [] };
}
};

const featureManager = new FeatureManager(
featureProvider,
{
targetingContextAccessor: exampleTargetingContextAccessor
}
);

import express from "express";
const server = express();
const PORT = 3000;

// Use a middleware to store the request object in async local storage.
// The async local storage allows the targeting context accessor to access the current request throughout its lifetime.
// Middleware 1 (request object is stored in async local storage here and it will be available across the following chained async operations)
// Middleware 2
// Request Handler (feature flag evaluation happens here)
server.use((req, res, next) => {
requestAccessor.run(req, next);
});

server.get("/", (req, res) => {
res.send("Hello World!");
});

server.get("/Beta", async (req, res) => {
if (await featureManager.isEnabled("Beta")) {
res.send("Welcome to the Beta page!");
} else {
res.status(404).send("Page not found");
}
});

// Start the server
server.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});
2 changes: 1 addition & 1 deletion src/feature-management/src/IFeatureManager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

import { ITargetingContext } from "./common/ITargetingContext";
import { ITargetingContext } from "./common/targetingContext";
import { Variant } from "./variant/Variant";

export interface IFeatureManager {
Expand Down
8 changes: 0 additions & 8 deletions src/feature-management/src/common/ITargetingContext.ts

This file was deleted.

26 changes: 26 additions & 0 deletions src/feature-management/src/common/targetingContext.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

/**
* Contextual information that is required to perform a targeting evaluation.
*/
export interface ITargetingContext {
/**
* The user id that should be considered when evaluating if the context is being targeted.
*/
userId?: string;
/**
* The groups that should be considered when evaluating if the context is being targeted.
*/
groups?: string[];
}

/**
* Provides access to the current targeting context.
*/
export interface ITargetingContextAccessor {
/**
* Retrieves the current targeting context.
*/
getTargetingContext: () => ITargetingContext | undefined;
}
44 changes: 30 additions & 14 deletions src/feature-management/src/featureManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,25 @@ import { IFeatureFlagProvider } from "./featureProvider.js";
import { TargetingFilter } from "./filter/TargetingFilter.js";
import { Variant } from "./variant/Variant.js";
import { IFeatureManager } from "./IFeatureManager.js";
import { ITargetingContext } from "./common/ITargetingContext.js";
import { ITargetingContext, ITargetingContextAccessor } from "./common/targetingContext.js";
import { isTargetedGroup, isTargetedPercentile, isTargetedUser } from "./common/targetingEvaluator.js";

export class FeatureManager implements IFeatureManager {
#provider: IFeatureFlagProvider;
#featureFilters: Map<string, IFeatureFilter> = new Map();
#onFeatureEvaluated?: (event: EvaluationResult) => void;
readonly #provider: IFeatureFlagProvider;
readonly #featureFilters: Map<string, IFeatureFilter> = new Map();
readonly #onFeatureEvaluated?: (event: EvaluationResult) => void;
readonly #targetingContextAccessor?: ITargetingContextAccessor;

constructor(provider: IFeatureFlagProvider, options?: FeatureManagerOptions) {
this.#provider = provider;
this.#onFeatureEvaluated = options?.onFeatureEvaluated;
this.#targetingContextAccessor = options?.targetingContextAccessor;

const builtinFilters = [new TimeWindowFilter(), new TargetingFilter()];

const builtinFilters = [new TimeWindowFilter(), new TargetingFilter(options?.targetingContextAccessor)];
// If a custom filter shares a name with an existing filter, the custom filter overrides the existing one.
for (const filter of [...builtinFilters, ...(options?.customFilters ?? [])]) {
this.#featureFilters.set(filter.name, filter);
}

this.#onFeatureEvaluated = options?.onFeatureEvaluated;
}

async listFeatureNames(): Promise<string[]> {
Expand Down Expand Up @@ -78,7 +78,7 @@ export class FeatureManager implements IFeatureManager {
return { variant: undefined, reason: VariantAssignmentReason.None };
}

async #isEnabled(featureFlag: FeatureFlag, context?: unknown): Promise<boolean> {
async #isEnabled(featureFlag: FeatureFlag, appContext?: unknown): Promise<boolean> {
if (featureFlag.enabled !== true) {
// If the feature is not explicitly enabled, then it is disabled by default.
return false;
Expand Down Expand Up @@ -106,7 +106,7 @@ export class FeatureManager implements IFeatureManager {
console.warn(`Feature filter ${clientFilter.name} is not found.`);
return false;
}
if (await matchedFeatureFilter.evaluate(contextWithFeatureName, context) === shortCircuitEvaluationResult) {
if (await matchedFeatureFilter.evaluate(contextWithFeatureName, appContext) === shortCircuitEvaluationResult) {
return shortCircuitEvaluationResult;
}
}
Expand All @@ -115,7 +115,7 @@ export class FeatureManager implements IFeatureManager {
return !shortCircuitEvaluationResult;
}

async #evaluateFeature(featureName: string, context: unknown): Promise<EvaluationResult> {
async #evaluateFeature(featureName: string, appContext: unknown): Promise<EvaluationResult> {
const featureFlag = await this.#provider.getFeatureFlag(featureName);
const result = new EvaluationResult(featureFlag);

Expand All @@ -128,9 +128,10 @@ export class FeatureManager implements IFeatureManager {
validateFeatureFlagFormat(featureFlag);

// Evaluate if the feature is enabled.
result.enabled = await this.#isEnabled(featureFlag, context);
result.enabled = await this.#isEnabled(featureFlag, appContext);

const targetingContext = context as ITargetingContext;
// Get targeting context from the app context or the targeting context accessor
const targetingContext = this.#getTargetingContext(appContext);
result.targetingId = targetingContext?.userId;

// Determine Variant
Expand All @@ -151,7 +152,7 @@ export class FeatureManager implements IFeatureManager {
}
} else {
// enabled, assign based on allocation
if (context !== undefined && featureFlag.allocation !== undefined) {
if (targetingContext !== undefined && featureFlag.allocation !== undefined) {
const variantAndReason = await this.#assignVariant(featureFlag, targetingContext);
variantDef = variantAndReason.variant;
reason = variantAndReason.reason;
Expand Down Expand Up @@ -189,6 +190,16 @@ export class FeatureManager implements IFeatureManager {

return result;
}

#getTargetingContext(context: unknown): ITargetingContext | undefined {
let targetingContext: ITargetingContext | undefined = context as ITargetingContext;
if (targetingContext?.userId === undefined &&
targetingContext?.groups === undefined &&
this.#targetingContextAccessor !== undefined) {
targetingContext = this.#targetingContextAccessor.getTargetingContext();
}
return targetingContext;
}
}

export interface FeatureManagerOptions {
Expand All @@ -202,6 +213,11 @@ export interface FeatureManagerOptions {
* The callback function is called only when telemetry is enabled for the feature flag.
*/
onFeatureEvaluated?: (event: EvaluationResult) => void;

/**
* The accessor function that provides the @see ITargetingContext for targeting evaluation.
*/
targetingContextAccessor?: ITargetingContextAccessor;
}

export class EvaluationResult {
Expand Down
Loading