OpenFeature Dart Server SDK

Specification Release Built with Dart
Pub Version API Reference Code Coverage GitHub CI Status

:warning: This repository is a work in progress repository for an implementation of the dart-server-sdk.

OpenFeature is an open specification that provides a vendor-agnostic, community-driven API for feature flagging that works with your favorite feature flag management tool.

🚀 Quick start

Requirements

Dart language version: 3.10.7

Note

The OpenFeature DartServer SDK only supports the latest currently maintained Dart language versions.

Install

dependencies:
  openfeature_dart_server_sdk: ^0.0.18

Then run:

dart pub get

Usage

import 'dart:async';
import 'package:openfeature_dart_server_sdk/open_feature_api.dart';
import 'package:openfeature_dart_server_sdk/feature_provider.dart';

void main() async {
  // Get the API instance
  final api = OpenFeatureAPI();

  // Register your feature flag provider and wait for it to be ready
  await api.setProviderAndWait(InMemoryProvider({
    'new-feature': true,
    'welcome-message': 'Hello, OpenFeature!'
  }));

  // Create a client
  final client = api.getClient('my-app');

  // Evaluate your feature flags
  final newFeatureEnabled = await client.getBooleanFlag(
    'new-feature',
    defaultValue: false,
  );

  // Get full evaluation details if needed
  final details = await client.getBooleanDetails(
    'new-feature',
    defaultValue: false,
  );
  print('Reason: ${details.reason}, Variant: ${details.variant}');

  // Use the returned flag value
  if (newFeatureEnabled) {
    print('New feature is enabled!');

    final welcomeMessage = await client.getStringFlag(
      'welcome-message',
      defaultValue: 'Welcome!',
    );

    print(welcomeMessage);
  }
}

API Reference

See here for the complete API documentation.

🌟 Features

Status Features Description
Providers Integrate with a commercial, open source, or in-house feature management tool.
Targeting Contextually-aware flag evaluation using evaluation context.
Hooks Add functionality to various stages of the flag evaluation life-cycle.
Tracking Associate user actions with feature flag evaluations for experimentation.
Logging Integrate with popular logging packages.
Domains Logically bind clients with providers.
Eventing React to state changes in the provider or flag management system.
Shutdown Gracefully clean up a provider during application shutdown.
Transaction Context Propagation Set a specific evaluation context for a transaction (e.g. an HTTP request or a thread)
Extending Extend OpenFeature with custom providers and hooks.

Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌

Providers

Providers are an abstraction between a flag management system and the OpenFeature SDK. Look here for a complete list of available providers. If the provider you're looking for hasn't been created yet, see the develop a provider section to learn how to build it yourself.

Once you've added a provider as a dependency, it can be registered with OpenFeature like this:

final api = OpenFeatureAPI();
api.setProvider(MyProvider());

Targeting

Sometimes, the value of a flag must consider some dynamic criteria about the application or user, such as the user's location, IP, email address, or the server's location. In OpenFeature, we refer to this as targeting. If the flag management system you're using supports targeting, you can provide the input data using the evaluation context.

// Set a value to the global context
final api = OpenFeatureAPI();
api.setGlobalContext(OpenFeatureEvaluationContext({
  'region': 'us-east-1-iah-1a',
}));

// Create a client with a client-level default context
final client = FeatureClient(
  metadata: ClientMetadata(name: 'my-app'),
  hookManager: HookManager(),
  defaultContext: EvaluationContext(attributes: {
    'version': '1.4.6',
  }),
  provider: api.provider,
);

// Set a value to the invocation context
final result = await client.getBooleanFlag(
  'feature-flag',
  defaultValue: false,
  context: EvaluationContext(attributes: {
    'user': 'user-123',
    'company': 'Initech',
  }),
);

Hooks

Hooks allow for custom logic to be added at well-defined points of the flag evaluation life-cycle Look here for a complete list of available hooks. If the hook you're looking for hasn't been created yet, see the develop a hook section to learn how to build it yourself.

