Code Monkey home page Code Monkey logo

featuretoggle's Introduction

FeatureToggle

The Feature Toggle library for Android.

Overview

The FeatureToggle library allows you to configure features of an Android application at runtime using feature flags. Here are common usecases:

  • Trunk-Based Developement.
  • Safe release with a new implementation of the app’s critical part. If the new implementation causes a critical problem, developers can switch back to the old implementation using a feature flag.
  • A/B testing, when feature flags are used to switch between multiple feature implementations.

When you use FeatureToggle library, each dynamic feature in an Android application must be represented as a separate class or an interface with multiple implementations. Each dynamic feature has a Feature Flag with unique key and a FeatureFactory.

Feature Flag is Kotlin class that contains one or more fields that describe feature configuration.

Feature Flags can be loaded from multiple FeatureFlagDataSources. FeatureFlagDataSource has a priority value, which helps to decide which FeatureFlagDataSource should be used to apply a certain Feature Flag.

Feature Flags are stored in JSON format, and at runtime are represented as Koltin objects.

A FeatureFactory is responsible for creating feature objects, using the provided Feature Flag objects to decide how to create feature objects.

The FeatureToggle library automatically generates registries of current application feature flags and factories using annotation processors.

Quick Start

  1. Add a feature manager and compiler:
implementation("com.qiwi.featuretoggle:featuretoggle-feature-manager:0.1.3")
// To use kapt
kapt("com.qiwi.featuretoggle:featuretoggle-compiler:0.1.3")
// To use ksp
ksp("com.qiwi.featuretoggle:featuretoggle-compiler:0.1.3")
  1. Add a converter that will be used to convert feature flags from Json into Kotlin objects. Two converters are available: Jackson and Gson:
implementation("com.qiwi.featuretoggle:featuretoggle-converter-jackson:0.1.3")
//or
implementation("com.qiwi.featuretoggle:featuretoggle-converter-gson:0.1.3")
  1. Add a feature flag with an unique key and factory for every feature:
class SampleFeature {
    //code
}

@FeatureFlag("feature_key")
class SampleFeatureFlag(
    //fields
)

@Factory
class SampleFeatureFeatureFactory : FeatureFactory<SampleFeature, SampleFeatureFlag>() {

    override fun createFeature(flag: SampleFeatureFlag): SampleFeature {
        //construct feature using flag
    }

    override fun createDefault(): AndroidInfoFeature {
        //construct default feature implementation
    }
}
  1. Create an instance of FeatureManager using FeatureManager.Builder. Provide a converter, necessary data sources and generated registries. It is recommended to fetch feature flags immediately after creating an instance of FeatureManager:
val featureManager = FeatureManager.Builder(context)
    .converter(JacksonFeatureFlagConverter()) //or GsonFeatureFlagConverter()
    .logger(DebugLogger()) //optional logger
    .addDataSource(AssetsDataSource("feature_flags.json", context)) //also available additional data sources: FirebaseDataSource, AgConnectDataSource, RemoteDataSource
    .flagRegistry(FeatureFlagRegistryGenerated()) //set generated flag registry
    .factoryRegistry(FeatureFactoryRegistryGenerated()) //set generated factory registry
    .build()

featureManager.fetchFlags()
  1. Provide an instance of FeatureManager using your favourite DI framework, or you can use the FeatureToggle singleton:
implementation("com.qiwi.featuretoggle:featuretoggle-feature-manager-singleton:0.1.3")
FeatureToggle.setFeatureManager(...)

FeatureToggle.featureManager().getFeature(...)
  1. Get a feature from FeatureManager:
val feature = featureManager.getFeature<SampleFeature>()

It is recommended to wait for the feature flags to get loaded, for example on a splash screen:

class SplashScreenActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ...
        lifecycleScope.launchWhenCreated {
            runCatching {
                withTimeout(TIMEOUT_MILLIS) {
                    FeatureToggle.featureManager().awaitFullLoading()
                }
            }
            openMainActivity()
        }
    }

    ...
}

Assets DataSource

