1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00
unleash.unleash/website/docs/how-to/how-to-use-custom-strategies.md
Thomas Heartman d5fbd0b743
refactor: move docs into new structure / fix links for SEO (#2416)
## What

This (admittedly massive) PR updates the "physical" documentation
structure and fixes url inconsistencies and SEO problems reported by
marketing. The main points are:

- remove or move directories : advanced, user_guide, deploy, api
- move the files contained within to the appropriate one of topics,
how-to, tutorials, or reference
- update internal doc links and product links to the content
- create client-side redirects for all the urls that have changed.

A number of the files have been renamed in small ways to better match
their url and to make them easier to find. Additionally, the top-level
api directory has been moved to /reference/api/legacy/unleash (see the
discussion points section for more on this).

## Why

When moving our doc structure to diataxis a while back, we left the
"physical' files lying where they were, because it didn't matter much to
the new structure. However, that did introduce some inconsistencies with
where you place docs and how we organize them.

There's also the discrepancies in whether urls us underscores or hyphens
(which isn't necessarily the same as their file name), which has been
annoying me for a while, but now has also been raised by marketing as an
issue in terms of SEO.

## Discussion points

The old, hand-written API docs have been moved from /api to
/reference/api/legacy/unleash. There _is_ a /reference/api/unleash
directory, but this is being populated by the OpenAPI plugin, and mixing
those could only cause trouble. However, I'm unsure about putting
/legacy/ in the title, because the API isn't legacy, the docs are. Maybe
we could use another path? Like /old-docs/ or something? I'd appreciate
some input on this.
2022-11-22 09:05:30 +00:00

8.6 KiB

title
How to use custom activation strategies

This guide takes you through how to use custom activation strategies with Unleash. We'll go through how you define a custom strategy in the admin UI, how you add it to a toggle, and how you'd implement it in a client SDK.

In this example we want to define an activation strategy offers a scheduled release of a feature toggle. This means that we want the feature toggle to be activated after a given date and time.

Step 1: Define your custom strategy

  1. Navigate to the strategies view. Interact with the "Configure" button in the page header and then go to the "Strategies" link in the dropdown menu that appears.

    A visual guide for how to navigate to the strategies page in the Unleash admin UI. It shows the steps described in the preceding paragraph.

  2. Define your strategy. Use the "Add new strategy" button to open the strategy creation form. Fill in the form to define your strategy. Refer to the custom strategy reference documentation for a full list of options.

    A strategy creation form. It has fields labeled "strategy name" — "TimeStamp" — and "description" — "activate toggle after a given timestamp". It also has fields for a parameter named "enableAfter". The parameter is of type "string" and the parameter description is "Expected format: YYYY-MM-DD HH:MM". The parameter is required.

Step 2: Apply your custom strategy to a feature toggle

Navigate to your feature toggle and apply the strategy you just created.

The strategy configuration screen for the custom "TimeStamp" strategy from the previous step. The "enableAfter" field says "2021-12-25 00:00".

Step 3: Implement the strategy in your client SDK

The steps to implement a custom strategy for your client depend on the kind of client SDK you're using:

Option A: Implement the strategy for a server-side client SDK

  1. Implement the custom strategy in your client SDK. The exact way to do this will vary depending on the specific SDK you're using, so refer to the SDK's documentation. The example below shows an example of how you'd implement a custom strategy called "TimeStamp" for the Node.js client SDK.

    const { Strategy } = require('unleash-client');
    
    class TimeStampStrategy extends Strategy {
      constructor() {
        super('TimeStamp');
      }
    
      isEnabled(parameters, context) {
        return Date.parse(parameters.enableAfter) < Date.now();
      }
    }
    
  2. Register the custom strategy with the Unleash Client. When instantiating the Unleash Client, provide it with a list of the custom strategies you'd like to use — again: refer to your client SDK's docs for the specifics.

    Here's a full, working example for Node.js. Notice the strategies property being passed to the initialize function.

    const { Strategy, initialize, isEnabled } = require('unleash-client');
    
    class TimeStampStrategy extends Strategy {
      constructor() {
        super('TimeStamp');
      }
    
      isEnabled(parameters, context) {
        return Date.parse(parameters.enableAfter) < Date.now();
      }
    }
    
    const instance = initialize({
      url: 'https://unleash.example.com/api/',
      appName: 'unleash-demo',
      instanceId: '1',
      // highlight-next-line
      strategies: [new TimeStampStrategy()],
    });
    
    instance.on('ready', () => {
      setInterval(() => {
        console.log(isEnabled('demo.TimeStampRollout'));
      }, 1000);
    });
    

Option B: Implement the strategy for a front-end client SDK

Front-end client SDKs don't evaluate strategies directly, so you need to implement the custom strategy in the Unleash Proxy. Depending on how you run the Unleash Proxy, follow one of the below series of steps:

With a containerized proxy

Strategies are stored in separate JavaScript files and loaded into the container at startup. Refer to the Unleash Proxy documentation for a full overview of all the options.

  1. Create a strategies directory. Create a directory that Docker has access to where you can store your strategies. The next steps assume you called it strategies

  2. Initialize a Node.js project and install the Unleash Client:

    npm init -y && \
    npm install unleash-client
    
  3. Create a strategy file and implement your strategies. Remember to export your list of strategies. The next steps will assume you called the file timestamp.js. An example implementation looks like this:

    const { Strategy } = require('unleash-client');
    
    class TimeStampStrategy extends Strategy {
      constructor() {
        super('TimeStamp');
      }
    
      isEnabled(parameters, context) {
        return Date.parse(parameters.enableAfter) < Date.now();
      }
    }
    
    module.exports = [new TimeStampStrategy()]; // <- export strategies
    
  4. Mount the strategies directory and point the Unleash Proxy docker container at your strategies file. The highlighted lines below show the extra options you need to add. The following command assumes that your strategies directory is a direct subdirectory of your current working directory. Modify the rest of the command to suit your needs.

    docker run --name unleash-proxy --pull=always \
        -e UNLEASH_PROXY_CLIENT_KEYS=some-secret \
        -e UNLEASH_URL='http://unleash:4242/api/' \
        -e UNLEASH_API_TOKEN=${API_TOKEN} \
        # highlight-start
        -e UNLEASH_CUSTOM_STRATEGIES_FILE=/strategies/timestamp.js \
        --mount type=bind,source="$(pwd)"/strategies,target=/strategies \
        # highlight-end
        -p 3000:3000 --network unleash unleashorg/unleash-proxy
    

When running the proxy with Node.js

The Unleash Proxy accepts a customStrategies property as part of its initialization options. Use this to pass it initialized strategies.

  1. Install the unleash-client package. You'll need this to implement the custom strategy:

    npm install unleash-client
    
  2. Implement your strategy. You can import it from a different file or put it in the same file as the Proxy initialization. For instance, a TimeStampStrategy could look like this:

    const { Strategy } = require('unleash-client');
    
    class TimeStampStrategy extends Strategy {
      constructor() {
        super('TimeStamp');
      }
    
      isEnabled(parameters, context) {
        return Date.parse(parameters.enableAfter) < Date.now();
      }
    }
    
  3. Pass the strategy to the Proxy Client using the customStrategies option. A full code example:

    const { createApp } = require('@unleash/proxy');
    const { Strategy } = require('unleash-client');
    
    class TimeStampStrategy extends Strategy {
      constructor() {
        super('TimeStamp');
      }
    
      isEnabled(parameters, context) {
        return Date.parse(parameters.enableAfter) < Date.now();
      }
    }
    
    const port = 3000;
    
    const app = createApp({
      unleashUrl: 'https://app.unleash-hosted.com/demo/api/',
      unleashApiToken:
        '*:default.56907a2fa53c1d16101d509a10b78e36190b0f918d9f122d',
      clientKeys: ['proxy-secret', 'another-proxy-secret', 's1'],
      refreshInterval: 1000,
      // highlight-next-line
      customStrategies: [new TimeStampStrategy()],
    });
    
    app.listen(port, () =>
      // eslint-disable-next-line no-console
      console.log(`Unleash Proxy listening on http://localhost:${port}/proxy`),
    );