Once you've added a hook as a dependency, it can be registered at the global, client, or flag invocation level.

// Add a hook globally, to run on all evaluations
final api = OpenFeatureAPI();
api.addHooks([MyGlobalHook()]);

// Add a hook on this client, to run on all evaluations made by this client
final hookManager = HookManager();
hookManager.addHook(MyClientHook());

final client = FeatureClient(
  metadata: ClientMetadata(name: 'my-app'),
  hookManager: hookManager,
  defaultContext: EvaluationContext(attributes: {}),
  provider: api.provider,
);

Note

Invocation-level hooks are not yet supported. Hooks can currently be registered at the global or client level.

Tracking

The tracking API allows you to use OpenFeature abstractions and objects to associate user actions with feature flag evaluations. This is essential for robust experimentation powered by feature flags. For example, a flag enhancing the appearance of a UI component might drive user engagement to a new feature; to test this hypothesis, telemetry collected by a hook or provider can be associated with telemetry reported in the client's track function.

Note that some providers may not support tracking; check the documentation for your provider for more information.

import 'package:openfeature_dart_server_sdk/open_feature_api.dart';
import 'package:openfeature_dart_server_sdk/feature_provider.dart';

final api = OpenFeatureAPI();
final client = api.getClient('my-app');

// Track a user action associated with a feature flag evaluation
await client.track(
  'checkout-completed',
  context: EvaluationContext(attributes: {
    'user': 'user-123',
  }),
  trackingDetails: TrackingEventDetails(
    value: 99.99,
    attributes: {'currency': 'USD'},
  ),
);

Logging

Note that in accordance with the OpenFeature specification, the SDK doesn't generally log messages during flag evaluation.

The SDK uses the package:logging structured logging API internally. You can configure log levels and listeners to capture SDK log output for troubleshooting and debugging.

See hooks for more information on adding custom logging behavior via hooks.

Domains

Clients can be assigned to a domain. A domain is a logical identifier that can be used to associate clients with a particular provider. If a domain has no associated provider, the default provider is used.

import 'package:openfeature_dart_server_sdk/domain_manager.dart';
import 'package:openfeature_dart_server_sdk/feature_provider.dart';
import 'package:openfeature_dart_server_sdk/open_feature_api.dart';

// Get the OpenFeature API instance
final api = OpenFeatureAPI();

// Register the default provider
api.setProvider(InMemoryProvider({'default-flag': true}));

// Register a domain-specific provider
api.bindClientToProvider('cache-domain', 'CachedProvider');

// Client backed by default provider
final defaultClient = api.getClient('default-client');
await defaultClient.getBooleanFlag('my-flag', defaultValue: false);

// Client backed by CachedProvider
final cacheClient = api.getClient('cache-client', domain: 'cache-domain');
await cacheClient.getBooleanFlag('my-flag', defaultValue: false);

Eventing

Events allow you to react to state changes in the provider or underlying flag management system, such as flag definition changes, provider readiness, or error conditions. Initialization events (PROVIDER_READY on success, PROVIDER_ERROR on failure) are dispatched for every provider. Some providers support additional events, such as PROVIDER_CONFIGURATION_CHANGED.

Please refer to the documentation of the provider you're using to see what events are supported.

import 'package:openfeature_dart_server_sdk/open_feature_api.dart';
import 'package:openfeature_dart_server_sdk/open_feature_event.dart';

// Get the OpenFeature API instance
final api = OpenFeatureAPI();

// Listen for provider configuration change events
api.events.listen((event) {
  if (event.type == OpenFeatureEventType.PROVIDER_CONFIGURATION_CHANGED) {
    print('Provider configuration changed: ${event.message}');
  }
});

The SDK also provides a global event bus for flag evaluation events:

import 'package:openfeature_dart_server_sdk/event_system.dart';

// Listen for flag evaluation events
OpenFeatureEvents.instance.subscribe(
  (event) {
    print('Flag evaluated: ${event.data['flagKey']} = ${event.data['result']}');
  },
  filter: EventFilter(
    types: {OpenFeatureEventType.flagEvaluated},
  ),
);

