diff --git a/openfeature/providers/kotlin-provider/.gitignore b/openfeature/providers/kotlin-provider/.gitignore new file mode 100644 index 00000000000..aa724b77071 --- /dev/null +++ b/openfeature/providers/kotlin-provider/.gitignore @@ -0,0 +1,15 @@ +*.iml +.gradle +/local.properties +/.idea/caches +/.idea/libraries +/.idea/modules.xml +/.idea/workspace.xml +/.idea/navEditor.xml +/.idea/assetWizardSettings.xml +.DS_Store +/build +/captures +.externalNativeBuild +.cxx +local.properties diff --git a/openfeature/providers/kotlin-provider/README.md b/openfeature/providers/kotlin-provider/README.md new file mode 100644 index 00000000000..30480007ba7 --- /dev/null +++ b/openfeature/providers/kotlin-provider/README.md @@ -0,0 +1,93 @@ +# GO Feature Flag Kotlin OpenFeature Provider for Android + +![Static Badge](https://img.shields.io/badge/status-experimental-red) + +This OpenFeature provider is a Kotlin implementation for Android to communicate with the GO Feature +Flag Server. + +The OpenFeature Kotlin is experimental, and the provider is also experimental. +We don't recommend using this in production yet. + +## About this provider + +[GO Feature Flag](https://gofeatureflag.org) provider allows you to connect to your GO Feature Flag +instance with the OpenFeature Kotlin SDK. + +This is a client provider made for Android, we do not recommend using it in a server environment. +If you want to use it in a server environment, you should use +the [`Java` provider](https://gofeatureflag.org/docs/openfeature_sdk/server_providers/openfeature_java). + +## What is GO Feature Flag? + +GO Feature Flag is a simple, complete and lightweight self-hosted feature flag solution 100% Open +Source. +Our focus is to avoid any complex infrastructure work to use GO Feature Flag. + +This is a complete feature flagging solution with the possibility to target only a group of users, +use any types of flags, store your configuration in various location and advanced rollout +functionality. You can also collect usage data of your flags and be notified of configuration +changes. + +## Install the provider + +TODO + +## How to use the provider? + +```kotlin +val evaluationContext = ImmutableContext( + targetingKey = "0a23d9a5-0a8f-42c9-9f5f-4de3afd6cf99", + attributes = mutableMapOf( + "region" to Value.String("us-east-1"), + "email" to Value.String("john.doe@gofeatureflag.org") + ) +) + +OpenFeatureAPI.setProvider( + GoFeatureFlagProvider( + options = GoFeatureFlagOptions( + endpoint = "http://localhost:1031" + ) + ), evaluationContext +) + +val client = OpenFeatureAPI.getClient("my-client") +if (client.getBooleanValue("my-flag", false)) { + println("my-flag is enabled") +} +OpenFeatureAPI.shutdown() +``` + +### Available options + +| Option name | Type | Default | Description | +|--------------------|--------|---------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| endpoint | String | | endpoint is the URL where your GO Feature Flag server is located. | +| timeout | Long | 10000 | (optional) timeout is the time in millisecond we wait for an answer from the server. | +| maxIdleConnections | Int | 1000 | (optional) maxIdleConnections is the maximum number of connexions in the connexion pool. | +| keepAliveDuration | Long | 7200000 | (optional) keepAliveDuration is the time in millisecond we keep the connexion open. | +| apiKey | String | | (optional) If GO Feature Flag is configured to authenticate the requests, you should provide an API Key to the provider. Please ask the administrator of the relay proxy to provide an API Key. | +| retryDelay | Long | 300 | (optional) delay in millisecond to wait before retrying to connect the websocket | + +### Reconnection + +If the connection to the GO Feature Flag instance fails, the provider will attempt to reconnect. + +### Event streaming + +Event streaming is not implemented yet in the GO Feature Flag provider. + +## Features status + +| Status | Feature | Description | +|--------|--------------------|--------------------------------------------------------------------------------------| +| ✅ | Flag evaluation | It is possible to evaluate all the type of flags | +| ✅ | Cache invalidation | Websocket mechanism is in place to refresh the cache in case of configuration change | +| ❌ | Logging | Not supported by the SDK | +| ❌ | Flag Metadata | Not supported by the SDK | +| ❌ | Event Streaming | Not implemented | +| ❌ | Unit test | Not implemented | + +Implemented: ✅ | In-progress: ⚠️ | Not implemented yet: ❌ + + diff --git a/openfeature/providers/kotlin-provider/build.gradle.kts b/openfeature/providers/kotlin-provider/build.gradle.kts new file mode 100644 index 00000000000..e52cca11b5d --- /dev/null +++ b/openfeature/providers/kotlin-provider/build.gradle.kts @@ -0,0 +1,14 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +plugins { + id("com.android.application") version "8.1.2" apply false + id("org.jetbrains.kotlin.android") version "1.9.0" apply false + id("com.android.library") version "8.1.2" apply false +} + +allprojects { + extra["groupId"] = "org.gofeatureflag.openfeature" + ext["version"] = "0.0.1" +} + +group = project.extra["groupId"].toString() +version = project.extra["version"].toString() \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/.gitignore b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/.gitignore new file mode 100644 index 00000000000..42afabfd2ab --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/build.gradle.kts b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/build.gradle.kts new file mode 100644 index 00000000000..a3c6520e08c --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/build.gradle.kts @@ -0,0 +1,44 @@ +plugins { + id("com.android.library") + id("org.jetbrains.kotlin.android") +} + +val releaseVersion = project.extra["version"].toString() + +android { + namespace = "org.gofeatureflag.openfeature" + compileSdk = 33 + + defaultConfig { + minSdk = 21 + version = releaseVersion + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + buildTypes { + release { + isMinifyEnabled = false + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + kotlinOptions { + jvmTarget = JavaVersion.VERSION_11.toString() + } +} + +dependencies { + implementation("dev.openfeature:kotlin-sdk:0.0.4") + implementation("com.squareup.okhttp3:okhttp:4.12.0") + implementation("com.google.code.gson:gson:2.8.9") + implementation("dev.gustavoavila:java-android-websocket-client:2.0.2") + testImplementation("junit:junit:4.13.2") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3") + testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") +} diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/consumer-rules.pro b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/consumer-rules.pro new file mode 100644 index 00000000000..e69de29bb2d diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/proguard-rules.pro b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/proguard-rules.pro new file mode 100644 index 00000000000..481bb434814 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/AndroidManifest.xml b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..a5918e68abc --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/AndroidManifest.xml @@ -0,0 +1,4 @@ + + + + \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagMetadata.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagMetadata.kt new file mode 100644 index 00000000000..f58c0eb00a3 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagMetadata.kt @@ -0,0 +1,9 @@ +package org.gofeatureflag.openfeature + +import dev.openfeature.sdk.ProviderMetadata +import java.security.Provider + +class GoFeatureFlagMetadata() : ProviderMetadata { + override val name: String + get() = "GoFeatureFlagProvider" +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagProvider.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagProvider.kt new file mode 100644 index 00000000000..66b44fed03d --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/GoFeatureFlagProvider.kt @@ -0,0 +1,271 @@ +package org.gofeatureflag.openfeature + +import com.google.gson.Gson +import dev.gustavoavila.websocketclient.WebSocketClient +import dev.openfeature.sdk.EvaluationContext +import dev.openfeature.sdk.FeatureProvider +import dev.openfeature.sdk.Hook +import dev.openfeature.sdk.OpenFeatureAPI.getEvaluationContext +import dev.openfeature.sdk.ProviderEvaluation +import dev.openfeature.sdk.ProviderMetadata +import dev.openfeature.sdk.Reason +import dev.openfeature.sdk.Value +import dev.openfeature.sdk.exceptions.ErrorCode +import dev.openfeature.sdk.exceptions.OpenFeatureError.FlagNotFoundError +import dev.openfeature.sdk.exceptions.OpenFeatureError.GeneralError +import okhttp3.ConnectionPool +import okhttp3.HttpUrl +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.OkHttpClient +import okhttp3.RequestBody.Companion.toRequestBody +import org.gofeatureflag.openfeature.bean.FlagState +import org.gofeatureflag.openfeature.bean.GoFeatureFlagOptions +import org.gofeatureflag.openfeature.bean.GoffRequest +import org.gofeatureflag.openfeature.bean.GoffResponse +import org.gofeatureflag.openfeature.bean.ProviderStatus +import org.gofeatureflag.openfeature.exception.InvalidEndpoint +import java.net.HttpURLConnection.HTTP_BAD_REQUEST +import java.net.HttpURLConnection.HTTP_UNAUTHORIZED +import java.net.URI +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.TimeUnit + + +class GoFeatureFlagProvider(private val options: GoFeatureFlagOptions) : FeatureProvider { + companion object { + private val gson = Gson() + } + + private var httpClient: OkHttpClient = OkHttpClient.Builder() + .connectTimeout(this.options.timeout, TimeUnit.MILLISECONDS) + .readTimeout(this.options.timeout, TimeUnit.MILLISECONDS) + .callTimeout(this.options.timeout, TimeUnit.MILLISECONDS) + .writeTimeout(this.options.timeout, TimeUnit.MILLISECONDS) + .connectionPool( + ConnectionPool( + this.options.maxIdleConnections, + this.options.keepAliveDuration, + TimeUnit.MILLISECONDS + ) + ) + .build() + private var parsedEndpoint: HttpUrl? = options.endpoint.toHttpUrlOrNull() + private var flags: ConcurrentHashMap = ConcurrentHashMap() + private var status: ProviderStatus = ProviderStatus.NOT_READY + private var goffWebsocketClient: WebSocketClient? = null + + init { + if (this.parsedEndpoint == null) { + throw InvalidEndpoint() + } + } + + override val hooks: List> + get() = listOf() + + override val metadata: ProviderMetadata + get() = GoFeatureFlagMetadata() + + override fun getBooleanEvaluation( + key: String, + defaultValue: Boolean, + context: EvaluationContext? + ): ProviderEvaluation { + return this.evaluate(key, listOf("Boolean"), defaultValue) + } + + override fun getDoubleEvaluation( + key: String, + defaultValue: Double, + context: EvaluationContext? + ): ProviderEvaluation { + return this.evaluate(key, listOf("Double"), defaultValue) + } + + override fun getIntegerEvaluation( + key: String, + defaultValue: Int, + context: EvaluationContext? + ): ProviderEvaluation { + return this.evaluate(key, listOf("Int"), defaultValue) + } + + override fun getObjectEvaluation( + key: String, + defaultValue: Value, + context: EvaluationContext? + ): ProviderEvaluation { + return this.evaluate(key, listOf("LinkedTreeMap", "ArrayList"), defaultValue) + } + + override fun getStringEvaluation( + key: String, + defaultValue: String, + context: EvaluationContext? + ): ProviderEvaluation { + return this.evaluate(key, listOf("String"), defaultValue) + } + + override fun initialize(initialContext: EvaluationContext?) { + try { + fetchAllFlags(initialContext) + this.goffWebsocketClient = + object : WebSocketClient(buildWebsocketURI(this.options)) { + init { + this.enableAutomaticReconnection(options.retryDelay) + this.setReadTimeout(options.timeout.toInt()) + this.setConnectTimeout(options.timeout.toInt()) + } + + override fun onOpen() { + status = ProviderStatus.READY + } + + override fun onTextReceived(message: String?) { + try { + status = ProviderStatus.STALE + fetchAllFlags(getEvaluationContext()) + status = ProviderStatus.READY + } catch (e: Exception) { + status = ProviderStatus.ERROR + } + } + + override fun onException(e: java.lang.Exception?) { + status = ProviderStatus.ERROR + } + + override fun onBinaryReceived(data: ByteArray?) {} + override fun onPingReceived(data: ByteArray?) {} + override fun onPongReceived(data: ByteArray?) {} + override fun onCloseReceived(reason: Int, description: String?) {} + } + this.goffWebsocketClient?.connect() + } catch (e: Exception) { + this.status = ProviderStatus.ERROR + } + } + + override fun onContextSet(oldContext: EvaluationContext?, newContext: EvaluationContext) { + this.status = ProviderStatus.STALE + try { + fetchAllFlags(newContext) + this.status = ProviderStatus.READY + } catch (e: Exception) { + this.status = ProviderStatus.ERROR + } + } + + override fun shutdown() { + this.goffWebsocketClient?.close(0, 1000, "stop provider") + } + + fun status(): ProviderStatus { + return this.status + } + + /** + * Evaluate is the function call by all types to fetch the flag from the cache + * and return the ProviderEvaluation object. + * + * @param flagKey the key of the flag to fetch + * @param expectedTypes the types of the flag to fetch + * @param defaultValue the default value to return if there is an error + * + * @return ProviderEvaluation the evaluation of the flag + */ + private fun evaluate( + flagKey: String, + expectedTypes: List, + defaultValue: T + ): ProviderEvaluation { + if (this.status == ProviderStatus.NOT_READY) { + return ProviderEvaluation( + value = defaultValue, + variant = null, + reason = Reason.ERROR.toString(), + errorCode = ErrorCode.PROVIDER_NOT_READY + ) + } + + val flag = this.flags[flagKey] ?: throw FlagNotFoundError(flagKey) + + if (!expectedTypes.contains(flag.value::class.simpleName)) { + // TODO: throw here when the SDK with this PR https://github.com/open-feature/kotlin-sdk/pull/64/files is released + // throw TypeMismatchError() + return ProviderEvaluation( + value = defaultValue, + variant = flag.variationType, + reason = Reason.ERROR.toString(), + errorCode = ErrorCode.TYPE_MISMATCH + ) + } + + val errorCode: ErrorCode? = try { + ErrorCode.valueOf(flag.errorCode) + } catch (e: IllegalArgumentException) { + null + } + + return ProviderEvaluation( + value = flag.value as T, + variant = flag.variationType, + reason = flag.reason, + errorCode = errorCode + ) + } + + /** fetchAllFlags is the function called to fetch all flags from the relay proxy + * and store them in the cache. + * + * @param context the context to use to fetch the flags + */ + private fun fetchAllFlags(context: EvaluationContext?) { + if (context == null) { + return + } + val goffctx = GoffRequest(context) + val urlBuilder = parsedEndpoint!!.newBuilder() + .addEncodedPathSegment("v1") + .addEncodedPathSegment("allflags") + + if (this.options.apiKey != null && this.options.apiKey.trim().isNotEmpty()) { + urlBuilder.addQueryParameter("apiKey", this.options.apiKey) + } + + // call an API endpoint to fetch all flags + val mediaType = "application/json".toMediaTypeOrNull() + val requestBody = gson.toJson(goffctx).toRequestBody(mediaType) + val reqBuilder = okhttp3.Request.Builder() + .url(urlBuilder.build()) + .post(requestBody) + + httpClient.newCall(reqBuilder.build()).execute().use { response -> + if (response.code == HTTP_UNAUTHORIZED) { + throw GeneralError("invalid token used to contact GO Feature Flag relay proxy instance") + } + if (response.code >= HTTP_BAD_REQUEST) { + throw GeneralError("impossible to contact GO Feature Flag relay proxy instance") + } + + val t = response.body?.string() + val parsedResp = gson.fromJson(t, GoffResponse::class.java) + this.flags = ConcurrentHashMap(parsedResp.flags) + } + } + + /** buildWebsocketURI is the function called to build the websocket URI + * to connect to the relay proxy. + * + * @param options the options to use to build the URI + * @return URI the URI to connect to + */ + private fun buildWebsocketURI(options: GoFeatureFlagOptions): URI { + // take the endpoint and replace http:// or https:// by ws:// or wss:// + val wsEndpoint = options.endpoint + .replaceFirst("http", "ws") + .replaceFirst("https", "wss") + return URI("$wsEndpoint/ws/v1/flag/change") + } +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/FlagState.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/FlagState.kt new file mode 100644 index 00000000000..06315ef8941 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/FlagState.kt @@ -0,0 +1,12 @@ +package org.gofeatureflag.openfeature.bean + +data class FlagState( + val value: Any, + val timestamp: Long, + val variationType: String, + val trackEvents: Boolean, + val failed: Boolean, + val errorCode: String, + val reason: String, + val metadata: Map? +) \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoFeatureFlagOptions.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoFeatureFlagOptions.kt new file mode 100644 index 00000000000..9318e1bf0d7 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoFeatureFlagOptions.kt @@ -0,0 +1,42 @@ +package org.gofeatureflag.openfeature.bean + +data class GoFeatureFlagOptions( + /** + * (mandatory) endpoint contains the DNS of your GO Feature Flag relay proxy + * example: https://mydomain.com/gofeatureflagproxy/ + */ + val endpoint: String, + + /** + * (optional) timeout in millisecond we are waiting when calling the + * go-feature-flag relay proxy API. + * Default: 10000 ms + */ + val timeout: Long = 10000, + + /** + * (optional) maxIdleConnections is the maximum number of connexions in the connexion pool. + * Default: 1000 + */ + val maxIdleConnections: Int = 1000, + + /** + * (optional) keepAliveDuration is the time in millisecond we keep the connexion open. + * Default: 7200000 (2 hours) + */ + val keepAliveDuration: Long = 7200000, + + /** + * (optional) apiKey, if the relay proxy is configured to authenticate the requests, you should provide + * an API Key to the provider. + * Please ask the administrator of the relay proxy to provide an API Key. + * (This feature is available only if you are using GO Feature Flag relay proxy v1.7.0 or above) + * Default: null + */ + val apiKey: String? = null, + + /** (optional) retryDelay is the time in millisecond we wait before retrying to connect to the relay proxy. + * Default: 1000 ms + */ + val retryDelay: Long = 1000, +) diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffEvaluationContext.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffEvaluationContext.kt new file mode 100644 index 00000000000..0f2e15735d8 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffEvaluationContext.kt @@ -0,0 +1,4 @@ +package org.gofeatureflag.openfeature.bean + +data class GoffEvaluationContext(val key: String, val custom: Map) { +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffRequest.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffRequest.kt new file mode 100644 index 00000000000..cbc88a96584 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffRequest.kt @@ -0,0 +1,8 @@ +package org.gofeatureflag.openfeature.bean + +import dev.openfeature.sdk.EvaluationContext + +data class GoffRequest(@Transient val ctx: EvaluationContext) { + private val evaluationContext: GoffEvaluationContext = + GoffEvaluationContext(ctx.getTargetingKey(), ctx.asObjectMap()) +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffResponse.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffResponse.kt new file mode 100644 index 00000000000..ff4a0add1b8 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/GoffResponse.kt @@ -0,0 +1,7 @@ +package org.gofeatureflag.openfeature.bean + +data class GoffResponse( + val flags: Map, + val valid: Boolean +) + diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/ProviderStatus.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/ProviderStatus.kt new file mode 100644 index 00000000000..140c721f8f8 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/bean/ProviderStatus.kt @@ -0,0 +1,23 @@ +package org.gofeatureflag.openfeature.bean + +enum class ProviderStatus { + /** + * The provider has not been initialized and cannot yet evaluate flags. + */ + NOT_READY, + + /** + * The provider is ready to resolve flags. + */ + READY, + + /** + * The provider is in an error state and unable to evaluate flags. + */ + ERROR, + + /** + * The provider's cached state is no longer valid and may not be up-to-date with the source of truth. + */ + STALE +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/GoFeatureFlagException.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/GoFeatureFlagException.kt new file mode 100644 index 00000000000..7d6d9a9adf9 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/GoFeatureFlagException.kt @@ -0,0 +1,4 @@ +package org.gofeatureflag.openfeature.exception + +open class GoFeatureFlagException(): Exception() { +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/InvalidEndpoint.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/InvalidEndpoint.kt new file mode 100644 index 00000000000..bf836fcc8db --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/InvalidEndpoint.kt @@ -0,0 +1,4 @@ +package org.gofeatureflag.openfeature.exception + +class InvalidEndpoint(): InvalidOptions() { +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/InvalidOptions.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/InvalidOptions.kt new file mode 100644 index 00000000000..d9e7fc0d6a7 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/main/java/org/gofeatureflag/openfeature/exception/InvalidOptions.kt @@ -0,0 +1,4 @@ +package org.gofeatureflag.openfeature.exception + +open class InvalidOptions(): GoFeatureFlagException() { +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/test/java/org/gofeatureflag/openfeature/ExampleUnitTest.kt b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/test/java/org/gofeatureflag/openfeature/ExampleUnitTest.kt new file mode 100644 index 00000000000..341ec6f69cf --- /dev/null +++ b/openfeature/providers/kotlin-provider/gofeatureflag-kotlin-provider/src/test/java/org/gofeatureflag/openfeature/ExampleUnitTest.kt @@ -0,0 +1,52 @@ +package org.gofeatureflag.openfeature + +import dev.openfeature.sdk.ImmutableContext +import dev.openfeature.sdk.OpenFeatureAPI +import dev.openfeature.sdk.Value +import org.gofeatureflag.openfeature.bean.GoFeatureFlagOptions +import org.junit.Assert.assertEquals +import org.junit.Test + + +/** + * Example local unit test, which will execute on the development machine (host). + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +class ExampleUnitTest { + @Test + fun addition_isCorrect() { + assertEquals(4, 2 + 2) + } + + @Test + fun xxx() { + val evaluationContext = ImmutableContext( + targetingKey = "0a23d9a5-0a8f-42c9-9f5f-4de3afd6cf99", + attributes = mutableMapOf( + "region" to Value.String("us-east-1"), +// "email" to Value.String("john.doe@gofeatureflag.org") + ) + ) + OpenFeatureAPI.setProvider( + GoFeatureFlagProvider( + options = GoFeatureFlagOptions( + endpoint = "http://localhost:1031" + ) + ), evaluationContext + ) + + OpenFeatureAPI.setEvaluationContext(evaluationContext) + val cli = OpenFeatureAPI.getClient("cli") + println(cli.getObjectDetails("object_key", Value.Structure(mapOf()))) + if (cli.getBooleanValue("my-flag", false)) { + println("my-flag is true") + } + + OpenFeatureAPI.shutdown() + + Thread.sleep(90000) + println(cli.getObjectDetails("object_key", Value.Structure(mapOf()))) + + } +} \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gradle.properties b/openfeature/providers/kotlin-provider/gradle.properties new file mode 100644 index 00000000000..3c5031eb7d6 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app's APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Enables namespacing of each library's R class so that its R class includes only the +# resources declared in the library itself and none from the library's dependencies, +# thereby reducing the size of the R class for that library +android.nonTransitiveRClass=true \ No newline at end of file diff --git a/openfeature/providers/kotlin-provider/gradle/wrapper/gradle-wrapper.jar b/openfeature/providers/kotlin-provider/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..e708b1c023e Binary files /dev/null and b/openfeature/providers/kotlin-provider/gradle/wrapper/gradle-wrapper.jar differ diff --git a/openfeature/providers/kotlin-provider/gradle/wrapper/gradle-wrapper.properties b/openfeature/providers/kotlin-provider/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..95bf7ee6414 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Fri Nov 03 22:36:18 CET 2023 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/openfeature/providers/kotlin-provider/gradlew b/openfeature/providers/kotlin-provider/gradlew new file mode 100755 index 00000000000..4f906e0c811 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gradlew @@ -0,0 +1,185 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=`expr $i + 1` + done + case $i in + 0) set -- ;; + 1) set -- "$args0" ;; + 2) set -- "$args0" "$args1" ;; + 3) set -- "$args0" "$args1" "$args2" ;; + 4) set -- "$args0" "$args1" "$args2" "$args3" ;; + 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=`save "$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +exec "$JAVACMD" "$@" diff --git a/openfeature/providers/kotlin-provider/gradlew.bat b/openfeature/providers/kotlin-provider/gradlew.bat new file mode 100644 index 00000000000..ac1b06f9382 --- /dev/null +++ b/openfeature/providers/kotlin-provider/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/openfeature/providers/kotlin-provider/settings.gradle.kts b/openfeature/providers/kotlin-provider/settings.gradle.kts new file mode 100644 index 00000000000..8da0565dac2 --- /dev/null +++ b/openfeature/providers/kotlin-provider/settings.gradle.kts @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} + +rootProject.name = "go-feature-flag-kotlin-provider" +include(":gofeatureflag-kotlin-provider")