AssetsDataSource loads feature flags from a JSON file from assets folder. It is used to include default feature flag values into apk or app bundle. Default AssetsDataSource priority value is 1.

Cache

Feature flags when loaded from remote data sources are cached and used on the next fetch. You can also set a priority of cached feature flags in a FeatureManager.Builder:

FeatureManager.Builder(context)
    ...
    .cachedFlagsPriority(2)

Default cached flags priority value is 2.

Remote Config DataSource

FeatureToggle supports Firebase Remote Config and AppGallery Connect Remote Configuration.

Add a remote config value with its feature flag key for every feature. Remote config value must be stored as a Json string. Sample:

{
    "versionName": "12",
    "apiLevel": 31
}

Default remote config data sources priority value is 4.

FirebaseDataSource:

  1. Add Firebase to your Android project.
  2. If you need to use Google Analytics with Remote Config, add the analytics dependency:
implementation("com.google.firebase:firebase-analytics:${version}")
  1. Add FirebaseDataSource:
implementation("com.qiwi.featuretoggle:featuretoggle-datasource-firebase:0.1.3")
FeatureManager.Builder(context)
    ...
    .addDataSource(FirebaseDataSource())
  1. Add feature flags into the Engage > Remote Config section in the Firebase console. Sample:

For more details about Firebase Remote Config, look at the official docs.

AgConnectDataSource:

  1. Integrate the AppGallery Connect SDK.
  2. If you need to use HUAWEI Analytics with remote configuration, add the analytics dependency:
implementation("com.huawei.hms:hianalytics:${version}")
  1. Add AgConnectDataSource:
implementation("com.qiwi.featuretoggle:featuretoggle-datasource-agconnect:0.1.3")
FeatureManager.Builder(context)
    ...
    .addDataSource(AgConnectDataSource())
  1. Add feature flags into the Grow > Remote Configuration section in AppGallery Connect. Sample:

For more details about AppGallery Connect Remote Configuration, look at the official docs.

Remote DataSource

The FeatureToggle library also has RemoteDataSource that can download feature flags from JSON REST API using the OkHttp library. JSON response must be in the following format:

[
    {
      "feature": "android_info",
      "versionName": "12",
      "apiLevel": 31
    }
]

Usage:

implementation("com.qiwi.featuretoggle:featuretoggle-datasource-remote:0.1.3")
FeatureManager.Builder(context)
    ...
    .addDataSource(RemoteDataSource("url"))

Default RemoteDataSource priority value is 3.

Debug DataSource

If you need to update feature flags manually (for debug purposes), use DebugDataSource:

implementation("com.qiwi.featuretoggle:featuretoggle-datasource-debug:0.1.3")
val debugDataSource = DebugDataSource()

FeatureManager.Builder(context)
    ...
    .addDataSource(debugDataSource)

...

debugDataSource.updateFeatureFlagsFromJsonString(...)

Default DebugDataSource priority value is 100.

Custom DataSource

You can extend the FeatureToggle library with custom data source:

class CustomDataSource : FeatureFlagDataSource {

    override val sourceType: FeatureFlagsSourceType ...

    override val key: String ...

    override val priority: Int ...

    override fun getFlags(
        registry: FeatureFlagRegistry,
        converter: FeatureFlagConverter,
        logger: Logger
    ): Flow<Map<String, Any>> = flow {
        ...
    }

}

Testing

If you need to use FeatureManager in unit tests, use FakeFeatureManager. It doesn’t load flags from data sources – but uses mocked feature flags instead. Usage example:

testImplementation("com.qiwi.featuretoggle:featuretoggle-feature-manager-test:0.1.3")
val fakeFeatureManager = FakeFeatureManager.create(FeatureFlagRegistryGenerated(), FeatureFactoryRegistryGenerated())

...

fakeFeatureManager.overrideFlag(...)

R8/Proguard

FeatureToggle library modules have bundled proguard rules for its classes. However, you need to add a proguard rule for every feature flag class:

-keep class com.example.SampleFeatureFlag { *; }

License

MIT License

Copyright (c) 2021 QIWI

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

featuretoggle's People

Contributors

viska97 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.