Shutdown

The OpenFeature API provides mechanisms to perform a cleanup of all registered providers. This should only be called when your application is in the process of shutting down.

import 'package:openfeature_dart_server_sdk/open_feature_api.dart';
import 'package:openfeature_dart_server_sdk/shutdown_manager.dart';

// Get the OpenFeature API instance
final api = OpenFeatureAPI();

// Register shutdown hooks
final shutdownManager = ShutdownManager();
shutdownManager.registerHook(ShutdownHook(
  name: 'provider-cleanup',
  phase: ShutdownPhase.PROVIDER_SHUTDOWN,
  execute: () async {
    // Clean up provider resources
    await api.dispose();
  },
));

// During application shutdown
await shutdownManager.shutdown();

Transaction Context Propagation

Transaction context is a container for transaction-specific evaluation context (e.g. user id, user agent, IP). Transaction context can be set where specific data is available (e.g. an auth service or request handler), and by using the transaction context propagator, it will automatically be applied to all flag evaluations within a transaction (e.g. a request or thread).

import 'package:openfeature_dart_server_sdk/transaction_context.dart';

// Get the transaction context manager (singleton)
final transactionManager = TransactionContextManager();

// Set the transaction context
final context = TransactionContext(
  transactionId: 'request-123',
  attributes: {
    'user': 'user-456',
    'region': 'us-west-1',
  },
);
transactionManager.pushContext(context);

// The transaction context will automatically be applied to flag evaluations
await client.getBooleanFlag('my-flag', defaultValue: false);

// Execute code with a specific transaction context
await transactionManager.withContext(
  'transaction-id',
  {'user': 'user-123'},
  () async {
    await client.getBooleanFlag('my-flag', defaultValue: false);
  },
);

// When the transaction is complete, pop the context
transactionManager.popContext();

Extending

Develop a provider

To develop a provider, you need to create a new project and include the OpenFeature SDK as a dependency. This can be a new repository or included in the existing contrib repository available under the OpenFeature organization. You'll then need to write the provider by implementing the FeatureProvider interface exported by the OpenFeature SDK.

import 'dart:async';
import 'package:openfeature_dart_server_sdk/feature_provider.dart';

class MyCustomProvider implements FeatureProvider {
  @override
  String get name => 'MyCustomProvider';

  @override
  ProviderMetadata get metadata => ProviderMetadata(name: name);

  @override
  ProviderState get state => ProviderState.READY;

  @override
  ProviderConfig get config => ProviderConfig();

  @override
  Future<void> initialize([Map<String, dynamic>? config]) async {
    // Initialize your provider
  }

  @override
  Future<void> connect() async {
    // Connection logic if needed
  }

  @override
  Future<void> shutdown() async {
    // Clean up resources
  }

  @override
  Future<void> track(
    String trackingEventName, {
    Map<String, dynamic>? evaluationContext,
    TrackingEventDetails? trackingDetails,
  }) async {
    // Send tracking event to your backend, or no-op if unsupported
  }

  @override
  Future<FlagEvaluationResult<bool>> getBooleanFlag(
    String flagKey,
    bool defaultValue, {
    Map<String, dynamic>? context,
  }) async {
    // Evaluate boolean flag
    return FlagEvaluationResult(
      flagKey: flagKey,
      value: true, // Your implementation here
      evaluatedAt: DateTime.now(),
      evaluatorId: name,
    );
  }

  @override
  Future<FlagEvaluationResult<String>> getStringFlag(
    String flagKey,
    String defaultValue, {
    Map<String, dynamic>? context,
  }) async {
    // Evaluate string flag
    return FlagEvaluationResult(
      flagKey: flagKey,
      value: 'value', // Your implementation here
      evaluatedAt: DateTime.now(),
      evaluatorId: name,
    );
  }

