diff --git a/.github/workflows/lint.yml b/.github/workflows/lint-sdks.yml similarity index 93% rename from .github/workflows/lint.yml rename to .github/workflows/lint-sdks.yml index b4239ba7..b3929def 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint-sdks.yml @@ -1,4 +1,4 @@ -name: SDKs +name: Lint SDKs on: push: branches: @@ -12,7 +12,7 @@ jobs: steps: - name: Checkout Sources uses: actions/checkout@v4 - + - name: Setup Python uses: actions/setup-python@v4 with: @@ -22,20 +22,20 @@ jobs: uses: snok/install-poetry@v1 with: version: 1.7.0 - + - name: Lint Python source working-directory: flipt-client-python run: | poetry install poetry run black --check . - + lint-typescript: name: Lint Typescript runs-on: ubuntu-latest steps: - name: Checkout Sources uses: actions/checkout@v4 - + - name: Install Node uses: actions/setup-node@v4 with: @@ -45,4 +45,4 @@ jobs: working-directory: flipt-client-node run: | npm ci - npm run prettier-check + npm run lint diff --git a/.github/workflows/test.yml b/.github/workflows/test-sdks.yml similarity index 86% rename from .github/workflows/test.yml rename to .github/workflows/test-sdks.yml index c163beee..4bfb0153 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test-sdks.yml @@ -1,4 +1,4 @@ -name: Tests +name: Test SDKs on: push: branches: @@ -7,7 +7,7 @@ on: jobs: test: - name: Dagger ITs + name: Integration Tests runs-on: ubuntu-latest steps: - name: Checkout Sources @@ -18,12 +18,12 @@ jobs: go-version: "1.21.3" check-latest: true cache: true - + - name: Install Dagger run: | cd /usr/local curl -L https://dl.dagger.io/dagger/install.sh | DAGGER_VERSION=0.9.3 sh - - - name: Run ITs + + - name: Run Integration Tests run: | dagger run go run ./build diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md new file mode 100644 index 00000000..6d1b7554 --- /dev/null +++ b/ARCHITECTURE.md @@ -0,0 +1,11 @@ +# Architecture + +The `flipt-engine` is a Rust library responsible for evaluating context and returning the results of the evaluation. The client engine polls for evaluation state from the Flipt server and uses this state to determine the results of the evaluation. The client engine is designed to be embedded in the native language client SDKs. The native language client SDKs will send context to the client engine via [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface) and receive the results of the evaluation from engine. + +This design allows for the client evaluation logic to be written once in a memory safe language and embedded in the native language client SDKs. This design also allows for the client engine to be updated independently of the native language client SDKs. + +You can refer to the architecture diagram below: + +
+ +
diff --git a/README.md b/README.md index 3030e88b..52b4d80a 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,18 @@ # Client SDKs -The intention of this repo is to centralize the core evaluation logic for Flipt's feature flags, and have thin multi-language wrappers around that logic. +![Status: Experimental](https://img.shields.io/badge/status-experimental-yellow) -The evaluation logic is written in Rust and can be found in the `flipt-engine` directory. The language clients that wrap the engine can be found in the `flipt-client-{language}` directories. +This repository centralizes the client-side SDKs for [Flipt](https://github.com/flipt-io/flipt). -The Rust core is compiled down into a dynamically-linked library and the language clients are able to access that logic through [FFI (foreign function interface)](https://levelup.gitconnected.com/what-is-ffi-foreign-function-interface-an-intuitive-explanation-7327444e347a). +These client-side SDKs are responsible for evaluating context and returning the results of the evaluation. They enable developers to easily integrate Flipt into their applications without relying on server-side SDKs. -You can refer to the architecture diagram below: +## Architecture - +The client SDKs are designed to be embedded in end-user applications. + +The evaluation logic is written in Rust and can be found in the `flipt-engine` directory. The language clients that are used in end-user applications wrap the engine can be found in the `flipt-client-{language}` directories. + +See [ARCHITECTURE.md](./ARCHITECTURE.md). ## Language Support diff --git a/build/README.md b/build/README.md index 12a09c3a..77b51c64 100644 --- a/build/README.md +++ b/build/README.md @@ -1,14 +1,16 @@ -## Integration Testing +# Integration Tests -The different languages clients should all have an integration test suite that is dependent on a dynamic library being present somewhere and a running instance of Flipt. In the `build/` directory we will use [Dagger](https://dagger.io/) to orchestrate setting up the dependencies for running the test suites for the different languages. +The different languages clients should all have an integration test suite that is dependent on the dynamic library being present somewhere and a running instance of Flipt. -### Requirements +In the `build/` directory we will use [Dagger](https://dagger.io/) to orchestrate setting up the dependencies for running the test suites for the different languages. + +## Requirements Make sure you have `dagger` installed. This module is pinned to `v0.9.3` currently. Here are the [installation instructions](https://docs.dagger.io/quickstart/729236/cli) for `dagger`. -### How to run tests? +## Running Tests From the root of this repository you can run: diff --git a/build/main.go b/build/main.go index 5b3f8cd9..4c047e97 100644 --- a/build/main.go +++ b/build/main.go @@ -5,6 +5,7 @@ import ( "flag" "fmt" "log" + "maps" "os" "strings" @@ -18,6 +19,7 @@ var ( "python": pythonTests, "go": goTests, "node": nodeTests, + "ruby": rubyTests, } sema = make(chan struct{}, len(languageToFn)) ) @@ -37,24 +39,22 @@ func main() { } func run() error { - var languagesTestsMap = map[string]integrationTestFn{ - "python": pythonTests, - "go": goTests, - "node": nodeTests, - } + var tests = make(map[string]integrationTestFn, len(languageToFn)) + + maps.Copy(tests, languageToFn) if languages != "" { l := strings.Split(languages, ",") - tlm := make(map[string]integrationTestFn, len(l)) + subset := make(map[string]integrationTestFn, len(l)) for _, language := range l { - if testFn, ok := languageToFn[language]; !ok { + testFn, ok := languageToFn[language] + if !ok { return fmt.Errorf("language %s is not supported", language) - } else { - tlm[language] = testFn } + subset[language] = testFn } - languagesTestsMap = tlm + tests = subset } ctx := context.Background() @@ -73,7 +73,7 @@ func run() error { var g errgroup.Group - for _, testFn := range languagesTestsMap { + for _, testFn := range tests { err := testFn(ctx, client, flipt, dynamicLibrary, headerFile, dir) if err != nil { return err @@ -182,3 +182,18 @@ func nodeTests(ctx context.Context, client *dagger.Client, flipt *dagger.Contain return err } + +// rubyTests runs the ruby integration test suite against a container running Flipt. +func rubyTests(ctx context.Context, client *dagger.Client, flipt *dagger.Container, dynamicLibrary *dagger.File, _ *dagger.File, hostDirectory *dagger.Directory) error { + _, err := client.Container().From("ruby:3.1-bookworm"). + WithWorkdir("/app"). + WithDirectory("/app", hostDirectory.Directory("flipt-client-ruby")). + WithFile("/app/lib/ext/libfliptengine.so", dynamicLibrary). + WithServiceBinding("flipt", flipt.WithExec(nil).AsService()). + WithEnvVariable("FLIPT_URL", "http://flipt:8080"). + WithExec([]string{"bundle", "install"}). + WithExec([]string{"bundle", "exec", "rspec"}). + Sync(ctx) + + return err +} diff --git a/flipt-client-go/README.md b/flipt-client-go/README.md index dd2fca17..64b5081a 100644 --- a/flipt-client-go/README.md +++ b/flipt-client-go/README.md @@ -1,6 +1,6 @@ # Flipt Client Go -The `flipt-client-go` directory contains the Golang source code for a Flipt evaluation client using FFI to make calls to a core built in Rust. +The `flipt-client-go` directory contains the Go source code for a Flipt evaluation client. ## Instructions @@ -10,7 +10,7 @@ To use this client, you can run the following command from the root of the repos cargo build --release ``` -This should generate a `target/` directory in the root of this repository, which contains the dynamic linking library built for your platform. This dynamic library will contain the functionality necessary for the Golang client to make FFI calls. +This should generate a `target/` directory in the root of this repository, which contains the dynamic linking library built for your platform. This dynamic library will contain the functionality necessary for the Go client to make FFI calls. You can import the module that contains the evaluation client: `go.flipt.io/flipt/flipt-client-go` and build your Go project with the `CGO_LDFLAGS` environment variable set: @@ -26,44 +26,42 @@ The `path/to/lib` will be the path to the dynamic library which will have the fo You can then use the client like so: -```golang +```go package main import ( - "context" - "fmt" - "log" + "context" + "fmt" + "log" - evaluation "go.flipt.io/flipt/flipt-client-go" + evaluation "go.flipt.io/flipt/flipt-client-go" ) func main() { - // The NewClient() accepts options which are the following: - // evaluation.WithNamespace(string): configures which namespace you will be making evaluations on - // evaluation.WithURL(string): configures which upstream Flipt data should be fetched from - // evaluation.WithUpdateInterval(int): configures how often data should be fetched from the upstream - evaluationClient, err := evaluation.NewClient() - if err != nil { - log.Fatal(err) - } - defer evaluationClient.Close() - - variantResult, err := evaluationClient.Variant(context.Background(), "flag1", "someentity", map[string]string{ - "fizz": "buzz", - }) - if err != nil { - log.Fatal(err) - } - - fmt.Println(*variantResult.Result) + // The NewClient() accepts options which are the following: + // evaluation.WithNamespace(string): configures which namespace you will be making evaluations on + // evaluation.WithURL(string): configures which upstream Flipt data should be fetched from + // evaluation.WithUpdateInterval(int): configures how often data should be fetched from the upstream + evaluationClient, err := evaluation.NewClient() + if err != nil { + log.Fatal(err) + } + defer evaluationClient.Close() + + variantResult, err := evaluationClient.Variant(context.Background(), "flag1", "someentity", map[string]string{ + "fizz": "buzz", + }) + if err != nil { + log.Fatal(err) + } + + fmt.Println(*variantResult.Result) } ``` ## Memory Management -The engine that is allocated on the Rust side to compute evaluations for flag state will not be properly deallocated unless you call the `Close()` method on a `Client` instance, please be sure to do that to avoid leaking memory. - -ie: +The engine that is allocated on the Rust side to compute evaluations for flag state will not be properly deallocated unless you call the `Close()` method on a `Client` instance. Please be sure to do this to avoid leaking memory. ```go defer evaluationClient.Close() diff --git a/flipt-client-node/README.md b/flipt-client-node/README.md index c172cb22..61504e41 100644 --- a/flipt-client-node/README.md +++ b/flipt-client-node/README.md @@ -1,6 +1,6 @@ # Flipt Client Node -The `flipt-client-node` directory contains the TypeScript source code for a Flipt evaluation client using FFI to make calls to a core built in Rust. +The `flipt-client-node` directory contains the TypeScript source code for a Flipt evaluation client. ## Instructions @@ -41,4 +41,10 @@ console.log(variant); ## Memory Management -Since TypeScript/JavaScript is a garbage collected language there is no concept of "freeing" memory. We had to allocated memory for the engine through the `initialize_engine` FFI call, and with that being said please make sure to call the `freeEngine` method on the `FliptEvaluationClient` class once you are done using it. +Since TypeScript/JavaScript is a garbage collected language there is no concept of "freeing" memory. We have to allocate memory for the engine through the `initialize_engine` FFI call. + +Make sure to call the `freeEngine` method on the `FliptEvaluationClient` class once you are done using it. + +```typescript +fliptEvaluationClient.freeEngine(); +``` diff --git a/flipt-client-node/package.json b/flipt-client-node/package.json index 6a148f6b..8bc6973e 100644 --- a/flipt-client-node/package.json +++ b/flipt-client-node/package.json @@ -1,14 +1,14 @@ { "name": "flipt-client-node", "version": "0.0.1", - "description": "Flipt Node Client for evaluations through FFI", + "description": "Flipt Node Client for client-side evaluation", "main": "dist/index.js", "types": "dist/index.d.ts", "author": "", - "license": "ISC", + "license": "MIT", "scripts": { - "prettier-format": "prettier --config .prettierrc 'src/**/*.ts' --write", - "prettier-check": "prettier --check src/**/*.ts", + "fmt": "prettier --config .prettierrc 'src/**/*.ts' --write", + "lint": "prettier --check src/**/*.ts", "test": "jest" }, "dependencies": { diff --git a/flipt-client-python/README.md b/flipt-client-python/README.md index 898ba76d..eb48bd21 100644 --- a/flipt-client-python/README.md +++ b/flipt-client-python/README.md @@ -1,6 +1,6 @@ # Flipt Client Python -The `flipt-client-python` directory contains the Python source code for a Flipt evaluation client using FFI to make calls to a core built in Rust. +The `flipt-client-python` directory contains the Python source code for a Flipt evaluation client. ## Instructions @@ -10,7 +10,7 @@ To use this client, you can run the following command from the root of the repos cargo build --release ``` -This should generate a `target/` directory in the root of this repository, which contains the dynamic linking library built for your platform. This dynamic library will contain the functionality necessary for the Python client to make FFI calls. You'll need to set the `FLIPT_ENGINE_LIB_PATH` environment variable depending on your platform: +This should generate a `target/` directory in the root of this repository which contains the dynamic linking library built for your platform. This dynamic library will contain the functionality necessary for the Python client to make FFI calls. You'll need to set the `FLIPT_ENGINE_LIB_PATH` environment variable depending on your platform: - **Linux**: `{REPO_ROOT}/target/release/libfliptengine.so` - **Windows**: `{REPO_ROOT}/target/release/libfliptengine.dll` diff --git a/flipt-client-ruby/.rspec b/flipt-client-ruby/.rspec new file mode 100644 index 00000000..c99d2e73 --- /dev/null +++ b/flipt-client-ruby/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/flipt-client-ruby/.rubocop.yml b/flipt-client-ruby/.rubocop.yml new file mode 100644 index 00000000..cc32da4b --- /dev/null +++ b/flipt-client-ruby/.rubocop.yml @@ -0,0 +1 @@ +inherit_from: .rubocop_todo.yml diff --git a/flipt-client-ruby/.rubocop_todo.yml b/flipt-client-ruby/.rubocop_todo.yml new file mode 100644 index 00000000..a3fb1ad3 --- /dev/null +++ b/flipt-client-ruby/.rubocop_todo.yml @@ -0,0 +1,33 @@ +# This configuration was generated by +# `rubocop --auto-gen-config` +# on 2023-12-03 00:21:30 UTC using RuboCop version 1.58.0. +# The point is for the user to remove these configuration records +# one by one as the offenses are removed from the code base. +# Note that changes in the inspected code, or installation of new +# versions of RuboCop, may require this file to be generated again. + +# Offense count: 1 +# Configuration parameters: Severity, Include. +# Include: **/*.gemspec +Gemspec/RequiredRubyVersion: + Exclude: + - 'flipt-client-ruby.gemspec' + +# Offense count: 1 +Lint/ShadowingOuterLocalVariable: + Exclude: + - 'lib/evaluation.rb' + +# Offense count: 1 +# Configuration parameters: CountComments, CountAsOne, AllowedMethods, AllowedPatterns. +# AllowedMethods: refine +Metrics/BlockLength: + Max: 35 + +# Offense count: 1 +# Configuration parameters: AllowedConstants. +Style/Documentation: + Exclude: + - 'spec/**/*' + - 'test/**/*' + - 'lib/evaluation.rb' diff --git a/flipt-client-ruby/Gemfile b/flipt-client-ruby/Gemfile index 9f7c8096..fe7b7def 100644 --- a/flipt-client-ruby/Gemfile +++ b/flipt-client-ruby/Gemfile @@ -1,11 +1,15 @@ -source "https://rubygems.org" +# frozen_string_literal: true + +source 'https://rubygems.org' # Specify your gem's dependencies in flipt-client-ruby.gemspec gemspec -gem "rake", "~> 12.0" -gem "ffi", "~> 1.16" +gem 'ffi', '~> 1.16' +gem 'rake', '~> 12.0' group :development do - gem "bundler", "~> 2.0" + gem 'bundler', '~> 2.0' + gem 'rspec', '~> 3.0' + gem 'rubocop', require: false end diff --git a/flipt-client-ruby/Gemfile.lock b/flipt-client-ruby/Gemfile.lock index 683d00d3..5b39a96c 100644 --- a/flipt-client-ruby/Gemfile.lock +++ b/flipt-client-ruby/Gemfile.lock @@ -6,9 +6,20 @@ PATH GEM remote: https://rubygems.org/ specs: + ast (2.4.2) diff-lcs (1.5.0) ffi (1.16.3) + json (2.7.0) + language_server-protocol (3.17.0.3) + parallel (1.23.0) + parser (3.2.2.4) + ast (~> 2.4.1) + racc + racc (1.7.3) + rainbow (3.1.1) rake (12.3.3) + regexp_parser (2.8.2) + rexml (3.2.6) rspec (3.12.0) rspec-core (~> 3.12.0) rspec-expectations (~> 3.12.0) @@ -22,6 +33,21 @@ GEM diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.12.0) rspec-support (3.12.1) + rubocop (1.58.0) + json (~> 2.3) + language_server-protocol (>= 3.17.0) + parallel (~> 1.10) + parser (>= 3.2.2.4) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 1.8, < 3.0) + rexml (>= 3.2.5, < 4.0) + rubocop-ast (>= 1.30.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 3.0) + rubocop-ast (1.30.0) + parser (>= 3.2.1.0) + ruby-progressbar (1.13.0) + unicode-display_width (2.5.0) PLATFORMS ruby @@ -32,6 +58,7 @@ DEPENDENCIES flipt_client! rake (~> 12.0) rspec (~> 3.0) + rubocop BUNDLED WITH 2.1.4 diff --git a/flipt-client-ruby/Makefile b/flipt-client-ruby/Makefile deleted file mode 100644 index e69de29b..00000000 diff --git a/flipt-client-ruby/README.md b/flipt-client-ruby/README.md index 63c94f0a..870e3346 100644 --- a/flipt-client-ruby/README.md +++ b/flipt-client-ruby/README.md @@ -1,6 +1,6 @@ # Flipt Client Ruby -The `flipt-client-ruby` directory contains the Ruby source code for a Flipt evaluation client using FFI to make calls to a core built in Rust. +The `flipt-client-ruby` directory contains the Ruby source code for a Flipt evaluation client. ## Instructions @@ -37,17 +37,3 @@ resp = client.variant({ flag_key: 'buzz', entity_id: 'someentity', context: { fi puts resp ``` - -## Testing - -### Preqrequisites - -- Ruby -- Bundler -- Run `make ruby` from the root of the repository to build the Rust library and copy the necessary files over. - -To run the tests for this client, you can run the following command from this directory: - -```bash -rspec . -``` diff --git a/flipt-client-ruby/Rakefile b/flipt-client-ruby/Rakefile index 43022f71..7f6fc4ab 100644 --- a/flipt-client-ruby/Rakefile +++ b/flipt-client-ruby/Rakefile @@ -1,2 +1,4 @@ -require "bundler/gem_tasks" -task :default => :spec +# frozen_string_literal: true + +require 'bundler/gem_tasks' +task default: :spec diff --git a/flipt-client-ruby/flipt-client-ruby.gemspec b/flipt-client-ruby/flipt-client-ruby.gemspec index caeb7531..6f4fbcf6 100644 --- a/flipt-client-ruby/flipt-client-ruby.gemspec +++ b/flipt-client-ruby/flipt-client-ruby.gemspec @@ -1,25 +1,27 @@ +# frozen_string_literal: true + require_relative 'lib/client/version' Gem::Specification.new do |spec| - spec.name = "flipt_client" + spec.name = 'flipt_client' spec.version = Flipt::Client::VERSION - spec.authors = ["Flipt Devs"] - spec.email = ["dev@flipt.io"] + spec.authors = ['Flipt Devs'] + spec.email = ['dev@flipt.io'] - spec.summary = "Ruby Client SDK for Flipt" - spec.description = "..." - spec.homepage = "https://www.flipt.io" - spec.license = "MIT" - spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0") + spec.summary = 'Ruby Client SDK for Flipt' + spec.description = '...' + spec.homepage = 'https://www.flipt.io' + spec.license = 'MIT' + spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0') - spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" + spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" - spec.metadata["homepage_uri"] = spec.homepage + spec.metadata['homepage_uri'] = spec.homepage # spec.metadata["source_code_uri"] = "TODO: Put your gem's public repo URL here." # spec.metadata["changelog_uri"] = "TODO: Put your gem's CHANGELOG.md URL here." - spec.files = Dir.glob("{lib,spec}/**/*") + ["README.md"] - spec.bindir = "exe" + spec.files = Dir.glob('{lib,spec}/**/*') + ['README.md'] + spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } - spec.require_paths = ["lib"] + spec.require_paths = ['lib'] end diff --git a/flipt-client-ruby/lib/client/version.rb b/flipt-client-ruby/lib/client/version.rb index c2b120c3..58e49fc6 100644 --- a/flipt-client-ruby/lib/client/version.rb +++ b/flipt-client-ruby/lib/client/version.rb @@ -1,5 +1,7 @@ +# frozen_string_literal: true + module Flipt module Client - VERSION = "0.1.0" + VERSION = '0.1.0' end end diff --git a/flipt-client-ruby/lib/evaluation.rb b/flipt-client-ruby/lib/evaluation.rb index c5fe9b6a..e7045ffd 100644 --- a/flipt-client-ruby/lib/evaluation.rb +++ b/flipt-client-ruby/lib/evaluation.rb @@ -1,12 +1,14 @@ -require "client/version" -require "ffi" -require "json" +# frozen_string_literal: true + +require 'client/version' +require 'ffi' +require 'json' module Flipt class Error < StandardError; end class EvaluationClient - FLIPTENGINE="ext/libfliptengine" + FLIPTENGINE = 'ext/libfliptengine' def self.platform_specific_lib case RbConfig::CONFIG['host_os'] @@ -25,15 +27,15 @@ def self.platform_specific_lib ffi_lib File.expand_path(platform_specific_lib, __dir__) # void *initialize_engine(const char *const *namespaces, const char *opts); - attach_function :initialize_engine, [:pointer, :string], :pointer + attach_function :initialize_engine, %i[pointer string], :pointer # void destroy_engine(void *engine_ptr); attach_function :destroy_engine, [:pointer], :void # const char *variant(void *engine_ptr, const char *evaluation_request); - attach_function :variant, [:pointer, :string], :string + attach_function :variant, %i[pointer string], :string # const char *boolean(void *engine_ptr, const char *evaluation_request); - attach_function :boolean, [:pointer, :string], :string + attach_function :boolean, %i[pointer string], :string - def initialize(namespace = "default", opts = {}) + def initialize(namespace = 'default', opts = {}) @namespace = namespace namespace_list = [namespace] ns = FFI::MemoryPointer.new(:pointer, namespace_list.size) @@ -46,7 +48,7 @@ def initialize(namespace = "default", opts = {}) end def self.finalize(engine) - proc { self.destroy_engine(engine) } + proc { destroy_engine(engine) } end def variant(evaluation_request = {}) @@ -63,14 +65,15 @@ def boolean(evaluation_request = {}) JSON.parse(resp) end - private + private + def validate_evaluation_request(evaluation_request) if evaluation_request[:entity_id].nil? || evaluation_request[:entity_id].empty? - raise ArgumentError, "entity_id is required" + raise ArgumentError, 'entity_id is required' elsif evaluation_request[:namespace_key].nil? || evaluation_request[:namespace_key].empty? - raise ArgumentError, "namespace_key is required" + raise ArgumentError, 'namespace_key is required' elsif evaluation_request[:flag_key].nil? || evaluation_request[:flag_key].empty? - raise ArgumentError, "flag_key is required" + raise ArgumentError, 'flag_key is required' end end end diff --git a/flipt-client-ruby/spec/evaluation_spec.rb b/flipt-client-ruby/spec/evaluation_spec.rb new file mode 100644 index 00000000..c77b936c --- /dev/null +++ b/flipt-client-ruby/spec/evaluation_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true + +require_relative '../lib/evaluation' + +RSpec.describe Flipt::EvaluationClient do + describe '#initialize' do + it 'initializes the engine' do + url = ENV.fetch('FLIPT_URL', 'http://localhost:8080') + client = Flipt::EvaluationClient.new('default', { url: url }) + expect(client).to be_a(Flipt::EvaluationClient) + end + end + + describe '#variant' do + it 'returns a variant' do + url = ENV.fetch('FLIPT_URL', 'http://localhost:8080') + client = Flipt::EvaluationClient.new('default', { url: url }) + + resp = client.variant({ flag_key: 'flag1', entity_id: 'someentity', context: { "fizz": 'buzz' } }) + + expect(resp).to_not be_nil + expect(resp['status']).to eq('success') + expect(resp['error_message']).to be_nil + expect(resp['result']['flag_key']).to eq('flag1') + expect(resp['result']['match']).to eq(true) + expect(resp['result']['reason']).to eq('MATCH_EVALUATION_REASON') + expect(resp['result']['variant_key']).to eq('variant1') + expect(resp['result']['segment_keys']).to eq(['segment1']) + end + end + + describe '#boolean' do + it 'returns a boolean' do + url = ENV.fetch('FLIPT_URL', 'http://localhost:8080') + client = Flipt::EvaluationClient.new('default', { url: url }) + + resp = client.boolean({ flag_key: 'flag_boolean', entity_id: 'someentity', context: { "fizz": 'buzz' } }) + + expect(resp).to_not be_nil + expect(resp['status']).to eq('success') + expect(resp['error_message']).to be_nil + expect(resp['result']['flag_key']).to eq('flag_boolean') + expect(resp['result']['enabled']).to eq(true) + expect(resp['result']['reason']).to eq('MATCH_EVALUATION_REASON') + end + end +end diff --git a/flipt-client-ruby/spec/spec_helper.rb b/flipt-client-ruby/spec/spec_helper.rb new file mode 100644 index 00000000..4f8c8d91 --- /dev/null +++ b/flipt-client-ruby/spec/spec_helper.rb @@ -0,0 +1,98 @@ +# frozen_string_literal: true + +# This file was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + + # The settings below are suggested to provide a good initial experience + # with RSpec, but feel free to customize to your heart's content. + # # This allows you to limit a spec run to individual examples or groups + # # you care about by tagging them with `:focus` metadata. When nothing + # # is tagged with `:focus`, all examples get run. RSpec also provides + # # aliases for `it`, `describe`, and `context` that include `:focus` + # # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + # config.filter_run_when_matching :focus + # + # # Allows RSpec to persist some state between runs in order to support + # # the `--only-failures` and `--next-failure` CLI options. We recommend + # # you configure your source control system to ignore this file. + # config.example_status_persistence_file_path = "spec/examples.txt" + # + # # Limits the available syntax to the non-monkey patched syntax that is + # # recommended. For more details, see: + # # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ + # config.disable_monkey_patching! + # + # # This setting enables warnings. It's recommended, but in some cases may + # # be too noisy due to issues in dependencies. + # config.warnings = true + # + # # Many RSpec users commonly either run the entire suite or an individual + # # file, and it's useful to allow more verbose output when running an + # # individual spec file. + # if config.files_to_run.one? + # # Use the documentation formatter for detailed output, + # # unless a formatter has already been configured + # # (e.g. via a command-line flag). + # config.default_formatter = "doc" + # end + # + # # Print the 10 slowest examples and example groups at the + # # end of the spec run, to help surface which specs are running + # # particularly slow. + # config.profile_examples = 10 + # + # # Run specs in random order to surface order dependencies. If you find an + # # order dependency and want to debug it, you can fix the order by providing + # # the seed, which is printed after each run. + # # --seed 1234 + # config.order = :random + # + # # Seed global randomization in this process using the `--seed` CLI option. + # # Setting this allows you to use `--seed` to deterministically reproduce + # # test failures related to randomization by passing the same `--seed` value + # # as the one that triggered the failure. + # Kernel.srand config.seed +end diff --git a/flipt-engine/README.md b/flipt-engine/README.md index b5da4dad..55a2103c 100644 --- a/flipt-engine/README.md +++ b/flipt-engine/README.md @@ -1,17 +1,7 @@ # Flipt Client Engine -![Status: Experimental](https://img.shields.io/badge/status-experimental-yellow) - This is the client engine for Flipt. It is responsible for evaluating context provided by the native language client SDKs and returning the results of the evaluation. -## Architecture - -The client engine is a Rust library responsible for evaluating context and returning the results of the evaluation. The client engine polls for evaluation state from the Flipt server and uses this state to determine the results of the evaluation. The client engine is designed to be embedded in the native language client SDKs. The native language client SDKs will send context to the client engine via [FFI](https://en.wikipedia.org/wiki/Foreign_function_interface) and receive the results of the evaluation from engine. - -This design allows for the client evaluation logic to be written once in a memory safe language and embedded in the native language client SDKs. This design also allows for the client engine to be updated independently of the native language client SDKs. - -TODO: Diagram - ## Development TODO: Add more details