diff --git a/.github/workflows/lint-pr.yml b/.github/workflows/lint-pr.yml index e2fe79ce..88b02783 100644 --- a/.github/workflows/lint-pr.yml +++ b/.github/workflows/lint-pr.yml @@ -18,6 +18,6 @@ jobs: name: Validate PR title runs-on: ubuntu-latest steps: - - uses: amannn/action-semantic-pull-request@cfb60706e18bc85e8aec535e3c577abe8f70378e + - uses: amannn/action-semantic-pull-request@80c0371c57c5142ed6c844270bba1864bac8a4c6 env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/merge.yml b/.github/workflows/merge.yml index 538322eb..4ff06ca6 100644 --- a/.github/workflows/merge.yml +++ b/.github/workflows/merge.yml @@ -20,9 +20,9 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + - uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 - name: Set up JDK 8 - uses: actions/setup-java@a1c6c9c8677803c9f4bd31e0f15ac0844258f955 + uses: actions/setup-java@fd08b9c8dc6f530393a204a04e1f05101a5d00fd with: java-version: '8' distribution: 'temurin' @@ -49,7 +49,7 @@ jobs: run: mvn --batch-mode --update-snapshots verify - name: Upload coverage to Codecov - uses: codecov/codecov-action@v4.3.1 + uses: codecov/codecov-action@v4.5.0 with: token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos flags: unittests # optional diff --git a/.github/workflows/pullrequest.yml b/.github/workflows/pullrequest.yml index 5825acba..e565d68c 100644 --- a/.github/workflows/pullrequest.yml +++ b/.github/workflows/pullrequest.yml @@ -10,17 +10,17 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out the code - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 - name: Set up JDK 8 - uses: actions/setup-java@a1c6c9c8677803c9f4bd31e0f15ac0844258f955 + uses: actions/setup-java@fd08b9c8dc6f530393a204a04e1f05101a5d00fd with: java-version: '8' distribution: 'temurin' cache: maven - name: Initialize CodeQL - uses: github/codeql-action/init@84d6ead480f493c32a39f012db4b9dfb02e8868b + uses: github/codeql-action/init@de945755c9edd3a4e5d160a71f1482ece6a3c271 with: languages: java @@ -36,7 +36,7 @@ jobs: run: mvn --batch-mode --update-snapshots --activate-profiles e2e verify - name: Upload coverage to Codecov - uses: codecov/codecov-action@v4.3.1 + uses: codecov/codecov-action@v4.5.0 with: token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos flags: unittests # optional @@ -45,4 +45,4 @@ jobs: verbose: true # optional (default = false) - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@84d6ead480f493c32a39f012db4b9dfb02e8868b + uses: github/codeql-action/analyze@de945755c9edd3a4e5d160a71f1482ece6a3c271 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 26c8b868..29866c56 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,7 +19,7 @@ jobs: # Release-please creates a PR that tracks all changes steps: - - uses: google-github-actions/release-please-action@a37ac6e4f6449ce8b3f7607e4d97d0146028dc0b + - uses: google-github-actions/release-please-action@e4dc86ba9405554aeba3c6bb2d169500e7d3b4ee id: release with: token: ${{secrets.GITHUB_TOKEN}} @@ -28,10 +28,10 @@ jobs: # These steps are only run if this was a merged release-please PR - name: checkout if: ${{ steps.release.outputs.release_created }} - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 - name: Set up JDK 8 if: ${{ steps.release.outputs.release_created }} - uses: actions/setup-java@a1c6c9c8677803c9f4bd31e0f15ac0844258f955 + uses: actions/setup-java@fd08b9c8dc6f530393a204a04e1f05101a5d00fd with: java-version: '8' distribution: 'temurin' diff --git a/.github/workflows/static-code-scanning.yaml b/.github/workflows/static-code-scanning.yaml index 397d5144..2e8f35fc 100644 --- a/.github/workflows/static-code-scanning.yaml +++ b/.github/workflows/static-code-scanning.yaml @@ -29,16 +29,16 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@44c2b7a8a4ea60a981eaca3cf939b5f4305c123b + uses: actions/checkout@692973e3d937129bcbf40652eb9f2f61becf3332 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@84d6ead480f493c32a39f012db4b9dfb02e8868b + uses: github/codeql-action/init@de945755c9edd3a4e5d160a71f1482ece6a3c271 with: languages: java - name: Autobuild - uses: github/codeql-action/autobuild@84d6ead480f493c32a39f012db4b9dfb02e8868b + uses: github/codeql-action/autobuild@de945755c9edd3a4e5d160a71f1482ece6a3c271 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@84d6ead480f493c32a39f012db4b9dfb02e8868b + uses: github/codeql-action/analyze@de945755c9edd3a4e5d160a71f1482ece6a3c271 diff --git a/.gitignore b/.gitignore index 1d5d37e4..a7575d54 100644 --- a/.gitignore +++ b/.gitignore @@ -9,4 +9,7 @@ target .DS_Store # vscode stuff - we may want to use a more specific pattern later if we'd like to suggest editor configurations -.vscode/ \ No newline at end of file +.vscode/ + +# used for spec compliance tooling +java-report.json diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 57327365..24ed335a 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1 +1 @@ -{".":"1.8.0"} \ No newline at end of file +{".":"1.9.0"} \ No newline at end of file diff --git a/.specrc b/.specrc new file mode 100644 index 00000000..4b31b31d --- /dev/null +++ b/.specrc @@ -0,0 +1,5 @@ +[spec] +file_extension=java +multiline_regex=@Specification\((?P.*?)\)\s*$ +number_subregex=number\s*=\s*['"](.*?)['"] +text_subregex=text\s*=\s*['"](.*)['"] \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 328e4800..b3226d8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,92 @@ # Changelog +## [1.9.0](https://github.com/open-feature/java-sdk/compare/v1.8.0...v1.9.0) (2024-06-28) + + +### ๐Ÿ› Bug Fixes + +* **deps:** update dependency io.cucumber:cucumber-bom to v7.18.0 ([#944](https://github.com/open-feature/java-sdk/issues/944)) ([bdc19b2](https://github.com/open-feature/java-sdk/commit/bdc19b2cc07dfbad1093914933b52d405d9941f7)) +* **deps:** update dependency org.projectlombok:lombok to v1.18.34 ([#993](https://github.com/open-feature/java-sdk/issues/993)) ([44b4b35](https://github.com/open-feature/java-sdk/commit/44b4b354311deee266b6b4f2a911293a0ec8f049)) +* **deps:** update junit5 monorepo ([#990](https://github.com/open-feature/java-sdk/issues/990)) ([a2c04c1](https://github.com/open-feature/java-sdk/commit/a2c04c1b23f18dbe45bb206749ddcf996e277dca)) +* PMD warnings with new version ([#936](https://github.com/open-feature/java-sdk/issues/936)) ([1a46aea](https://github.com/open-feature/java-sdk/commit/1a46aea2422e6841a7909c01b8568450360477d7)) +* run error hook when provider returns error code ([#951](https://github.com/open-feature/java-sdk/issues/951)) ([dbfeb72](https://github.com/open-feature/java-sdk/commit/dbfeb72bc5c1cda089384cf15f034c92f9d795c5)) + + +### โœจ New Features + +* implement domain scoping ([#934](https://github.com/open-feature/java-sdk/issues/934)) ([5c0aaaa](https://github.com/open-feature/java-sdk/commit/5c0aaaa8bc939412bf8f6ca21f47cd7a7f504ada)) + + +### ๐Ÿงน Chore + +* Adding information needed for spec-compliance tooling ([#900](https://github.com/open-feature/java-sdk/issues/900)) ([e65b2a0](https://github.com/open-feature/java-sdk/commit/e65b2a0ecbb25c5bcba1006195b34112f2e53808)) +* **deps:** update actions/checkout digest to 692973e ([#972](https://github.com/open-feature/java-sdk/issues/972)) ([c3eb16c](https://github.com/open-feature/java-sdk/commit/c3eb16cd75e168c317307be2d65ba4a2bad2bea7)) +* **deps:** update actions/checkout digest to a5ac7e5 ([#941](https://github.com/open-feature/java-sdk/issues/941)) ([08567f4](https://github.com/open-feature/java-sdk/commit/08567f43c85236d32101a608adad1586cb0bd952)) +* **deps:** update actions/checkout digest to b80ff79 ([#945](https://github.com/open-feature/java-sdk/issues/945)) ([015961b](https://github.com/open-feature/java-sdk/commit/015961b4fcce6ac2f24d17abedc01d1a48cc2672)) +* **deps:** update actions/setup-java digest to 2e74cbc ([#949](https://github.com/open-feature/java-sdk/issues/949)) ([0467e99](https://github.com/open-feature/java-sdk/commit/0467e999eea6bfe19c0c3bef8d92cf0e1b3a61d6)) +* **deps:** update actions/setup-java digest to fd08b9c ([#992](https://github.com/open-feature/java-sdk/issues/992)) ([0ec57a1](https://github.com/open-feature/java-sdk/commit/0ec57a1b0393437d910c81ca3e96d0bd171daa16)) +* **deps:** update amannn/action-semantic-pull-request digest to 80c0371 ([#994](https://github.com/open-feature/java-sdk/issues/994)) ([32b101e](https://github.com/open-feature/java-sdk/commit/32b101ed8f55b100554f2d5dc4e262563bd231dc)) +* **deps:** update amannn/action-semantic-pull-request digest to e32d7e6 ([#966](https://github.com/open-feature/java-sdk/issues/966)) ([dd33ec8](https://github.com/open-feature/java-sdk/commit/dd33ec82cbd2addc684c42258d44711fa10f0801)) +* **deps:** update codecov/codecov-action action to v4.4.0 ([#937](https://github.com/open-feature/java-sdk/issues/937)) ([0844c8f](https://github.com/open-feature/java-sdk/commit/0844c8f7420f2674b19c1496e524bd105b98604c)) +* **deps:** update codecov/codecov-action action to v4.4.1 ([#947](https://github.com/open-feature/java-sdk/issues/947)) ([be833a0](https://github.com/open-feature/java-sdk/commit/be833a07f28bc967c65153787e823cce0adcc92c)) +* **deps:** update codecov/codecov-action action to v4.5.0 ([#974](https://github.com/open-feature/java-sdk/issues/974)) ([59f9779](https://github.com/open-feature/java-sdk/commit/59f9779f19aab0f24d139c7e6a6a40f2c63103d2)) +* **deps:** update dependency com.github.spotbugs:spotbugs to v4.8.5 ([#922](https://github.com/open-feature/java-sdk/issues/922)) ([5097d7c](https://github.com/open-feature/java-sdk/commit/5097d7ca0ffb9b3df22c89ec62b98235708bdb8c)) +* **deps:** update dependency com.github.spotbugs:spotbugs to v4.8.6 ([#981](https://github.com/open-feature/java-sdk/issues/981)) ([8e17099](https://github.com/open-feature/java-sdk/commit/8e1709944f22921dba28748cd5ce02c2a027f564)) +* **deps:** update dependency com.github.spotbugs:spotbugs-maven-plugin to v4.8.5.0 ([#924](https://github.com/open-feature/java-sdk/issues/924)) ([3dfbfac](https://github.com/open-feature/java-sdk/commit/3dfbfac2684d5ae4633e8e3584aba728b0ce7827)) +* **deps:** update dependency com.github.spotbugs:spotbugs-maven-plugin to v4.8.6.1 ([#987](https://github.com/open-feature/java-sdk/issues/987)) ([616d7e7](https://github.com/open-feature/java-sdk/commit/616d7e7b0578624c92560fac0b2183e97ad30714)) +* **deps:** update dependency com.google.guava:guava to v33.2.1-jre ([#960](https://github.com/open-feature/java-sdk/issues/960)) ([65e2bf3](https://github.com/open-feature/java-sdk/commit/65e2bf3895eb9522390fb41621f8e132a0e51380)) +* **deps:** update dependency org.apache.maven.plugins:maven-checkstyle-plugin to v3.4.0 ([#965](https://github.com/open-feature/java-sdk/issues/965)) ([6d6bcd1](https://github.com/open-feature/java-sdk/commit/6d6bcd1dea696fc8dac4b9b05426d8fced3ed9da)) +* **deps:** update dependency org.apache.maven.plugins:maven-dependency-plugin to v3.7.0 ([#968](https://github.com/open-feature/java-sdk/issues/968)) ([82c265f](https://github.com/open-feature/java-sdk/commit/82c265f1685b099e8bca4918572267ca2d3ed4b7)) +* **deps:** update dependency org.apache.maven.plugins:maven-dependency-plugin to v3.7.1 ([#984](https://github.com/open-feature/java-sdk/issues/984)) ([b128f13](https://github.com/open-feature/java-sdk/commit/b128f13e0be61946806fed70fbc43457fa92e62a)) +* **deps:** update dependency org.apache.maven.plugins:maven-failsafe-plugin to v3.3.0 ([#977](https://github.com/open-feature/java-sdk/issues/977)) ([51721c2](https://github.com/open-feature/java-sdk/commit/51721c21638157ff116bd723f2e19d585d966c83)) +* **deps:** update dependency org.apache.maven.plugins:maven-jar-plugin to v3.4.2 ([#983](https://github.com/open-feature/java-sdk/issues/983)) ([cc2989b](https://github.com/open-feature/java-sdk/commit/cc2989bb596aa592d04904f3ee93fbe546b16f0e)) +* **deps:** update dependency org.apache.maven.plugins:maven-javadoc-plugin to v3.7.0 ([#961](https://github.com/open-feature/java-sdk/issues/961)) ([4420bca](https://github.com/open-feature/java-sdk/commit/4420bcaaa9c4f0f190796ba1ce61caf07a9515b0)) +* **deps:** update dependency org.apache.maven.plugins:maven-pmd-plugin to v3.23.0 ([#969](https://github.com/open-feature/java-sdk/issues/969)) ([20ce4da](https://github.com/open-feature/java-sdk/commit/20ce4daa4a4f0d39bc791626bba2cb5d8c93309c)) +* **deps:** update dependency org.apache.maven.plugins:maven-surefire-plugin to v3.3.0 ([#978](https://github.com/open-feature/java-sdk/issues/978)) ([078f94e](https://github.com/open-feature/java-sdk/commit/078f94edd9d6a497e771580935af3561c070c0ef)) +* **deps:** update dependency org.assertj:assertj-core to v3.26.0 ([#953](https://github.com/open-feature/java-sdk/issues/953)) ([340dd9c](https://github.com/open-feature/java-sdk/commit/340dd9c27ce2848e3875327aea4dd9c15fbbb803)) +* **deps:** update dependency org.codehaus.mojo:exec-maven-plugin to v3.3.0 ([#948](https://github.com/open-feature/java-sdk/issues/948)) ([c3c0fd2](https://github.com/open-feature/java-sdk/commit/c3c0fd2412504801fd8d976cf16344df98b13688)) +* **deps:** update dependency org.sonatype.plugins:nexus-staging-maven-plugin to v1.6.14 ([#954](https://github.com/open-feature/java-sdk/issues/954)) ([08e170e](https://github.com/open-feature/java-sdk/commit/08e170e24a293bb7474efcb4f32d3afda262e764)) +* **deps:** update dependency org.sonatype.plugins:nexus-staging-maven-plugin to v1.7.0 ([#956](https://github.com/open-feature/java-sdk/issues/956)) ([62bbd57](https://github.com/open-feature/java-sdk/commit/62bbd571e72d7618fc30fee4f9f4f0a8f2cb70af)) +* **deps:** update github/codeql-action digest to 08487db ([#932](https://github.com/open-feature/java-sdk/issues/932)) ([c94a0ba](https://github.com/open-feature/java-sdk/commit/c94a0ba8027c59aeced24af758fdb9eaf874d994)) +* **deps:** update github/codeql-action digest to 0d9161c ([#938](https://github.com/open-feature/java-sdk/issues/938)) ([00478ec](https://github.com/open-feature/java-sdk/commit/00478ec57b8188a3fefea66640fa7ecf861ce669)) +* **deps:** update github/codeql-action digest to 1428e58 ([#979](https://github.com/open-feature/java-sdk/issues/979)) ([a79c0ee](https://github.com/open-feature/java-sdk/commit/a79c0ee80a77321b4edb53a74978012d1da38b99)) +* **deps:** update github/codeql-action digest to 1e21373 ([#925](https://github.com/open-feature/java-sdk/issues/925)) ([81cba71](https://github.com/open-feature/java-sdk/commit/81cba711905dcd06f324cd6a445d455cd9e601ad)) +* **deps:** update github/codeql-action digest to 35619fb ([#980](https://github.com/open-feature/java-sdk/issues/980)) ([8928bd4](https://github.com/open-feature/java-sdk/commit/8928bd4ab811af63cba54956aad50e5c4449a8ae)) +* **deps:** update github/codeql-action digest to 3990b56 ([#975](https://github.com/open-feature/java-sdk/issues/975)) ([3fc7ccf](https://github.com/open-feature/java-sdk/commit/3fc7ccf88ac6435a0ba3bea80d1ebd353aaea876)) +* **deps:** update github/codeql-action digest to 3ce5d00 ([#985](https://github.com/open-feature/java-sdk/issues/985)) ([0dbdfa3](https://github.com/open-feature/java-sdk/commit/0dbdfa386dbe955419ba6c40e34d0f1c837e7eb7)) +* **deps:** update github/codeql-action digest to 4995c49 ([#930](https://github.com/open-feature/java-sdk/issues/930)) ([09c9a5c](https://github.com/open-feature/java-sdk/commit/09c9a5c254099f5e5b58746d2a1eed0b6191dc37)) +* **deps:** update github/codeql-action digest to 4a51972 ([#931](https://github.com/open-feature/java-sdk/issues/931)) ([29e6a90](https://github.com/open-feature/java-sdk/commit/29e6a90b102830c5112c079b4803c191dba1c232)) +* **deps:** update github/codeql-action digest to 4b812a5 ([#926](https://github.com/open-feature/java-sdk/issues/926)) ([23c01b9](https://github.com/open-feature/java-sdk/commit/23c01b9fa34b80d1667cbbfd07c1b0e496b1071c)) +* **deps:** update github/codeql-action digest to 5bf6dad ([#973](https://github.com/open-feature/java-sdk/issues/973)) ([d8db02f](https://github.com/open-feature/java-sdk/commit/d8db02f8727bb61eefe185e1f55e3f17409b14e0)) +* **deps:** update github/codeql-action digest to 63d519c ([#943](https://github.com/open-feature/java-sdk/issues/943)) ([1638b89](https://github.com/open-feature/java-sdk/commit/1638b8974f4131bd9e2d2328c27419d1406cc444)) +* **deps:** update github/codeql-action digest to 7927df0 ([#955](https://github.com/open-feature/java-sdk/issues/955)) ([a84f375](https://github.com/open-feature/java-sdk/commit/a84f37562e89b30401b8150b6929181055605392)) +* **deps:** update github/codeql-action digest to 7d9b7a1 ([#927](https://github.com/open-feature/java-sdk/issues/927)) ([0e3c10f](https://github.com/open-feature/java-sdk/commit/0e3c10fd741c3b808efec906e55f8aab52deb846)) +* **deps:** update github/codeql-action digest to 7fd4900 ([#935](https://github.com/open-feature/java-sdk/issues/935)) ([41213c7](https://github.com/open-feature/java-sdk/commit/41213c74227b1eedf5e35292eb829b6e6c7b9515)) +* **deps:** update github/codeql-action digest to 81b8143 ([#970](https://github.com/open-feature/java-sdk/issues/970)) ([f9ec8de](https://github.com/open-feature/java-sdk/commit/f9ec8de7b6d223976df5a7f4324ba56832fb06fe)) +* **deps:** update github/codeql-action digest to 8723b5b ([#986](https://github.com/open-feature/java-sdk/issues/986)) ([72b9ffe](https://github.com/open-feature/java-sdk/commit/72b9ffe5831efb0a2725efe91d16a55eab8974ed)) +* **deps:** update github/codeql-action digest to 8c4bc43 ([#952](https://github.com/open-feature/java-sdk/issues/952)) ([253f29d](https://github.com/open-feature/java-sdk/commit/253f29da2bf858cf31105c2bed5f12b9749e2ba5)) +* **deps:** update github/codeql-action digest to 8f1a6fe ([#963](https://github.com/open-feature/java-sdk/issues/963)) ([402cb1b](https://github.com/open-feature/java-sdk/commit/402cb1bc221b85c447726265f21dd097eddeacca)) +* **deps:** update github/codeql-action digest to 9550da9 ([#957](https://github.com/open-feature/java-sdk/issues/957)) ([71098a8](https://github.com/open-feature/java-sdk/commit/71098a85697eb6bf31d62142cf13da0a8cdb7132)) +* **deps:** update github/codeql-action digest to 9b7c22c ([#988](https://github.com/open-feature/java-sdk/issues/988)) ([f80a303](https://github.com/open-feature/java-sdk/commit/f80a303e3f2671157efcf409bfc45053a8aec03f)) +* **deps:** update github/codeql-action digest to 9c15e42 ([#962](https://github.com/open-feature/java-sdk/issues/962)) ([b3ba6fe](https://github.com/open-feature/java-sdk/commit/b3ba6fe5a2994f284724754d5e5c11648463cdf5)) +* **deps:** update github/codeql-action digest to a095bf2 ([#958](https://github.com/open-feature/java-sdk/issues/958)) ([27c9114](https://github.com/open-feature/java-sdk/commit/27c9114c589b26d028b5d8b5e2a8e0bc600b79bd)) +* **deps:** update github/codeql-action digest to acdf238 ([#950](https://github.com/open-feature/java-sdk/issues/950)) ([767e1ef](https://github.com/open-feature/java-sdk/commit/767e1ef04a6e1c54ed8d293190f91752ab391546)) +* **deps:** update github/codeql-action digest to add199b ([#959](https://github.com/open-feature/java-sdk/issues/959)) ([c363bdd](https://github.com/open-feature/java-sdk/commit/c363bdd1ca3dff452a589ec8cd74295ee44a0834)) +* **deps:** update github/codeql-action digest to b1bd8da ([#946](https://github.com/open-feature/java-sdk/issues/946)) ([bca1f0b](https://github.com/open-feature/java-sdk/commit/bca1f0bab67755236374c1b2afc5149f3a9833db)) +* **deps:** update github/codeql-action digest to bd2ebac ([#976](https://github.com/open-feature/java-sdk/issues/976)) ([a0b1d25](https://github.com/open-feature/java-sdk/commit/a0b1d25f4935f12fee321e4fa4751f6a7a7d8f53)) +* **deps:** update github/codeql-action digest to c36b5fc ([#971](https://github.com/open-feature/java-sdk/issues/971)) ([7cadadb](https://github.com/open-feature/java-sdk/commit/7cadadb8ec11013ab2df1a88df95ee58c662b16a)) +* **deps:** update github/codeql-action digest to c796494 ([#967](https://github.com/open-feature/java-sdk/issues/967)) ([4ea74d8](https://github.com/open-feature/java-sdk/commit/4ea74d8a0acc4fb215dbbb846533f17d4f276404)) +* **deps:** update github/codeql-action digest to ce5603b ([#982](https://github.com/open-feature/java-sdk/issues/982)) ([9ff353e](https://github.com/open-feature/java-sdk/commit/9ff353e509c8b17e65db01d731b3546bae3c5e07)) +* **deps:** update github/codeql-action digest to de94575 ([#991](https://github.com/open-feature/java-sdk/issues/991)) ([843b420](https://github.com/open-feature/java-sdk/commit/843b420cd197c0ce971a7466d1437be6871f2589)) +* **deps:** update github/codeql-action digest to def4d2c ([#929](https://github.com/open-feature/java-sdk/issues/929)) ([0c540f1](https://github.com/open-feature/java-sdk/commit/0c540f1f39f1b3e9576f0ff3f35dd774a257f1bd)) +* **deps:** update google-github-actions/release-please-action digest to e4dc86b ([#933](https://github.com/open-feature/java-sdk/issues/933)) ([2334906](https://github.com/open-feature/java-sdk/commit/2334906534d724c5a38df1ac6362759e7dbe1f96)) +* javadoc and tests for api, context ([#942](https://github.com/open-feature/java-sdk/issues/942)) ([4126b51](https://github.com/open-feature/java-sdk/commit/4126b511fbc442632dd60d0d308fdc220b2f2ae7)) + + +### ๐Ÿ“š Documentation + +* remove golang snippet and fix variable name ([#964](https://github.com/open-feature/java-sdk/issues/964)) ([515f38b](https://github.com/open-feature/java-sdk/commit/515f38b3c7621ccf6b4dbe78a028e0b354367bc3)) + ## [1.8.0](https://github.com/open-feature/java-sdk/compare/v1.7.6...v1.8.0) (2024-05-03) diff --git a/README.md b/README.md index b7fa813a..1d5598f5 100644 --- a/README.md +++ b/README.md @@ -18,8 +18,8 @@ - - Release + + Release @@ -48,7 +48,7 @@ - Java 8+ (compiler target is 1.8) -Note that this library is intended to be used in server-side contexts and has not been evaluated for use in mobile devices. +Note that this library is intended to be used in server-side contexts and has not been evaluated for use on mobile devices. ### Install @@ -59,7 +59,7 @@ Note that this library is intended to be used in server-side contexts and has no dev.openfeature sdk - 1.8.0 + 1.9.0 ``` @@ -84,7 +84,7 @@ If you would like snapshot builds, this is the relevant repository information: ```groovy dependencies { - implementation 'dev.openfeature:sdk:1.8.0' + implementation 'dev.openfeature:sdk:1.9.0' } ``` @@ -126,7 +126,7 @@ See [here](https://javadoc.io/doc/dev.openfeature/sdk/latest/) for the Javadocs. | โœ… | [Targeting](#targeting) | Contextually-aware flag evaluation using [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context). | | โœ… | [Hooks](#hooks) | Add functionality to various stages of the flag evaluation life-cycle. | | โœ… | [Logging](#logging) | Integrate with popular logging packages. | -| โœ… | [Named clients](#named-clients) | Utilize multiple providers in a single application. | +| โœ… | [Domains](#domains) | Logically bind clients with providers. | | โœ… | [Eventing](#eventing) | React to state changes in the provider or flag management system. | | โœ… | [Shutdown](#shutdown) | Gracefully clean up a provider during application shutdown. | | โœ… | [Transaction Context Propagation](#transaction-context-propagation) | Set a specific [evaluation context](https://openfeature.dev/docs/reference/concepts/evaluation-context) for a transaction (e.g. an HTTP request or a thread). | @@ -160,7 +160,7 @@ To register a provider in a non-blocking manner, you can use the `setProvider` m ``` In some situations, it may be beneficial to register multiple providers in the same application. -This is possible using [named clients](#named-clients), which is covered in more details below. +This is possible using [domains](#domains), which is covered in more detail below. ### Targeting @@ -219,27 +219,27 @@ Once you've added a hook as a dependency, it can be registered at the global, cl The Java SDK uses SLF4J. See the [SLF4J manual](https://slf4j.org/manual.html) for complete documentation. -### Named clients +### Domains -Clients can be given a name. -A name is a logical identifier which can be used to associate clients with a particular provider. -If a name has no associated provider, the global provider is used. +Clients can be assigned to a domain. +A domain is a logical identifier which can be used to associate clients with a particular provider. +If a domain has no associated provider, the global provider is used. ```java FeatureProvider scopedProvider = new MyProvider(); // registering the default provider OpenFeatureAPI.getInstance().setProvider(LocalProvider()); -// registering a named provider -OpenFeatureAPI.getInstance().setProvider("clientForCache", new CachedProvider()); +// registering a provider to a domain +OpenFeatureAPI.getInstance().setProvider("my-domain", new CachedProvider()); -// a client backed by default provider +// A client bound to the default provider Client clientDefault = OpenFeatureAPI.getInstance().getClient(); -// a client backed by CachedProvider -Client clientNamed = OpenFeatureAPI.getInstance().getClient("clientForCache"); +// A client bound to the CachedProvider provider +Client domainScopedClient = OpenFeatureAPI.getInstance().getClient("my-domain"); ``` -Named providers can be set in a blocking or non-blocking way. +Providers for domains can be set in a blocking or non-blocking way. For more details, please refer to the [providers](#providers) section. ### Eventing @@ -282,7 +282,7 @@ To register a `ThreadLocal` context propagator, you can use the `setTransactionC // registering the ThreadLocalTransactionContextPropagator OpenFeatureAPI.getInstance().setTransactionContextPropagator(new ThreadLocalTransactionContextPropagator()); ``` -Once you've registered a transaction context propagator, you can propagate the data into request scoped transaction context. +Once you've registered a transaction context propagator, you can propagate the data into request-scoped transaction context. ```java // adding userId to transaction context @@ -290,7 +290,7 @@ OpenFeatureAPI api = OpenFeatureAPI.getInstance(); Map transactionAttrs = new HashMap<>(); transactionAttrs.put("userId", new Value("userId")); EvaluationContext transactionCtx = new ImmutableContext(transactionAttrs); -api.setTransactionContext(apiCtx); +api.setTransactionContext(transactionCtx); ``` Additionally, you can develop a custom transaction context propagator by implementing the `TransactionContextPropagator` interface and registering it as shown above. @@ -390,8 +390,6 @@ class MyEventProvider extends EventProvider { 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](https://github.com/open-feature/java-sdk-contrib) 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 make use of the `UnimplementedHook` struct (which already implements all the empty functions). ```java class MyHook implements Hook { @@ -434,7 +432,7 @@ class MyHook implements Hook { Interested in contributing? Great, we'd love your help! To get started, take a look at the [CONTRIBUTING](CONTRIBUTING.md) guide. -### Thanks to everyone that has already contributed +### Thanks to everyone who has already contributed Pictures of the folks who have contributed to the project diff --git a/pom.xml b/pom.xml index b6fef55e..6f6e8416 100644 --- a/pom.xml +++ b/pom.xml @@ -4,13 +4,13 @@ dev.openfeature sdk - 1.8.0 + 1.9.0 UTF-8 1.8 ${maven.compiler.source} - 5.10.2 + 5.10.3 **/e2e/*.java ${groupId}.${artifactId} @@ -45,7 +45,7 @@ org.projectlombok lombok - 1.18.32 + 1.18.34 provided @@ -53,7 +53,7 @@ com.github.spotbugs spotbugs - 4.8.4 + 4.8.6 provided @@ -74,7 +74,7 @@ org.assertj assertj-core - 3.25.3 + 3.26.0 test @@ -109,7 +109,7 @@ org.junit.platform junit-platform-suite - 1.10.2 + 1.10.3 test @@ -135,7 +135,7 @@ com.google.guava guava - 33.2.0-jre + 33.2.1-jre test @@ -154,7 +154,7 @@ io.cucumber cucumber-bom - 7.17.0 + 7.18.0 pom import @@ -162,7 +162,7 @@ org.junit junit-bom - 5.10.2 + 5.10.3 pom import @@ -200,7 +200,7 @@ maven-dependency-plugin - 3.6.1 + 3.7.1 verify @@ -235,7 +235,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.2.5 + 3.3.0 ${surefireArgLine} @@ -250,7 +250,7 @@ org.apache.maven.plugins maven-failsafe-plugin - 3.2.5 + 3.3.0 ${surefireArgLine} @@ -321,7 +321,7 @@ org.apache.maven.plugins maven-jar-plugin - 3.4.1 + 3.4.2 @@ -334,7 +334,7 @@ org.apache.maven.plugins maven-pmd-plugin - 3.21.2 + 3.23.0 run-pmd @@ -349,7 +349,7 @@ com.github.spotbugs spotbugs-maven-plugin - 4.8.4.0 + 4.8.6.1 spotbugs-exclusions.xml @@ -365,7 +365,7 @@ com.github.spotbugs spotbugs - 4.8.4 + 4.8.6 @@ -382,7 +382,7 @@ org.apache.maven.plugins maven-checkstyle-plugin - 3.3.1 + 3.4.0 checkstyle.xml UTF-8 @@ -424,7 +424,7 @@ org.sonatype.plugins nexus-staging-maven-plugin - 1.6.13 + 1.7.0 true ossrh @@ -452,7 +452,7 @@ org.apache.maven.plugins maven-javadoc-plugin - 3.6.3 + 3.7.0 true all,-missing @@ -501,7 +501,7 @@ org.codehaus.mojo exec-maven-plugin - 3.2.0 + 3.3.0 update-test-harness-submodule diff --git a/spec_finder.py b/spec_finder.py deleted file mode 100755 index 17f8f4bd..00000000 --- a/spec_finder.py +++ /dev/null @@ -1,111 +0,0 @@ -#!/usr/bin/env python -import urllib.request -import json -import re -import difflib -import os -import sys - -def _demarkdown(t): - return t.replace('**', '').replace('`', '').replace('"', '') - -def get_spec(force_refresh=False): - spec_path = './specification.json' - data = "" - if os.path.exists(spec_path) and not force_refresh: - with open(spec_path) as f: - data = ''.join(f.readlines()) - else: - # TODO: Status code check - spec_response = urllib.request.urlopen('https://raw.githubusercontent.com/open-feature/spec/main/specification.json') - raw = [] - for i in spec_response.readlines(): - raw.append(i.decode('utf-8')) - data = ''.join(raw) - with open(spec_path, 'w') as f: - f.write(data) - return json.loads(data) - - -def main(refresh_spec=False, diff_output=False, limit_numbers=None): - actual_spec = get_spec(refresh_spec) - - spec_map = {} - for entry in actual_spec['rules']: - number = re.search('[\d.]+', entry['id']).group() - if 'requirement' in entry['machine_id']: - spec_map[number] = _demarkdown(entry['content']) - - if len(entry['children']) > 0: - for ch in entry['children']: - number = re.search('[\d.]+', ch['id']).group() - if 'requirement' in ch['machine_id']: - spec_map[number] = _demarkdown(ch['content']) - - java_specs = {} - missing = set(spec_map.keys()) - - - import os - for root, dirs, files in os.walk(".", topdown=False): - for name in files: - F = os.path.join(root, name) - if '.java' not in name: - continue - with open(F) as f: - data = ''.join(f.readlines()) - - for match in re.findall('@Specification\((?P.*?)"\)', data.replace('\n', ''), re.MULTILINE | re.DOTALL): - number = re.findall('number\s*=\s*"(.*?)"', match)[0] - - if number in missing: - missing.remove(number) - text_with_concat_chars = re.findall('text\s*=\s*(.*)', match) - try: - # We have to match for ") to capture text with parens inside, so we add the trailing " back in. - text = _demarkdown(eval(''.join(text_with_concat_chars) + '"')) - entry = java_specs[number] = { - 'number': number, - 'text': text, - } - except: - print(f"Skipping {match} b/c we couldn't parse it") - - bad_num = len(missing) - for number, entry in java_specs.items(): - if limit_numbers is not None and len(limit_numbers) > 0 and number not in limit_numbers: - continue - if number in spec_map: - txt = entry['text'] - if txt == spec_map[number]: - # print(f'{number} is good') - continue - else: - print(f"{number} is bad") - bad_num += 1 - if diff_output: - print(number + '\n' + '\n'.join([li for li in difflib.ndiff([txt], [spec_map[number]]) if not li.startswith(' ')])) - continue - - print(f"{number} is defined in our tests, but couldn't find it in the spec") - print("") - - if len(missing) > 0: - print('In the spec, but not in our tests: ') - for m in missing: - print(f" {m}: {spec_map[m]}") - - sys.exit(bad_num) - - -if __name__ == '__main__': - import argparse - - parser = argparse.ArgumentParser(description='Parse the spec to make sure our tests cover it') - parser.add_argument('--refresh-spec', action='store_true', help='Re-downloads the spec') - parser.add_argument('--diff-output', action='store_true', help='print the text differences') - parser.add_argument('specific_numbers', metavar='num', type=str, nargs='*', - help='limit this to specific numbers') - - args = parser.parse_args() - main(refresh_spec=args.refresh_spec, diff_output=args.diff_output, limit_numbers=args.specific_numbers) diff --git a/src/main/java/dev/openfeature/sdk/Client.java b/src/main/java/dev/openfeature/sdk/Client.java index 4494180a..2184cdcb 100644 --- a/src/main/java/dev/openfeature/sdk/Client.java +++ b/src/main/java/dev/openfeature/sdk/Client.java @@ -6,7 +6,7 @@ * Interface used to resolve flags of varying types. */ public interface Client extends Features, EventBus { - Metadata getMetadata(); + ClientMetadata getMetadata(); /** * Return an optional client-level evaluation context. diff --git a/src/main/java/dev/openfeature/sdk/ClientMetadata.java b/src/main/java/dev/openfeature/sdk/ClientMetadata.java new file mode 100644 index 00000000..fa0ed402 --- /dev/null +++ b/src/main/java/dev/openfeature/sdk/ClientMetadata.java @@ -0,0 +1,14 @@ +package dev.openfeature.sdk; + +/** + * Metadata specific to an OpenFeature {@code Client}. + */ +public interface ClientMetadata { + String getDomain(); + + @Deprecated + // this is here for compatibility with getName() exposed from {@link Metadata} + default String getName() { + return getDomain(); + } +} diff --git a/src/main/java/dev/openfeature/sdk/EventDetails.java b/src/main/java/dev/openfeature/sdk/EventDetails.java index 02b1964d..f2113eea 100644 --- a/src/main/java/dev/openfeature/sdk/EventDetails.java +++ b/src/main/java/dev/openfeature/sdk/EventDetails.java @@ -9,19 +9,19 @@ @Data @SuperBuilder(toBuilder = true) public class EventDetails extends ProviderEventDetails { - private String clientName; + private String domain; private String providerName; static EventDetails fromProviderEventDetails(ProviderEventDetails providerEventDetails, String providerName) { - return EventDetails.fromProviderEventDetails(providerEventDetails, providerName, null); + return fromProviderEventDetails(providerEventDetails, providerName, null); } static EventDetails fromProviderEventDetails( ProviderEventDetails providerEventDetails, String providerName, - String clientName) { - return EventDetails.builder() - .clientName(clientName) + String domain) { + return builder() + .domain(domain) .providerName(providerName) .flagsChanged(providerEventDetails.getFlagsChanged()) .eventMetadata(providerEventDetails.getEventMetadata()) diff --git a/src/main/java/dev/openfeature/sdk/EventSupport.java b/src/main/java/dev/openfeature/sdk/EventSupport.java index aa48b8b0..085c8eb8 100644 --- a/src/main/java/dev/openfeature/sdk/EventSupport.java +++ b/src/main/java/dev/openfeature/sdk/EventSupport.java @@ -33,19 +33,19 @@ class EventSupport { }); /** - * Run all the event handlers associated with this client name. - * If the client name is null, handlers attached to unnamed clients will run. + * Run all the event handlers associated with this domain. + * If the domain is null, handlers attached to unnamed clients will run. * - * @param clientName the client name to run event handlers for, or null + * @param domain the domain to run event handlers for, or null * @param event the event type * @param eventDetails the event details */ - public void runClientHandlers(String clientName, ProviderEvent event, EventDetails eventDetails) { - clientName = Optional.ofNullable(clientName) + public void runClientHandlers(String domain, ProviderEvent event, EventDetails eventDetails) { + domain = Optional.ofNullable(domain) .orElse(defaultClientUuid); // run handlers if they exist - Optional.ofNullable(handlerStores.get(clientName)) + Optional.ofNullable(handlerStores.get(domain)) .filter(store -> Optional.of(store).isPresent()) .map(store -> store.handlerMap.get(event)) .ifPresent(handlers -> handlers @@ -66,15 +66,14 @@ public void runGlobalHandlers(ProviderEvent event, EventDetails eventDetails) { } /** - * Add a handler for the specified client name, or all unnamed clients. + * Add a handler for the specified domain, or all unnamed clients. * - * @param clientName the client name to add handlers for, or else the unnamed - * client + * @param domain the domain to add handlers for, or else unnamed * @param event the event type * @param handler the handler function to run */ - public void addClientHandler(String clientName, ProviderEvent event, Consumer handler) { - final String name = Optional.ofNullable(clientName) + public void addClientHandler(String domain, ProviderEvent event, Consumer handler) { + final String name = Optional.ofNullable(domain) .orElse(defaultClientUuid); // lazily create and cache a HandlerStore if it doesn't exist @@ -90,15 +89,15 @@ public void addClientHandler(String clientName, ProviderEvent event, Consumer handler) { - clientName = Optional.ofNullable(clientName) + public void removeClientHandler(String domain, ProviderEvent event, Consumer handler) { + domain = Optional.ofNullable(domain) .orElse(defaultClientUuid); - this.handlerStores.get(clientName).removeHandler(event, handler); + this.handlerStores.get(domain).removeHandler(event, handler); } /** @@ -122,11 +121,11 @@ public void removeGlobalHandler(ProviderEvent event, Consumer hand } /** - * Get all client names for which we have event handlers registered. + * Get all domain names for which we have event handlers registered. * - * @return set of client names + * @return set of domain names */ - public Set getAllClientNames() { + public Set getAllDomainNames() { return this.handlerStores.keySet(); } diff --git a/src/main/java/dev/openfeature/sdk/HookContext.java b/src/main/java/dev/openfeature/sdk/HookContext.java index 26b14f79..5c9091b8 100644 --- a/src/main/java/dev/openfeature/sdk/HookContext.java +++ b/src/main/java/dev/openfeature/sdk/HookContext.java @@ -16,7 +16,7 @@ public class HookContext { @NonNull FlagValueType type; @NonNull T defaultValue; @NonNull EvaluationContext ctx; - Metadata clientMetadata; + ClientMetadata clientMetadata; Metadata providerMetadata; /** @@ -30,7 +30,7 @@ public class HookContext { * @param type that the flag is evaluating against * @return resulting context for hook */ - public static HookContext from(String key, FlagValueType type, Metadata clientMetadata, + public static HookContext from(String key, FlagValueType type, ClientMetadata clientMetadata, Metadata providerMetadata, EvaluationContext ctx, T defaultValue) { return HookContext.builder() .flagKey(key) diff --git a/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java b/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java index db28555a..f4d20caf 100644 --- a/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java +++ b/src/main/java/dev/openfeature/sdk/OpenFeatureAPI.java @@ -1,5 +1,10 @@ package dev.openfeature.sdk; +import dev.openfeature.sdk.exceptions.OpenFeatureError; +import dev.openfeature.sdk.internal.AutoCloseableLock; +import dev.openfeature.sdk.internal.AutoCloseableReentrantReadWriteLock; +import lombok.extern.slf4j.Slf4j; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -7,17 +12,13 @@ import java.util.Set; import java.util.function.Consumer; -import dev.openfeature.sdk.exceptions.OpenFeatureError; -import dev.openfeature.sdk.internal.AutoCloseableLock; -import dev.openfeature.sdk.internal.AutoCloseableReentrantReadWriteLock; -import lombok.extern.slf4j.Slf4j; - /** * A global singleton which holds base configuration for the OpenFeature * library. * Configuration here will be shared across all {@link Client}s. */ @Slf4j +@SuppressWarnings("PMD.UnusedLocalVariable") public class OpenFeatureAPI implements EventBus { // package-private multi-read/single-write lock static AutoCloseableReentrantReadWriteLock lock = new AutoCloseableReentrantReadWriteLock(); @@ -47,39 +48,74 @@ public static OpenFeatureAPI getInstance() { return SingletonHolder.INSTANCE; } + /** + * Get metadata about the default provider. + * + * @return the provider metadata + */ public Metadata getProviderMetadata() { return getProvider().getMetadata(); } - public Metadata getProviderMetadata(String clientName) { - return getProvider(clientName).getMetadata(); + /** + * Get metadata about a registered provider using the client name. + * An unbound or empty client name will return metadata from the default provider. + * + * @param domain an identifier which logically binds clients with providers + * @return the provider metadata + */ + public Metadata getProviderMetadata(String domain) { + return getProvider(domain).getMetadata(); } /** - * {@inheritDoc} + * A factory function for creating new, OpenFeature clients. + * Clients can contain their own state (e.g. logger, hook, context). + * Multiple clients can be used to segment feature flag configuration. + * All un-named or unbound clients use the default provider. + * + * @return a new client instance */ public Client getClient() { return getClient(null, null); } /** - * {@inheritDoc} + * A factory function for creating new domainless OpenFeature clients. + * Clients can contain their own state (e.g. logger, hook, context). + * Multiple clients can be used to segment feature flag configuration. + * If there is already a provider bound to this domain, this provider will be used. + * Otherwise, the default provider is used until a provider is assigned to that domain. + * + * @param domain an identifier which logically binds clients with providers + * @return a new client instance */ - public Client getClient(String name) { - return getClient(name, null); + public Client getClient(String domain) { + return getClient(domain, null); } /** - * {@inheritDoc} + * A factory function for creating new domainless OpenFeature clients. + * Clients can contain their own state (e.g. logger, hook, context). + * Multiple clients can be used to segment feature flag configuration. + * If there is already a provider bound to this domain, this provider will be used. + * Otherwise, the default provider is used until a provider is assigned to that domain. + * + * @param domain a identifier which logically binds clients with providers + * @param version a version identifier + * @return a new client instance */ - public Client getClient(String name, String version) { + public Client getClient(String domain, String version) { return new OpenFeatureClient(this, - name, + domain, version); } /** - * {@inheritDoc} + * Sets the global evaluation context, which will be used for all evaluations. + * + * @param evaluationContext the context + * @return api instance */ public OpenFeatureAPI setEvaluationContext(EvaluationContext evaluationContext) { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { @@ -89,7 +125,9 @@ public OpenFeatureAPI setEvaluationContext(EvaluationContext evaluationContext) } /** - * {@inheritDoc} + * Gets the global evaluation context, which will be used for all evaluations. + * + * @return evaluation context */ public EvaluationContext getEvaluationContext() { try (AutoCloseableLock __ = lock.readLockAutoCloseable()) { @@ -153,14 +191,14 @@ public void setProvider(FeatureProvider provider) { } /** - * Add a provider for a named client. + * Add a provider for a domain. * - * @param clientName The name of the client. + * @param domain The domain to bind the provider to. * @param provider The provider to set. */ - public void setProvider(String clientName, FeatureProvider provider) { + public void setProvider(String domain, FeatureProvider provider) { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { - providerRepository.setProvider(clientName, + providerRepository.setProvider(domain, provider, this::attachEventProvider, this::emitReady, @@ -186,14 +224,14 @@ public void setProviderAndWait(FeatureProvider provider) throws OpenFeatureError } /** - * Add a provider for a named client and wait for initialization to finish. + * Add a provider for a domain and wait for initialization to finish. * - * @param clientName The name of the client. + * @param domain The domain to bind the provider to. * @param provider The provider to set. */ - public void setProviderAndWait(String clientName, FeatureProvider provider) throws OpenFeatureError { + public void setProviderAndWait(String domain, FeatureProvider provider) throws OpenFeatureError { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { - providerRepository.setProvider(clientName, + providerRepository.setProvider(domain, provider, this::attachEventProvider, this::emitReady, @@ -239,17 +277,20 @@ public FeatureProvider getProvider() { } /** - * Fetch a provider for a named client. If not found, return the default. + * Fetch a provider for a domain. If not found, return the default. * - * @param name The client name to look for. + * @param domain The domain to look for. * @return A named {@link FeatureProvider} */ - public FeatureProvider getProvider(String name) { - return providerRepository.getProvider(name); + public FeatureProvider getProvider(String domain) { + return providerRepository.getProvider(domain); } /** - * {@inheritDoc} + * Adds hooks for globally, used for all evaluations. + * Hooks are run in the order they're added in the before stage. They are run in reverse order for all other stages. + * + * @param hooks The hook to add. */ public void addHooks(Hook... hooks) { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { @@ -258,7 +299,8 @@ public void addHooks(Hook... hooks) { } /** - * {@inheritDoc} + * Fetch the hooks associated to this client. + * @return A list of {@link Hook}s. */ public List getHooks() { try (AutoCloseableLock __ = lock.readLockAutoCloseable()) { @@ -267,7 +309,7 @@ public List getHooks() { } /** - * {@inheritDoc} + * Removes all hooks. */ public void clearHooks() { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { @@ -343,20 +385,20 @@ public OpenFeatureAPI removeHandler(ProviderEvent event, Consumer return this; } - void removeHandler(String clientName, ProviderEvent event, Consumer handler) { + void removeHandler(String domain, ProviderEvent event, Consumer handler) { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { - eventSupport.removeClientHandler(clientName, event, handler); + eventSupport.removeClientHandler(domain, event, handler); } } - void addHandler(String clientName, ProviderEvent event, Consumer handler) { + void addHandler(String domain, ProviderEvent event, Consumer handler) { try (AutoCloseableLock __ = lock.writeLockAutoCloseable()) { // if the provider is in the state associated with event, run immediately - if (Optional.ofNullable(this.providerRepository.getProvider(clientName).getState()) + if (Optional.ofNullable(this.providerRepository.getProvider(domain).getState()) .orElse(ProviderState.READY).matchesEvent(event)) { - eventSupport.runHandler(handler, EventDetails.builder().clientName(clientName).build()); + eventSupport.runHandler(handler, EventDetails.builder().domain(domain).build()); } - eventSupport.addClientHandler(clientName, event, handler); + eventSupport.addClientHandler(domain, event, handler); } } @@ -370,8 +412,8 @@ void addHandler(String clientName, ProviderEvent event, Consumer h private void runHandlersForProvider(FeatureProvider provider, ProviderEvent event, ProviderEventDetails details) { try (AutoCloseableLock __ = lock.readLockAutoCloseable()) { - List clientNamesForProvider = providerRepository - .getClientNamesForProvider(provider); + List domainsForProvider = providerRepository + .getDomainsForProvider(provider); final String providerName = Optional.ofNullable(provider.getMetadata()) .map(metadata -> metadata.getName()) @@ -380,20 +422,20 @@ private void runHandlersForProvider(FeatureProvider provider, ProviderEvent even // run the global handlers eventSupport.runGlobalHandlers(event, EventDetails.fromProviderEventDetails(details, providerName)); - // run the handlers associated with named clients for this provider - clientNamesForProvider.forEach(name -> { - eventSupport.runClientHandlers(name, event, - EventDetails.fromProviderEventDetails(details, providerName, name)); + // run the handlers associated with domains for this provider + domainsForProvider.forEach(domain -> { + eventSupport.runClientHandlers(domain, event, + EventDetails.fromProviderEventDetails(details, providerName, domain)); }); if (providerRepository.isDefaultProvider(provider)) { // run handlers for clients that have no bound providers (since this is the default) - Set allClientNames = eventSupport.getAllClientNames(); - Set boundClientNames = providerRepository.getAllBoundClientNames(); - allClientNames.removeAll(boundClientNames); - allClientNames.forEach(name -> { - eventSupport.runClientHandlers(name, event, - EventDetails.fromProviderEventDetails(details, providerName, name)); + Set allDomainNames = eventSupport.getAllDomainNames(); + Set boundDomains = providerRepository.getAllBoundDomains(); + allDomainNames.removeAll(boundDomains); + allDomainNames.forEach(domain -> { + eventSupport.runClientHandlers(domain, event, + EventDetails.fromProviderEventDetails(details, providerName, domain)); }); } } diff --git a/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java b/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java index ce763a34..4a1c1179 100644 --- a/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java +++ b/src/main/java/dev/openfeature/sdk/OpenFeatureClient.java @@ -11,6 +11,7 @@ import dev.openfeature.sdk.exceptions.OpenFeatureError; import dev.openfeature.sdk.internal.AutoCloseableLock; import dev.openfeature.sdk.internal.AutoCloseableReentrantReadWriteLock; +import dev.openfeature.sdk.exceptions.ExceptionUtils; import dev.openfeature.sdk.internal.ObjectUtils; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -19,12 +20,13 @@ * {@inheritDoc} */ @Slf4j -@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.BeanMembersShouldSerialize", "unchecked", "rawtypes" }) +@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.BeanMembersShouldSerialize", + "PMD.UnusedLocalVariable", "unchecked", "rawtypes" }) public class OpenFeatureClient implements Client { private final OpenFeatureAPI openfeatureApi; @Getter - private final String name; + private final String domain; @Getter private final String version; private final List clientHooks; @@ -37,16 +39,16 @@ public class OpenFeatureClient implements Client { * Deprecated public constructor. Use OpenFeature.API.getClient() instead. * * @param openFeatureAPI Backing global singleton - * @param name Name of the client (used by observability tools). + * @param domain An identifier which logically binds clients with providers (used by observability tools). * @param version Version of the client (used by observability tools). * @deprecated Do not use this constructor. It's for internal use only. * Clients created using it will not run event handlers. * Use the OpenFeatureAPI's getClient factory method instead. */ @Deprecated() // TODO: eventually we will make this non-public. See issue #872 - public OpenFeatureClient(OpenFeatureAPI openFeatureAPI, String name, String version) { + public OpenFeatureClient(OpenFeatureAPI openFeatureAPI, String domain, String version) { this.openfeatureApi = openFeatureAPI; - this.name = name; + this.domain = domain; this.version = version; this.clientHooks = new ArrayList<>(); this.hookSupport = new HookSupport(); @@ -108,7 +110,7 @@ private FlagEvaluationDetails evaluateFlag(FlagValueType type, String key try { // openfeatureApi.getProvider() must be called once to maintain a consistent reference - provider = openfeatureApi.getProvider(this.name); + provider = openfeatureApi.getProvider(this.domain); mergedHooks = ObjectUtils.merge(provider.getProviderHooks(), flagOptions.getHooks(), clientHooks, openfeatureApi.getHooks()); @@ -124,7 +126,11 @@ private FlagEvaluationDetails evaluateFlag(FlagValueType type, String key defaultValue, provider, mergedCtx); details = FlagEvaluationDetails.from(providerEval, key); - hookSupport.afterHooks(type, hookCtx, details, mergedHooks, hints); + if (details.getErrorCode() != null) { + throw ExceptionUtils.instantiateErrorByErrorCode(details.getErrorCode(), details.getErrorMessage()); + } else { + hookSupport.afterHooks(type, hookCtx, details, mergedHooks, hints); + } } catch (Exception e) { log.error("Unable to correctly evaluate flag with key '{}'", key, e); if (details == null) { @@ -353,8 +359,8 @@ public FlagEvaluationDetails getObjectDetails(String key, Value defaultVa } @Override - public Metadata getMetadata() { - return () -> name; + public ClientMetadata getMetadata() { + return () -> domain; } /** @@ -394,7 +400,7 @@ public Client onProviderStale(Consumer handler) { */ @Override public Client on(ProviderEvent event, Consumer handler) { - OpenFeatureAPI.getInstance().addHandler(name, event, handler); + OpenFeatureAPI.getInstance().addHandler(domain, event, handler); return this; } @@ -403,7 +409,7 @@ public Client on(ProviderEvent event, Consumer handler) { */ @Override public Client removeHandler(ProviderEvent event, Consumer handler) { - OpenFeatureAPI.getInstance().removeHandler(name, event, handler); + OpenFeatureAPI.getInstance().removeHandler(domain, event, handler); return this; } } diff --git a/src/main/java/dev/openfeature/sdk/ProviderRepository.java b/src/main/java/dev/openfeature/sdk/ProviderRepository.java index 1ebd9b4c..47b9ecf5 100644 --- a/src/main/java/dev/openfeature/sdk/ProviderRepository.java +++ b/src/main/java/dev/openfeature/sdk/ProviderRepository.java @@ -36,22 +36,22 @@ public FeatureProvider getProvider() { } /** - * Fetch a provider for a named client. If not found, return the default. + * Fetch a provider for a domain. If not found, return the default. * - * @param name The client name to look for. + * @param domain The domain to look for. * @return A named {@link FeatureProvider} */ - public FeatureProvider getProvider(String name) { - return Optional.ofNullable(name).map(this.providers::get).orElse(this.defaultProvider.get()); + public FeatureProvider getProvider(String domain) { + return Optional.ofNullable(domain).map(this.providers::get).orElse(this.defaultProvider.get()); } - public List getClientNamesForProvider(FeatureProvider provider) { + public List getDomainsForProvider(FeatureProvider provider) { return providers.entrySet().stream() .filter(entry -> entry.getValue().equals(provider)) .map(entry -> entry.getKey()).collect(Collectors.toList()); } - public Set getAllBoundClientNames() { + public Set getAllBoundDomains() { return providers.keySet(); } @@ -75,14 +75,14 @@ public void setProvider(FeatureProvider provider, } /** - * Add a provider for a named client. + * Add a provider for a domain. * - * @param clientName The name of the client. + * @param domain The domain to bind the provider to. * @param provider The provider to set. * @param waitForInit When true, wait for initialization to finish, then returns. * Otherwise, initialization happens in the background. */ - public void setProvider(String clientName, + public void setProvider(String domain, FeatureProvider provider, Consumer afterSet, Consumer afterInit, @@ -92,13 +92,13 @@ public void setProvider(String clientName, if (provider == null) { throw new IllegalArgumentException("Provider cannot be null"); } - if (clientName == null) { - throw new IllegalArgumentException("clientName cannot be null"); + if (domain == null) { + throw new IllegalArgumentException("domain cannot be null"); } - prepareAndInitializeProvider(clientName, provider, afterSet, afterInit, afterShutdown, afterError, waitForInit); + prepareAndInitializeProvider(domain, provider, afterSet, afterInit, afterShutdown, afterError, waitForInit); } - private void prepareAndInitializeProvider(String clientName, + private void prepareAndInitializeProvider(String domain, FeatureProvider newProvider, Consumer afterSet, Consumer afterInit, @@ -112,8 +112,8 @@ private void prepareAndInitializeProvider(String clientName, } // provider is set immediately, on this thread - FeatureProvider oldProvider = clientName != null - ? this.providers.put(clientName, newProvider) + FeatureProvider oldProvider = domain != null + ? this.providers.put(domain, newProvider) : this.defaultProvider.getAndSet(newProvider); if (waitForInit) { diff --git a/src/main/java/dev/openfeature/sdk/exceptions/ExceptionUtils.java b/src/main/java/dev/openfeature/sdk/exceptions/ExceptionUtils.java new file mode 100644 index 00000000..28c7cd71 --- /dev/null +++ b/src/main/java/dev/openfeature/sdk/exceptions/ExceptionUtils.java @@ -0,0 +1,34 @@ +package dev.openfeature.sdk.exceptions; + +import dev.openfeature.sdk.ErrorCode; +import lombok.experimental.UtilityClass; + +@SuppressWarnings("checkstyle:MissingJavadocType") +@UtilityClass +public class ExceptionUtils { + + /** + * Creates an Error for the specific error code. + * @param errorCode the ErrorCode to use + * @param errorMessage the error message to include in the returned error + * @return the specific OpenFeatureError for the errorCode + */ + public static OpenFeatureError instantiateErrorByErrorCode(ErrorCode errorCode, String errorMessage) { + switch (errorCode) { + case FLAG_NOT_FOUND: + return new FlagNotFoundError(errorMessage); + case PARSE_ERROR: + return new ParseError(errorMessage); + case TYPE_MISMATCH: + return new TypeMismatchError(errorMessage); + case TARGETING_KEY_MISSING: + return new TargetingKeyMissingError(errorMessage); + case INVALID_CONTEXT: + return new InvalidContextError(errorMessage); + case PROVIDER_NOT_READY: + return new ProviderNotReadyError(errorMessage); + default: + return new GeneralError(errorMessage); + } + } +} diff --git a/src/test/java/dev/openfeature/sdk/AlwaysBrokenProvider.java b/src/test/java/dev/openfeature/sdk/AlwaysBrokenProvider.java index 4beb28c3..c1097623 100644 --- a/src/test/java/dev/openfeature/sdk/AlwaysBrokenProvider.java +++ b/src/test/java/dev/openfeature/sdk/AlwaysBrokenProvider.java @@ -6,11 +6,8 @@ public class AlwaysBrokenProvider implements FeatureProvider { @Override public Metadata getMetadata() { - return new Metadata() { - @Override - public String getName() { - throw new FlagNotFoundError(TestConstants.BROKEN_MESSAGE); - } + return () -> { + throw new FlagNotFoundError(TestConstants.BROKEN_MESSAGE); }; } diff --git a/src/test/java/dev/openfeature/sdk/DoSomethingProvider.java b/src/test/java/dev/openfeature/sdk/DoSomethingProvider.java index 4fdc433b..32293446 100644 --- a/src/test/java/dev/openfeature/sdk/DoSomethingProvider.java +++ b/src/test/java/dev/openfeature/sdk/DoSomethingProvider.java @@ -7,8 +7,6 @@ class DoSomethingProvider implements FeatureProvider { static final ImmutableMetadata DEFAULT_METADATA = ImmutableMetadata.builder().build(); private ImmutableMetadata flagMetadata; - private EvaluationContext savedContext; - public DoSomethingProvider() { this.flagMetadata = DEFAULT_METADATA; } @@ -17,10 +15,6 @@ public DoSomethingProvider(ImmutableMetadata flagMetadata) { this.flagMetadata = flagMetadata; } - EvaluationContext getMergedContext() { - return savedContext; - } - @Override public Metadata getMetadata() { return () -> name; @@ -28,7 +22,6 @@ public Metadata getMetadata() { @Override public ProviderEvaluation getBooleanEvaluation(String key, Boolean defaultValue, EvaluationContext ctx) { - savedContext = ctx; return ProviderEvaluation.builder() .value(!defaultValue) .flagMetadata(flagMetadata) @@ -45,7 +38,6 @@ public ProviderEvaluation getStringEvaluation(String key, String default @Override public ProviderEvaluation getIntegerEvaluation(String key, Integer defaultValue, EvaluationContext ctx) { - savedContext = ctx; return ProviderEvaluation.builder() .value(defaultValue * 100) .flagMetadata(flagMetadata) @@ -54,7 +46,6 @@ public ProviderEvaluation getIntegerEvaluation(String key, Integer defa @Override public ProviderEvaluation getDoubleEvaluation(String key, Double defaultValue, EvaluationContext ctx) { - savedContext = ctx; return ProviderEvaluation.builder() .value(defaultValue * 100) .flagMetadata(flagMetadata) @@ -63,7 +54,6 @@ public ProviderEvaluation getDoubleEvaluation(String key, Double default @Override public ProviderEvaluation getObjectEvaluation(String key, Value defaultValue, EvaluationContext invocationContext) { - savedContext = invocationContext; return ProviderEvaluation.builder() .value(null) .flagMetadata(flagMetadata) diff --git a/src/test/java/dev/openfeature/sdk/EventProviderTest.java b/src/test/java/dev/openfeature/sdk/EventProviderTest.java index 3744682b..a5be8589 100644 --- a/src/test/java/dev/openfeature/sdk/EventProviderTest.java +++ b/src/test/java/dev/openfeature/sdk/EventProviderTest.java @@ -77,14 +77,11 @@ void doesNotThrowWhenOnEmitSame() { class TestEventProvider extends EventProvider { + private static final String NAME = "TestEventProvider"; + @Override public Metadata getMetadata() { - return new Metadata() { - @Override - public String getName() { - return "TestEventProvider"; - } - }; + return () -> NAME; } @Override diff --git a/src/test/java/dev/openfeature/sdk/EventsTest.java b/src/test/java/dev/openfeature/sdk/EventsTest.java index f9f8e4b8..6b70617f 100644 --- a/src/test/java/dev/openfeature/sdk/EventsTest.java +++ b/src/test/java/dev/openfeature/sdk/EventsTest.java @@ -48,7 +48,7 @@ class Initialization { @Specification(number = "5.3.1", text = "If the provider's initialize function terminates normally," + " PROVIDER_READY handlers MUST run.") void apiInitReady() { - final Consumer handler = (Consumer)mockHandler(); + final Consumer handler = mockHandler(); final String name = "apiInitReady"; TestEventsProvider provider = new TestEventsProvider(INIT_DELAY); @@ -105,7 +105,7 @@ void apiShouldPropagateEvents() { @Specification(number = "5.2.2", text = "The API MUST provide a function for associating handler functions" + " with a particular provider event type.") - void apiShouldSupportAllEventTypes() throws Exception { + void apiShouldSupportAllEventTypes() { final String name = "apiShouldSupportAllEventTypes"; final Consumer handler1 = mockHandler(); final Consumer handler2 = mockHandler(); @@ -191,7 +191,7 @@ class Initialization { @Test @DisplayName("should fire initial READY event when provider init succeeds after client retrieved") @Specification(number = "5.3.1", text = "If the provider's initialize function terminates normally, PROVIDER_READY handlers MUST run.") - void initReadyProviderBefore() throws InterruptedException { + void initReadyProviderBefore() { final Consumer handler = mockHandler(); final String name = "initReadyProviderBefore"; @@ -201,7 +201,7 @@ void initReadyProviderBefore() throws InterruptedException { // set provider after getting a client OpenFeatureAPI.getInstance().setProvider(name, provider); verify(handler, timeout(TIMEOUT).atLeastOnce()) - .accept(argThat(details -> details.getClientName().equals(name))); + .accept(argThat(details -> details.getDomain().equals(name))); } @Test @@ -217,7 +217,7 @@ void initReadyProviderAfter() { Client client = OpenFeatureAPI.getInstance().getClient(name); client.onProviderReady(handler); verify(handler, timeout(TIMEOUT).atLeastOnce()) - .accept(argThat(details -> details.getClientName().equals(name))); + .accept(argThat(details -> details.getDomain().equals(name))); } @Test @@ -234,7 +234,7 @@ void initErrorProviderAfter() { // set provider after getting a client OpenFeatureAPI.getInstance().setProvider(name, provider); verify(handler, timeout(TIMEOUT)).accept(argThat(details -> { - return name.equals(details.getClientName()) + return name.equals(details.getDomain()) && errMessage.equals(details.getMessage()); })); } @@ -253,7 +253,7 @@ void initErrorProviderBefore() { Client client = OpenFeatureAPI.getInstance().getClient(name); client.onProviderError(handler); verify(handler, timeout(TIMEOUT)).accept(argThat(details -> { - return name.equals(details.getClientName()) + return name.equals(details.getDomain()) && errMessage.equals(details.getMessage()); })); } @@ -277,7 +277,7 @@ void shouldPropagateBefore() { client.onProviderConfigurationChanged(handler); provider.mockEvent(ProviderEvent.PROVIDER_CONFIGURATION_CHANGED, EventDetails.builder().build()); - verify(handler, timeout(TIMEOUT)).accept(argThat(details -> details.getClientName().equals(name))); + verify(handler, timeout(TIMEOUT)).accept(argThat(details -> details.getDomain().equals(name))); } @Test @@ -295,7 +295,7 @@ void shouldPropagateAfter() { OpenFeatureAPI.getInstance().setProvider(name, provider); provider.mockEvent(ProviderEvent.PROVIDER_CONFIGURATION_CHANGED, EventDetails.builder().build()); - verify(handler, timeout(TIMEOUT)).accept(argThat(details -> details.getClientName().equals(name))); + verify(handler, timeout(TIMEOUT)).accept(argThat(details -> details.getDomain().equals(name))); } @Test @@ -306,7 +306,7 @@ void shouldPropagateAfter() { @Specification(number = "5.2.1", text = "The client MUST provide a function for associating handler functions" + " with a particular provider event type.") - void shouldSupportAllEventTypes() throws Exception { + void shouldSupportAllEventTypes() { final String name = "shouldSupportAllEventTypes"; final Consumer handler1 = mockHandler(); final Consumer handler2 = mockHandler(); @@ -325,7 +325,7 @@ void shouldSupportAllEventTypes() throws Exception { Arrays.asList(ProviderEvent.values()).stream().forEach(eventType -> { provider.mockEvent(eventType, ProviderEventDetails.builder().build()); }); - ArgumentMatcher nameMatches = (EventDetails details) -> details.getClientName() + ArgumentMatcher nameMatches = (EventDetails details) -> details.getDomain() .equals(name); verify(handler1, timeout(TIMEOUT).atLeastOnce()).accept(argThat(nameMatches)); verify(handler2, timeout(TIMEOUT).atLeastOnce()).accept(argThat(nameMatches)); @@ -337,7 +337,7 @@ void shouldSupportAllEventTypes() throws Exception { @Test @DisplayName("shutdown provider should not run handlers") - void shouldNotRunHandlers() throws Exception { + void shouldNotRunHandlers() { final Consumer handler1 = mockHandler(); final Consumer handler2 = mockHandler(); final String name = "shouldNotRunHandlers"; @@ -369,7 +369,7 @@ void shouldNotRunHandlers() throws Exception { @DisplayName("other client handlers should not run") @Specification(number = "5.1.3", text = "When a provider signals the occurrence of a particular event, " + "event handlers on clients which are not associated with that provider MUST NOT run.") - void otherClientHandlersShouldNotRun() throws Exception { + void otherClientHandlersShouldNotRun() { final String name1 = "otherClientHandlersShouldNotRun1"; final String name2 = "otherClientHandlersShouldNotRun2"; final Consumer handlerToRun = mockHandler(); @@ -396,7 +396,7 @@ void otherClientHandlersShouldNotRun() throws Exception { @DisplayName("bound named client handlers should not run with default") @Specification(number = "5.1.3", text = "When a provider signals the occurrence of a particular event, " + "event handlers on clients which are not associated with that provider MUST NOT run.") - void boundShouldNotRunWithDefault() throws Exception { + void boundShouldNotRunWithDefault() { final String name = "boundShouldNotRunWithDefault"; final Consumer handlerNotToRun = mockHandler(); @@ -422,7 +422,7 @@ void boundShouldNotRunWithDefault() throws Exception { @DisplayName("unbound named client handlers should run with default") @Specification(number = "5.1.3", text = "When a provider signals the occurrence of a particular event, " + "event handlers on clients which are not associated with that provider MUST NOT run.") - void unboundShouldRunWithDefault() throws Exception { + void unboundShouldRunWithDefault() { final String name = "unboundShouldRunWithDefault"; final Consumer handlerToRun = mockHandler(); @@ -445,7 +445,7 @@ void unboundShouldRunWithDefault() throws Exception { @Test @DisplayName("subsequent handlers run if earlier throws") @Specification(number = "5.2.5", text = "If a handler function terminates abnormally, other handler functions MUST run.") - void handlersRunIfOneThrows() throws Exception { + void handlersRunIfOneThrows() { final String name = "handlersRunIfOneThrows"; final Consumer errorHandler = mockHandler(); doThrow(new NullPointerException()).when(errorHandler).accept(any()); @@ -471,7 +471,7 @@ void handlersRunIfOneThrows() throws Exception { @DisplayName("should have all properties") @Specification(number = "5.2.4", text = "The handler function MUST accept a event details parameter.") @Specification(number = "5.2.3", text = "The `event details` MUST contain the `provider name` associated with the event.") - void shouldHaveAllProperties() throws Exception { + void shouldHaveAllProperties() { final Consumer handler1 = mockHandler(); final Consumer handler2 = mockHandler(); final String name = "shouldHaveAllProperties"; @@ -508,14 +508,14 @@ void shouldHaveAllProperties() throws Exception { return metadata.equals(eventDetails.getEventMetadata()) && flagsChanged.equals(eventDetails.getFlagsChanged()) && message.equals(eventDetails.getMessage()) - && name.equals(eventDetails.getClientName()); + && name.equals(eventDetails.getDomain()); })); } @Test @DisplayName("if the provider is ready handlers must run immediately") @Specification(number = "5.3.3", text = "Handlers attached after the provider is already in the associated state, MUST run immediately.") - void matchingReadyEventsMustRunImmediately() throws Exception { + void matchingReadyEventsMustRunImmediately() { final String name = "matchingEventsMustRunImmediately"; final Consumer handler = mockHandler(); @@ -532,7 +532,7 @@ void matchingReadyEventsMustRunImmediately() throws Exception { @Test @DisplayName("if the provider is ready handlers must run immediately") @Specification(number = "5.3.3", text = "Handlers attached after the provider is already in the associated state, MUST run immediately.") - void matchingStaleEventsMustRunImmediately() throws Exception { + void matchingStaleEventsMustRunImmediately() { final String name = "matchingEventsMustRunImmediately"; final Consumer handler = mockHandler(); @@ -549,7 +549,7 @@ void matchingStaleEventsMustRunImmediately() throws Exception { @Test @DisplayName("if the provider is ready handlers must run immediately") @Specification(number = "5.3.3", text = "Handlers attached after the provider is already in the associated state, MUST run immediately.") - void matchingErrorEventsMustRunImmediately() throws Exception { + void matchingErrorEventsMustRunImmediately() { final String name = "matchingEventsMustRunImmediately"; final Consumer handler = mockHandler(); @@ -566,7 +566,7 @@ void matchingErrorEventsMustRunImmediately() throws Exception { @Test @DisplayName("must persist across changes") @Specification(number = "5.2.6", text = "Event handlers MUST persist across provider changes.") - void mustPersistAcrossChanges() throws Exception { + void mustPersistAcrossChanges() { final String name = "mustPersistAcrossChanges"; final Consumer handler = mockHandler(); @@ -578,7 +578,7 @@ void mustPersistAcrossChanges() throws Exception { client.onProviderConfigurationChanged(handler); provider1.mockEvent(ProviderEvent.PROVIDER_CONFIGURATION_CHANGED, ProviderEventDetails.builder().build()); - ArgumentMatcher nameMatches = (EventDetails details) -> details.getClientName().equals(name); + ArgumentMatcher nameMatches = (EventDetails details) -> details.getDomain().equals(name); verify(handler, timeout(TIMEOUT).times(1)).accept(argThat(nameMatches)); diff --git a/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java b/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java index 60b6ee13..b2a7510e 100644 --- a/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java +++ b/src/test/java/dev/openfeature/sdk/FlagEvaluationSpecTest.java @@ -11,7 +11,9 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -135,10 +137,13 @@ public void initialize(EvaluationContext evaluationContext) throws Exception { assertEquals(h2, api.getHooks().get(1)); } - @Specification(number="1.1.6", text="The API MUST provide a function for creating a client which accepts the following options: - name (optional): A logical string identifier for the client.") - @Test void namedClient() { - assertThatCode(() -> api.getClient("Sir Calls-a-lot")).doesNotThrowAnyException(); - // TODO: Doesn't say that you can *get* the client name.. which seems useful? + @Specification(number="1.1.6", text="The API MUST provide a function for creating a client which accepts the following options: - domain (optional): A logical string identifier for binding clients to provider.") + @Test void domainName() { + assertNull(api.getClient().getMetadata().getDomain()); + + String domain = "Sir Calls-a-lot"; + Client clientForDomain = api.getClient(domain); + assertEquals(domain, clientForDomain.getMetadata().getDomain()); } @Specification(number="1.2.1", text="The client MUST provide a method to add hooks which accepts one or more API-conformant hooks, and appends them to the collection of any previously added hooks. When new hooks are added, previously added hooks are not removed.") @@ -274,14 +279,18 @@ public void initialize(EvaluationContext evaluationContext) throws Exception { ArgumentMatchers.isA(FlagNotFoundError.class)); } - @Specification(number="1.2.2", text="The client interface MUST define a metadata member or accessor, containing an immutable name field or accessor of type string, which corresponds to the name value supplied during client creation.") + @Specification(number="1.2.2", text="The client interface MUST define a metadata member or accessor, containing an immutable domain field or accessor of type string, which corresponds to the domain value supplied during client creation. In previous drafts, this property was called name. For backwards compatibility, implementations should consider name an alias to domain.") @Test void clientMetadata() { Client c = _client(); assertNull(c.getMetadata().getName()); + assertNull(c.getMetadata().getDomain()); + String domainName = "test domain"; FeatureProviderTestUtils.setFeatureProvider(new AlwaysBrokenProvider()); - Client c2 = api.getClient("test"); - assertEquals("test", c2.getMetadata().getName()); + Client c2 = api.getClient(domainName); + + assertEquals(domainName, c2.getMetadata().getName()); + assertEquals(domainName, c2.getMetadata().getDomain()); } @Specification(number="1.4.9", text="In cases of abnormal execution (network failure, unhandled error, etc) the reason field in the evaluation details SHOULD indicate an error.") @@ -300,11 +309,30 @@ public void initialize(EvaluationContext evaluationContext) throws Exception { assertNotNull(result.getFlagMetadata()); } - @Specification(number="3.2.1.1", text="The API, Client and invocation MUST have a method for supplying evaluation context.") @Specification(number="3.2.2.1", text="The API MUST have a method for setting the global evaluation context.") + @Test void api_context() { + String contextKey = "some-key"; + String contextValue = "some-value"; + DoSomethingProvider provider = spy( new DoSomethingProvider()); + FeatureProviderTestUtils.setFeatureProvider(provider); + + Map attributes = new HashMap<>(); + attributes.put(contextKey, new Value(contextValue)); + EvaluationContext apiCtx = new ImmutableContext(attributes); + + // set the global context + api.setEvaluationContext(apiCtx); + Client client = api.getClient(); + client.getBooleanValue("any-flag", false); + + // assert that the value from the global context was passed to the provider + verify(provider).getBooleanEvaluation(any(), any(), argThat((arg) -> arg.getValue(contextKey).asString().equals(contextValue))); + } + + @Specification(number="3.2.1.1", text="The API, Client and invocation MUST have a method for supplying evaluation context.") @Specification(number="3.2.3", text="Evaluation context MUST be merged in the order: API (global; lowest precedence) -> transaction -> client -> invocation -> before hooks (highest precedence), with duplicate values being overwritten.") @Test void multi_layer_context_merges_correctly() { - DoSomethingProvider provider = new DoSomethingProvider(); + DoSomethingProvider provider = spy(new DoSomethingProvider()); FeatureProviderTestUtils.setFeatureProvider(provider); TransactionContextPropagator transactionContextPropagator = new ThreadLocalTransactionContextPropagator(); api.setTransactionContextPropagator(transactionContextPropagator); @@ -349,21 +377,21 @@ public void initialize(EvaluationContext evaluationContext) throws Exception { invocationAttributes.put("invocation", new Value("4")); EvaluationContext invocationCtx = new ImmutableContext(invocationAttributes); - // dosomethingprovider inverts this value. - assertTrue(c.getBooleanValue("key", false, invocationCtx)); - - EvaluationContext merged = provider.getMergedContext(); - assertEquals("1", merged.getValue("api").asString()); - assertEquals("2", merged.getValue("transaction").asString()); - assertEquals("3", merged.getValue("client").asString()); - assertEquals("4", merged.getValue("invocation").asString()); - assertEquals("2", merged.getValue("common1").asString(), "transaction merge is incorrect"); - assertEquals("3", merged.getValue("common2").asString(), "api client merge is incorrect"); - assertEquals("4", merged.getValue("common3").asString(), "invocation merge is incorrect"); - assertEquals("3", merged.getValue("common4").asString(), "api client merge is incorrect"); - assertEquals("4", merged.getValue("common5").asString(), "invocation merge is incorrect"); - assertEquals("4", merged.getValue("common6").asString(), "invocation merge is incorrect"); - + c.getBooleanValue("key", false, invocationCtx); + + // assert the connect overrides + verify(provider).getBooleanEvaluation(any(), any(), argThat((arg) -> { + return arg.getValue("api").asString().equals("1") && + arg.getValue("transaction").asString().equals("2") && + arg.getValue("client").asString().equals("3") && + arg.getValue("invocation").asString().equals("4") && + arg.getValue("common1").asString().equals("2") && + arg.getValue("common2").asString().equals("3") && + arg.getValue("common3").asString().equals("4") && + arg.getValue("common4").asString().equals("3") && + arg.getValue("common5").asString().equals("4") && + arg.getValue("common6").asString().equals("4"); + })); } @Specification(number="3.3.1.1", text="The API SHOULD have a method for setting a transaction context propagator.") diff --git a/src/test/java/dev/openfeature/sdk/HookContextTest.java b/src/test/java/dev/openfeature/sdk/HookContextTest.java index 763069fd..50cc6617 100644 --- a/src/test/java/dev/openfeature/sdk/HookContextTest.java +++ b/src/test/java/dev/openfeature/sdk/HookContextTest.java @@ -9,17 +9,18 @@ class HookContextTest { @Specification(number="4.2.2.2", text="Condition: The client metadata field in the hook context MUST be immutable.") @Specification(number="4.2.2.3", text="Condition: The provider metadata field in the hook context MUST be immutable.") @Test void metadata_field_is_type_metadata() { + ClientMetadata clientMetadata = mock(ClientMetadata.class); Metadata meta = mock(Metadata.class); HookContext hc = HookContext.from( "key", FlagValueType.BOOLEAN, - meta, + clientMetadata, meta, new ImmutableContext(), false ); - assertTrue(Metadata.class.isAssignableFrom(hc.getClientMetadata().getClass())); + assertTrue(ClientMetadata.class.isAssignableFrom(hc.getClientMetadata().getClass())); assertTrue(Metadata.class.isAssignableFrom(hc.getProviderMetadata().getClass())); } diff --git a/src/test/java/dev/openfeature/sdk/HookSpecTest.java b/src/test/java/dev/openfeature/sdk/HookSpecTest.java index d0e173b2..098d80d7 100644 --- a/src/test/java/dev/openfeature/sdk/HookSpecTest.java +++ b/src/test/java/dev/openfeature/sdk/HookSpecTest.java @@ -1,5 +1,6 @@ package dev.openfeature.sdk; +import dev.openfeature.sdk.exceptions.FlagNotFoundError; import dev.openfeature.sdk.fixtures.HookFixtures; import dev.openfeature.sdk.testutils.FeatureProviderTestUtils; import lombok.SneakyThrows; @@ -19,12 +20,14 @@ import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.fail; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -180,6 +183,40 @@ void emptyApiHooks() { verify(h, times(0)).error(any(), any(), any()); } + + @Test void error_hook_must_run_if_resolution_details_returns_an_error_code() { + + String errorMessage = "not found..."; + + EvaluationContext invocationCtx = new ImmutableContext(); + Hook hook = mockBooleanHook(); + FeatureProvider provider = mock(FeatureProvider.class); + when(provider.getBooleanEvaluation(any(), any(), any())).thenReturn(ProviderEvaluation.builder() + .errorCode(ErrorCode.FLAG_NOT_FOUND) + .errorMessage(errorMessage) + .build()); + + OpenFeatureAPI api = OpenFeatureAPI.getInstance(); + FeatureProviderTestUtils.setFeatureProvider(provider); + Client client = api.getClient(); + client.getBooleanValue("key", false, invocationCtx, + FlagEvaluationOptions.builder() + .hook(hook) + .build()); + + ArgumentCaptor captor = ArgumentCaptor.forClass(Exception.class); + + verify(hook, times(1)).before(any(), any()); + verify(hook, times(1)).error(any(), captor.capture(), any()); + verify(hook, times(1)).finallyAfter(any(), any()); + verify(hook, never()).after(any(),any(), any()); + + Exception exception = captor.getValue(); + assertEquals(errorMessage, exception.getMessage()); + assertInstanceOf(FlagNotFoundError.class, exception); + } + + @Specification(number="4.3.6", text="The after stage MUST run after flag resolution occurs. It accepts a hook context (required), flag evaluation details (required) and hook hints (optional). It has no return value.") @Specification(number="4.3.7", text="The error hook MUST run when errors are encountered in the before stage, the after stage or during flag resolution. It accepts hook context (required), exception representing what went wrong (required), and hook hints (optional). It has no return value.") @Specification(number="4.3.8", text="The finally hook MUST run after the before, after, and error stages. It accepts a hook context (required) and hook hints (optional). There is no return value.") diff --git a/src/test/java/dev/openfeature/sdk/HookSupportTest.java b/src/test/java/dev/openfeature/sdk/HookSupportTest.java index d8883780..bf6501dd 100644 --- a/src/test/java/dev/openfeature/sdk/HookSupportTest.java +++ b/src/test/java/dev/openfeature/sdk/HookSupportTest.java @@ -19,7 +19,6 @@ import dev.openfeature.sdk.fixtures.HookFixtures; class HookSupportTest implements HookFixtures { - @Test @DisplayName("should merge EvaluationContexts on before hooks correctly") void shouldMergeEvaluationContextsOnBeforeHooksCorrectly() { diff --git a/src/test/java/dev/openfeature/sdk/InitializeBehaviorSpecTest.java b/src/test/java/dev/openfeature/sdk/InitializeBehaviorSpecTest.java index 270ac77e..4d0599a7 100644 --- a/src/test/java/dev/openfeature/sdk/InitializeBehaviorSpecTest.java +++ b/src/test/java/dev/openfeature/sdk/InitializeBehaviorSpecTest.java @@ -8,6 +8,8 @@ class InitializeBehaviorSpecTest { + private static final String DOMAIN_NAME = "mydomain"; + @BeforeEach void setupTest() { OpenFeatureAPI.getInstance().setProvider(new NoOpProvider()); @@ -60,7 +62,7 @@ void mustCallInitializeFunctionOfTheNewlyRegisteredNamedProviderBeforeUsingItFor FeatureProvider featureProvider = mock(FeatureProvider.class); doReturn(ProviderState.NOT_READY).when(featureProvider).getState(); - OpenFeatureAPI.getInstance().setProvider("clientName", featureProvider); + OpenFeatureAPI.getInstance().setProvider(DOMAIN_NAME, featureProvider); verify(featureProvider, timeout(1000)).initialize(any()); } @@ -76,7 +78,7 @@ void shouldCatchExceptionThrownByTheNamedClientProviderOnInitialization() throws doReturn(ProviderState.NOT_READY).when(featureProvider).getState(); doThrow(TestException.class).when(featureProvider).initialize(any()); - assertThatCode(() -> OpenFeatureAPI.getInstance().setProvider("clientName", featureProvider)) + assertThatCode(() -> OpenFeatureAPI.getInstance().setProvider(DOMAIN_NAME, featureProvider)) .doesNotThrowAnyException(); verify(featureProvider, timeout(1000)).initialize(any()); diff --git a/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java b/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java index eceace2b..74298f72 100644 --- a/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java +++ b/src/test/java/dev/openfeature/sdk/OpenFeatureAPITest.java @@ -15,7 +15,7 @@ class OpenFeatureAPITest { - private static final String CLIENT_NAME = "client name"; + private static final String DOMAIN_NAME = "my domain"; private OpenFeatureAPI api; @@ -33,16 +33,16 @@ void namedProviderTest() { .isEqualTo(api.getProviderMetadata("namedProviderTest").getName()); } - @Specification(number="1.1.3", text="The API MUST provide a function to bind a given provider to one or more client names. If the client-name already has a bound provider, it is overwritten with the new mapping.") + @Specification(number="1.1.3", text="The API MUST provide a function to bind a given provider to one or more clients using a domain. If the domain already has a bound provider, it is overwritten with the new mapping.") @Test void namedProviderOverwrittenTest() { - String name = "namedProviderOverwrittenTest"; + String domain = "namedProviderOverwrittenTest"; FeatureProvider provider1 = new NoOpProvider(); FeatureProvider provider2 = new DoSomethingProvider(); - FeatureProviderTestUtils.setFeatureProvider(name, provider1); - FeatureProviderTestUtils.setFeatureProvider(name, provider2); + FeatureProviderTestUtils.setFeatureProvider(domain, provider1); + FeatureProviderTestUtils.setFeatureProvider(domain, provider2); - assertThat(OpenFeatureAPI.getInstance().getProvider(name).getMetadata().getName()) + assertThat(OpenFeatureAPI.getInstance().getProvider(domain).getMetadata().getName()) .isEqualTo(DoSomethingProvider.name); } @@ -71,8 +71,8 @@ void settingDefaultProviderToNullErrors() { } @Test - void settingNamedClientProviderToNullErrors() { - assertThatCode(() -> api.setProvider(CLIENT_NAME, null)).isInstanceOf(IllegalArgumentException.class); + void settingDomainProviderToNullErrors() { + assertThatCode(() -> api.setProvider(DOMAIN_NAME, null)).isInstanceOf(IllegalArgumentException.class); } @Test diff --git a/src/test/java/dev/openfeature/sdk/ProviderRepositoryTest.java b/src/test/java/dev/openfeature/sdk/ProviderRepositoryTest.java index 20da47ed..c827c91f 100644 --- a/src/test/java/dev/openfeature/sdk/ProviderRepositoryTest.java +++ b/src/test/java/dev/openfeature/sdk/ProviderRepositoryTest.java @@ -33,8 +33,8 @@ class ProviderRepositoryTest { - private static final String CLIENT_NAME = "client name"; - private static final String ANOTHER_CLIENT_NAME = "another client name"; + private static final String DOMAIN_NAME = "domain name"; + private static final String ANOTHER_DOMAIN_NAME = "another domain name"; private static final int TIMEOUT = 5000; private final ExecutorService executorService = Executors.newCachedThreadPool(); @@ -101,13 +101,13 @@ class NamedProvider { @Test @DisplayName("should reject null as named provider") void shouldRejectNullAsNamedProvider() { - assertThatCode(() -> providerRepository.setProvider(CLIENT_NAME, null, mockAfterSet(), mockAfterInit(), + assertThatCode(() -> providerRepository.setProvider(DOMAIN_NAME, null, mockAfterSet(), mockAfterInit(), mockAfterShutdown(), mockAfterError(), false)) .isInstanceOf(IllegalArgumentException.class); } @Test - @DisplayName("should reject null as client name") + @DisplayName("should reject null as domain name") void shouldRejectNullAsDefaultProvider() { NoOpProvider provider = new NoOpProvider(); assertThatCode(() -> providerRepository.setProvider(null, provider, mockAfterSet(), mockAfterInit(), @@ -116,8 +116,8 @@ void shouldRejectNullAsDefaultProvider() { } @Test - @DisplayName("should immediately return when calling the named client provider mutator") - void shouldImmediatelyReturnWhenCallingTheNamedClientProviderMutator() throws Exception { + @DisplayName("should immediately return when calling the domain provider mutator") + void shouldImmediatelyReturnWhenCallingTheDomainProviderMutator() throws Exception { FeatureProvider featureProvider = createMockedProvider(); doDelayResponse(Duration.ofSeconds(10)).when(featureProvider).initialize(any()); @@ -126,7 +126,7 @@ void shouldImmediatelyReturnWhenCallingTheNamedClientProviderMutator() throws Ex .pollDelay(Duration.ofMillis(1)) .atMost(Duration.ofSeconds(1)) .until(() -> { - providerRepository.setProvider("named client", featureProvider, mockAfterSet(), + providerRepository.setProvider("a domain", featureProvider, mockAfterSet(), mockAfterInit(), mockAfterShutdown(), mockAfterError(), false); verify(featureProvider, timeout(TIMEOUT)).initialize(any()); return true; @@ -137,7 +137,7 @@ void shouldImmediatelyReturnWhenCallingTheNamedClientProviderMutator() throws Ex @DisplayName("should avoid additional initialization call if provider has been initialized already") void shouldAvoidAdditionalInitializationCallIfProviderHasBeenInitializedAlready() throws Exception { FeatureProvider provider = createMockedReadyProvider(); - setFeatureProvider(CLIENT_NAME, provider); + setFeatureProvider(DOMAIN_NAME, provider); verify(provider, never()).initialize(any()); } @@ -176,7 +176,7 @@ void shouldNotCallShutdownIfReplacedDefaultProviderIsBoundAsNamedProvider() { FeatureProvider oldProvider = createMockedProvider(); FeatureProvider newProvider = createMockedProvider(); setFeatureProvider(oldProvider); - setFeatureProvider(CLIENT_NAME, oldProvider); + setFeatureProvider(DOMAIN_NAME, oldProvider); setFeatureProvider(newProvider); @@ -194,7 +194,7 @@ void shouldImmediatelyReturnWhenCallingTheProviderMutator() throws Exception { doDelayResponse(Duration.ofSeconds(10)).when(newProvider).initialize(any()); Future providerMutation = executorService - .submit(() -> providerRepository.setProvider(CLIENT_NAME, newProvider, mockAfterSet(), + .submit(() -> providerRepository.setProvider(DOMAIN_NAME, newProvider, mockAfterSet(), mockAfterInit(), mockAfterShutdown(), mockAfterError(), false)); await() @@ -209,11 +209,11 @@ void shouldImmediatelyReturnWhenCallingTheProviderMutator() throws Exception { void shouldNotCallShutdownIfReplacedProviderIsBoundToMultipleNames() throws InterruptedException { FeatureProvider oldProvider = createMockedProvider(); FeatureProvider newProvider = createMockedProvider(); - setFeatureProvider(CLIENT_NAME, oldProvider); + setFeatureProvider(DOMAIN_NAME, oldProvider); - setFeatureProvider(ANOTHER_CLIENT_NAME, oldProvider); + setFeatureProvider(ANOTHER_DOMAIN_NAME, oldProvider); - setFeatureProvider(CLIENT_NAME, newProvider); + setFeatureProvider(DOMAIN_NAME, newProvider); verify(oldProvider, never()).shutdown(); } @@ -224,9 +224,9 @@ void shouldNotCallShutdownIfReplacedProviderIsBoundAsDefaultProvider() { FeatureProvider oldProvider = createMockedProvider(); FeatureProvider newProvider = createMockedProvider(); setFeatureProvider(oldProvider); - setFeatureProvider(CLIENT_NAME, oldProvider); + setFeatureProvider(DOMAIN_NAME, oldProvider); - setFeatureProvider(CLIENT_NAME, newProvider); + setFeatureProvider(DOMAIN_NAME, newProvider); verify(oldProvider, never()).shutdown(); } @@ -293,8 +293,8 @@ void shouldShutdownAllFeatureProvidersOnShutdown() { FeatureProvider featureProvider2 = createMockedProvider(); setFeatureProvider(featureProvider1); - setFeatureProvider(CLIENT_NAME, featureProvider1); - setFeatureProvider(ANOTHER_CLIENT_NAME, featureProvider2); + setFeatureProvider(DOMAIN_NAME, featureProvider1); + setFeatureProvider(ANOTHER_DOMAIN_NAME, featureProvider2); providerRepository.shutdown(); verify(featureProvider1, timeout(TIMEOUT)).shutdown(); diff --git a/src/test/java/dev/openfeature/sdk/ShutdownBehaviorSpecTest.java b/src/test/java/dev/openfeature/sdk/ShutdownBehaviorSpecTest.java index b0a0a9d1..bc2dc0ea 100644 --- a/src/test/java/dev/openfeature/sdk/ShutdownBehaviorSpecTest.java +++ b/src/test/java/dev/openfeature/sdk/ShutdownBehaviorSpecTest.java @@ -15,6 +15,8 @@ class ShutdownBehaviorSpecTest { + private String DOMAIN = "myDomain"; + @BeforeEach void resetFeatureProvider() { setFeatureProvider(new NoOpProvider()); @@ -59,11 +61,10 @@ class NamedProvider { @Test @DisplayName("must invoke shutdown method on previously registered provider once it should not be used for flag evaluation anymore") void mustInvokeShutdownMethodOnPreviouslyRegisteredProviderOnceItShouldNotBeUsedForFlagEvaluationAnymore() { - String clientName = "clientName"; FeatureProvider featureProvider = ProviderFixture.createMockedProvider(); - setFeatureProvider(clientName, featureProvider); - setFeatureProvider(clientName, new NoOpProvider()); + setFeatureProvider(DOMAIN, featureProvider); + setFeatureProvider(DOMAIN, new NoOpProvider()); verify(featureProvider, timeout(1000)).shutdown(); } @@ -75,12 +76,11 @@ void mustInvokeShutdownMethodOnPreviouslyRegisteredProviderOnceItShouldNotBeUsed @Test @DisplayName("should catch exception thrown by the named client provider on shutdown") void shouldCatchExceptionThrownByTheNamedClientProviderOnShutdown() { - String clientName = "clientName"; FeatureProvider featureProvider = ProviderFixture.createMockedProvider(); doThrow(TestException.class).when(featureProvider).shutdown(); - setFeatureProvider(clientName, featureProvider); - setFeatureProvider(clientName, new NoOpProvider()); + setFeatureProvider(DOMAIN, featureProvider); + setFeatureProvider(DOMAIN, new NoOpProvider()); verify(featureProvider, timeout(1000)).shutdown(); } @@ -96,7 +96,7 @@ void mustShutdownAllProvidersOnShuttingDownApi() { FeatureProvider defaultProvider = ProviderFixture.createMockedProvider(); FeatureProvider namedProvider = ProviderFixture.createMockedProvider(); setFeatureProvider(defaultProvider); - setFeatureProvider("clientName", namedProvider); + setFeatureProvider(DOMAIN, namedProvider); OpenFeatureAPI api = OpenFeatureAPI.getInstance(); synchronized (OpenFeatureAPI.class) { diff --git a/src/test/java/dev/openfeature/sdk/exceptions/ExceptionUtilsTest.java b/src/test/java/dev/openfeature/sdk/exceptions/ExceptionUtilsTest.java new file mode 100644 index 00000000..58e59457 --- /dev/null +++ b/src/test/java/dev/openfeature/sdk/exceptions/ExceptionUtilsTest.java @@ -0,0 +1,45 @@ +package dev.openfeature.sdk.exceptions; + +import dev.openfeature.sdk.ErrorCode; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.ArgumentsProvider; +import org.junit.jupiter.params.provider.ArgumentsSource; + +import java.util.stream.Stream; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; + +class ExceptionUtilsTest { + + @ParameterizedTest + @DisplayName("should produce correct exception for a provided ErrorCode") + @ArgumentsSource(ErrorCodeTestParameters.class) + void shouldProduceCorrectExceptionForErrorCode(ErrorCode errorCode, Class exception) { + + String errorMessage = "error message"; + OpenFeatureError openFeatureError = ExceptionUtils.instantiateErrorByErrorCode(errorCode, errorMessage); + assertInstanceOf(exception, openFeatureError); + assertThat(openFeatureError.getMessage()).isEqualTo(errorMessage); + assertThat(openFeatureError.getErrorCode()).isEqualByComparingTo(errorCode); + } + + static class ErrorCodeTestParameters implements ArgumentsProvider { + + @Override + public Stream provideArguments(ExtensionContext context) { + return Stream.of( + Arguments.of(ErrorCode.GENERAL, GeneralError.class), + Arguments.of(ErrorCode.FLAG_NOT_FOUND, FlagNotFoundError.class), + Arguments.of(ErrorCode.PROVIDER_NOT_READY, ProviderNotReadyError.class), + Arguments.of(ErrorCode.INVALID_CONTEXT, InvalidContextError.class), + Arguments.of(ErrorCode.PARSE_ERROR, ParseError.class), + Arguments.of(ErrorCode.TARGETING_KEY_MISSING, TargetingKeyMissingError.class), + Arguments.of(ErrorCode.TYPE_MISMATCH, TypeMismatchError.class) + ); + } + } +} diff --git a/src/test/java/dev/openfeature/sdk/testutils/FeatureProviderTestUtils.java b/src/test/java/dev/openfeature/sdk/testutils/FeatureProviderTestUtils.java index b3fc898e..41ffbe18 100644 --- a/src/test/java/dev/openfeature/sdk/testutils/FeatureProviderTestUtils.java +++ b/src/test/java/dev/openfeature/sdk/testutils/FeatureProviderTestUtils.java @@ -24,8 +24,8 @@ private static void waitForProviderInitializationComplete(Function extractor.apply(OpenFeatureAPI.getInstance()) == provider); } - public static void setFeatureProvider(String namedProvider, FeatureProvider provider) { - OpenFeatureAPI.getInstance().setProvider(namedProvider, provider); - waitForProviderInitializationComplete(api -> api.getProvider(namedProvider), provider); + public static void setFeatureProvider(String domain, FeatureProvider provider) { + OpenFeatureAPI.getInstance().setProvider(domain, provider); + waitForProviderInitializationComplete(api -> api.getProvider(domain), provider); } } diff --git a/src/test/java/dev/openfeature/sdk/testutils/TestEventsProvider.java b/src/test/java/dev/openfeature/sdk/testutils/TestEventsProvider.java index b0e5eb78..0b19f82a 100644 --- a/src/test/java/dev/openfeature/sdk/testutils/TestEventsProvider.java +++ b/src/test/java/dev/openfeature/sdk/testutils/TestEventsProvider.java @@ -18,12 +18,7 @@ public class TestEventsProvider extends EventProvider { private boolean shutDown = false; private int initTimeoutMs = 0; private String name = "test"; - private Metadata metadata = new Metadata() { - @Override - public String getName() { - return name; - } - }; + private Metadata metadata = () -> name; @Override public ProviderState getState() { diff --git a/version.txt b/version.txt index 27f9cd32..f8e233b2 100644 --- a/version.txt +++ b/version.txt @@ -1 +1 @@ -1.8.0 +1.9.0