  @override
  Future<FlagEvaluationResult<int>> getIntegerFlag(
    String flagKey,
    int defaultValue, {
    Map<String, dynamic>? context,
  }) async {
    // Evaluate integer flag
    return FlagEvaluationResult(
      flagKey: flagKey,
      value: 42, // Your implementation here
      evaluatedAt: DateTime.now(),
      evaluatorId: name,
    );
  }

  @override
  Future<FlagEvaluationResult<double>> getDoubleFlag(
    String flagKey,
    double defaultValue, {
    Map<String, dynamic>? context,
  }) async {
    // Evaluate double flag
    return FlagEvaluationResult(
      flagKey: flagKey,
      value: 3.14, // Your implementation here
      evaluatedAt: DateTime.now(),
      evaluatorId: name,
    );
  }

  @override
  Future<FlagEvaluationResult<Map<String, dynamic>>> getObjectFlag(
    String flagKey,
    Map<String, dynamic> defaultValue, {
    Map<String, dynamic>? context,
  }) async {
    // Evaluate object flag
    return FlagEvaluationResult(
      flagKey: flagKey,
      value: {'key': 'value'}, // Your implementation here
      evaluatedAt: DateTime.now(),
      evaluatorId: name,
    );
  }
}

Built a new provider? Let us know so we can add it to the docs!

Develop a hook

To develop a hook, you need to create a new project and include the OpenFeature SDK as a dependency. This can be a new repository or included in the existing contrib repository available under the OpenFeature organization. Implement your own hook by conforming to the Hook interface. To satisfy the interface, all methods (before/after/finally_/error) need to be defined. To avoid defining empty functions, extend the BaseHook class (which provides no-op default implementations for all methods).

import 'dart:async';
import 'package:openfeature_dart_server_sdk/hooks.dart';

class MyCustomHook extends BaseHook {
  MyCustomHook()
    : super(metadata: HookMetadata(name: 'MyCustomHook'));

  @override
  Future<void> before(HookContext context) async {
    // Code to run before flag evaluation
    print('Before evaluating flag: ${context.flagKey}');
  }

  @override
  Future<void> after(HookContext context) async {
    // Code to run after successful flag evaluation
    print('After evaluating flag: ${context.flagKey}, result: ${context.result}');
  }

  @override
  Future<void> error(HookContext context) async {
    // Code to run when an error occurs during flag evaluation
    print('Error evaluating flag: ${context.flagKey}, error: ${context.error}');
  }

  @override
  Future<void> finally_(
    HookContext context,
    EvaluationDetails? evaluationDetails, [
    HookHints? hints,
  ]) async {
    // Code to run regardless of success or failure
    print('Finished evaluating flag: ${context.flagKey}');
  }
}

Built a new hook? Let us know so we can add it to the docs!

Testing

Use the InMemoryProvider to set flags for the scope of a test. Use OpenFeatureAPI.resetInstance() in tearDown to clean up between tests.

import 'package:test/test.dart';
import 'package:openfeature_dart_server_sdk/open_feature_api.dart';
import 'package:openfeature_dart_server_sdk/feature_provider.dart';

void main() {
  late OpenFeatureAPI api;
  late InMemoryProvider testProvider;

  setUp(() {
    api = OpenFeatureAPI();
    testProvider = InMemoryProvider({
      'test-flag': true,
      'string-flag': 'test-value',
    });
    api.setProvider(testProvider);
  });

  tearDown(() {
    OpenFeatureAPI.resetInstance();
  });

  test('evaluates boolean flag correctly', () async {
    final client = api.getClient('test-client');
    final result = await client.getBooleanFlag('test-flag', defaultValue: false);
    expect(result, isTrue);
  });

  test('evaluates string flag correctly', () async {
    final client = api.getClient('test-client');
    final result = await client.getStringFlag('string-flag', defaultValue: 'default');
    expect(result, equals('test-value'));
  });
}

⭐️ Support the project

🤝 Contributing

Interested in contributing? Great, we'd love your help! To get started, take a look at the CONTRIBUTING guide.

Thanks to everyone that has already contributed

Pictures of the folks who have contributed to the project

Made with contrib.rocks.