From 973fb07df889fb22a9177be3fc80df691bafccb4 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 19:53:49 +0100 Subject: [PATCH 01/21] feat: add schemas package and datafile sections for modules Datafiles can carry sections beside the SDK's own keys, such as schemas. The SDK now keeps them through every replace and merge, merging a section by entry as segments merge, and datafile_set details list the changed entries of each section. The module API gains getEntry, getEntryKeys and matchConditions. The last answers a package's conditions, as JSON text or trees, with the instance's engine, in one dependency session whose root is the package's entry, and reads leaves only the package knows, such as input, through readers that tell an absent value from null. VariableMutations.applyVariableOperations, Conditions.getPortableTimestamp and CompareVersions.isValidVersion are public for such packages. The new featurevisor-schemas Maven module, com.featurevisor.schemas, validates data against those schemas with the rules, messages, mutations and issues of @featurevisor/schemas, and describes fields for forms through handles, with checks in code and option sources. The artifact check verifies its JAR and POM. It passes the 85 cases of conformance/schemas-validation.json twice and matches the JavaScript package on a datafile the CLI built, issues, messages and handle members included. A schema that references itself follows the value, and one that loops fails closed after 128 nested references with schema_reference_depth. --- README.md | 90 + conformance/schemas-validation.json | 2598 +++++++++++++++++ conformance/sdk-sections.json | 941 ++++++ featurevisor-schemas/pom.xml | 78 + .../com/featurevisor/schemas/CheckInfo.java | 36 + .../com/featurevisor/schemas/Derived.java | 244 ++ .../java/com/featurevisor/schemas/Engine.java | 739 +++++ .../schemas/FieldConstraints.java | 69 + .../com/featurevisor/schemas/FieldKind.java | 24 + .../featurevisor/schemas/FlattenedIssues.java | 35 + .../featurevisor/schemas/HandleOptions.java | 61 + .../featurevisor/schemas/IssueTranslator.java | 7 + .../java/com/featurevisor/schemas/Json.java | 253 ++ .../com/featurevisor/schemas/MessageInfo.java | 20 + .../com/featurevisor/schemas/Messages.java | 229 ++ .../featurevisor/schemas/OptionSource.java | 113 + .../java/com/featurevisor/schemas/Paths.java | 138 + .../com/featurevisor/schemas/Patterns.java | 139 + .../com/featurevisor/schemas/Position.java | 18 + .../com/featurevisor/schemas/Refinement.java | 87 + .../com/featurevisor/schemas/Resolver.java | 35 + .../java/com/featurevisor/schemas/Run.java | 44 + .../featurevisor/schemas/SchemaHandle.java | 729 +++++ .../com/featurevisor/schemas/SchemaIssue.java | 70 + .../featurevisor/schemas/SchemaMessage.java | 9 + .../featurevisor/schemas/SchemaOption.java | 48 + .../schemas/SchemaValidationException.java | 24 + .../com/featurevisor/schemas/Schemas.java | 115 + .../featurevisor/schemas/SchemasOptions.java | 36 + .../java/com/featurevisor/schemas/Store.java | 335 +++ .../schemas/ValidationResult.java | 31 + .../com/featurevisor/schemas/Validator.java | 9 + .../java/com/featurevisor/schemas/Views.java | 163 ++ .../schemas/BuiltDatafileTest.java | 142 + .../schemas/SchemasConformanceTest.java | 108 + .../com/featurevisor/schemas/SchemasTest.java | 311 ++ .../resources/built-datafile-expected.json | 548 ++++ .../src/test/resources/built-datafile.json | 1 + .../com/featurevisor/sdk/CompareVersions.java | 11 + .../com/featurevisor/sdk/ConditionReader.java | 20 + .../java/com/featurevisor/sdk/Conditions.java | 10 + .../com/featurevisor/sdk/DatafileContent.java | 59 + .../com/featurevisor/sdk/DependencyOf.java | 18 +- .../java/com/featurevisor/sdk/Evaluate.java | 49 +- .../com/featurevisor/sdk/EvaluateOptions.java | 5 + .../java/com/featurevisor/sdk/Events.java | 36 + .../com/featurevisor/sdk/Featurevisor.java | 69 + .../sdk/FeaturevisorModuleApi.java | 37 + .../sdk/InstanceEvaluationDataProvider.java | 9 + .../sdk/MatchConditionsOptions.java | 33 + .../featurevisor/sdk/VariableMutations.java | 22 +- .../sdk/ModuleConditionsTest.java | 113 + .../sdk/SectionsConformanceTest.java | 142 + .../sdk/StatefulConformanceTest.java | 5 +- pom.xml | 3 +- scripts/verify-artifacts.sh | 28 +- 56 files changed, 9334 insertions(+), 12 deletions(-) create mode 100644 conformance/schemas-validation.json create mode 100644 conformance/sdk-sections.json create mode 100644 featurevisor-schemas/pom.xml create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/CheckInfo.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldConstraints.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/FlattenedIssues.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/IssueTranslator.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Json.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/MessageInfo.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Messages.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/OptionSource.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Refinement.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaIssue.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaMessage.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaOption.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaValidationException.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemasOptions.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/ValidationResult.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Validator.java create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java create mode 100644 featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java create mode 100644 featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java create mode 100644 featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java create mode 100644 featurevisor-schemas/src/test/resources/built-datafile-expected.json create mode 100644 featurevisor-schemas/src/test/resources/built-datafile.json create mode 100644 featurevisor-sdk/src/main/java/com/featurevisor/sdk/ConditionReader.java create mode 100644 featurevisor-sdk/src/main/java/com/featurevisor/sdk/MatchConditionsOptions.java create mode 100644 featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java create mode 100644 featurevisor-sdk/src/test/java/com/featurevisor/sdk/SectionsConformanceTest.java diff --git a/README.md b/README.md index a8589d0..f98ca59 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,10 @@ Use the Featurevisor Java SDK to evaluate flags, variations and variables in Jav - [Child instance](#child-instance) - [Close](#close) - [OpenFeature](#openfeature) +- [Schemas](#schemas) + - [Handles](#handles) + - [Messages](#messages) + - [Checks in code](#checks-in-code) - [CLI usage](#cli-usage) - [Test](#test) - [Benchmark](#benchmark) @@ -805,6 +809,8 @@ FeaturevisorModule myCustomModule = new FeaturevisorModule("my-custom-module") }); ``` +The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `getEntry(section, key)` returns an entry as stored, so treat it as read only, and `getEntryKeys(section)` lists a section's keys. `matchConditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `MatchConditionsOptions.reader` answers leaves only the package knows, such as `input`. This is how the [schemas](#schemas) artifact reads its schemas. + ### Registering modules Register modules when you create the instance: @@ -953,6 +959,90 @@ Composed values map to `TARGETING_MATCH` without additional JSON decoding. Unmet See the [OpenFeature provider guide](https://featurevisor.com/docs/sdks/openfeature/) for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages. +## Schemas + +Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/) a datafile carries, such as a sign up form's request, with the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. They are published as a separate artifact, with the same version as the Featurevisor Java SDK: + +```xml + + com.featurevisor + featurevisor-schemas + 5.0.0 + +``` + +Create one `Schemas` instance per Featurevisor instance, and validate by a schema's key: + +```java +import com.featurevisor.schemas.Schemas; +import com.featurevisor.schemas.SchemaIssue; +import com.featurevisor.schemas.ValidationResult; + +Schemas schemas = Schemas.create(f); + +ValidationResult result = schemas.validate("signUp", request); + +if (!result.isValid()) { + for (SchemaIssue issue : result.getIssues()) { + System.out.println(issue.getField() + ": " + issue.getMessage()); + } +} +``` + +A value can be maps, lists, strings, numbers, booleans and `null`, a Jackson `JsonNode`, or any object Jackson can convert, such as a request class with getters. `parse` returns the value when it passes and throws a `SchemaValidationException` with the issues when it does not. `flatten()` on a result or an exception groups the messages by field name, such as `displayName` or `items.0.name`, for an error response. + +Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. + +### Handles + +`schemas.get(key)` returns a schema's handle, and `at(path)` a field's, such as `address.city` or `items[].name`. A handle describes what its rules imply for rendering a form: + +```java +SchemaHandle signUp = schemas.get("signUp"); + +signUp.getFieldKeys(); // [accountType, displayName, taxId], in the schema's order +signUp.at("displayName").getConstraints(); // required, minLength and maxLength +signUp.at("accountType").getOptions(); // personal and business, with their titles +signUp.at("accountType").getKind(); // FieldKind.SELECT +``` + +`getConstraints().toAttributes()` gives them as HTML attributes, such as `required` and `maxlength`. `withInput(values)` returns the same handle for the values a form has so far, so its members describe the rules every matching mutation sets, such as a VAT number that becomes required for a business account. + +### Messages + +Issues are worded by the form's messages, then the schema's, then the application's, then a default in English: + +```java +Schemas schemas = Schemas.create(f, new SchemasOptions() + .message("required", "{title} is required") + .translator((issue, info) -> translations.get(issue.getCode()))); +``` + +A translator returning `null` keeps the chosen message. + +### Checks in code + +Refinements check what rules cannot express, and option sources check a value against choices from the application. Both run after the rules, only where the rules found nothing: + +```java +SchemaHandle signUp = schemas.get("signUp", new HandleOptions() + .refine( + Refinement.of("passwordsMatch", "confirmPassword", + (value, info) -> value.equals(info.read("password"))) + .reads("password") + .message("Passwords must match"), + Refinement.async("usernameFree", "username", + (value, info) -> users.isFreeAsync((String) value))) + .optionSource( + OptionSource.of("cities", "city") + .search((query, info) -> cities.search(query)) + .lookup((value, info) -> cities.find((String) value)))); +``` + +`validate` waits for checks that answer later, and `validateAsync` returns a `CompletableFuture` instead. A lookup that finds nothing reports `enum`, and a check that throws reports `refineError`. `search(query)` on the field's handle returns the source's suggestions. + +Handles are safe to share between threads. `close()` on the instance stops its subscriptions and removes its module from the Featurevisor instance. + ## CLI usage Compile the CLI module from this SDK repository: diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json new file mode 100644 index 0000000..d1d6b64 --- /dev/null +++ b/conformance/schemas-validation.json @@ -0,0 +1,2598 @@ +{ + "kind": "featurevisor.schemas-validation", + "schemaVersion": 2, + "cases": [ + { + "name": "a string passes type string", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string" + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "a number fails type string", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string" + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "integer rejects a fraction", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer" + } + }, + "schema": "subject", + "value": 1.5, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "integer", + "received": "number" + } + } + ] + }, + { + "name": "integer takes a whole number written with a decimal point", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer" + } + }, + "schema": "subject", + "value": 2.0, + "issues": [] + }, + { + "name": "number takes an integer", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number" + } + }, + "schema": "subject", + "value": 3, + "issues": [] + }, + { + "name": "boolean rejects the string true", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "boolean" + } + }, + "schema": "subject", + "value": "true", + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "boolean", + "received": "string" + } + } + ] + }, + { + "name": "null is not an object", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": null, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "object", + "received": "null" + } + } + ] + }, + { + "name": "an array is not an object", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": [], + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "object", + "received": "array" + } + } + ] + }, + { + "name": "an object is not an array", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array" + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "array", + "received": "object" + } + } + ] + }, + { + "name": "a type issue stops the node's other keywords", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "minLength": 5 + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "const rejects another value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "const": "GB" + } + }, + "schema": "subject", + "value": "NL", + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": "GB" + } + } + ] + }, + { + "name": "const null takes null", + "schemas": { + "subject": { + "hash": "subject-1", + "const": null + } + }, + "schema": "subject", + "value": null, + "issues": [] + }, + { + "name": "const compares objects by value, in any key order", + "schemas": { + "subject": { + "hash": "subject-1", + "const": { + "a": 1, + "b": [ + 1, + 2 + ] + } + } + }, + "schema": "subject", + "value": { + "b": [ + 1, + 2 + ], + "a": 1 + }, + "issues": [] + }, + { + "name": "const compares arrays in order", + "schemas": { + "subject": { + "hash": "subject-1", + "const": [ + 1, + 2 + ] + } + }, + "schema": "subject", + "value": [ + 2, + 1 + ], + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": [ + 1, + 2 + ] + } + } + ] + }, + { + "name": "enum rejects an unlisted value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "enum": [ + "GB", + "NL" + ] + } + }, + "schema": "subject", + "value": "BE", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "GB", + "NL" + ] + } + } + ] + }, + { + "name": "enum compares numbers numerically", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "enum": [ + 1, + 2 + ] + } + }, + "schema": "subject", + "value": 1.0, + "issues": [] + }, + { + "name": "minimum is inclusive", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer", + "minimum": 1 + } + }, + "schema": "subject", + "value": 1, + "issues": [] + }, + { + "name": "below minimum", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer", + "minimum": 1 + } + }, + "schema": "subject", + "value": 0, + "issues": [ + { + "code": "minimum", + "path": [], + "params": { + "minimum": 1, + "value": 0 + } + } + ] + }, + { + "name": "maximum is inclusive", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "maximum": 10 + } + }, + "schema": "subject", + "value": 10, + "issues": [] + }, + { + "name": "above maximum", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "maximum": 10 + } + }, + "schema": "subject", + "value": 10.5, + "issues": [ + { + "code": "maximum", + "path": [], + "params": { + "maximum": 10, + "value": 10.5 + } + } + ] + }, + { + "name": "too short", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "minLength": 2 + } + }, + "schema": "subject", + "value": "a", + "issues": [ + { + "code": "minLength", + "path": [], + "params": { + "minLength": 2, + "length": 1 + } + } + ] + }, + { + "name": "too long", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "maxLength": 3 + } + }, + "schema": "subject", + "value": "abcd", + "issues": [ + { + "code": "maxLength", + "path": [], + "params": { + "maxLength": 3, + "length": 4 + } + } + ] + }, + { + "name": "lengths count code points, so an emoji with a skin tone is two", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "maxLength": 2 + } + }, + "schema": "subject", + "value": "👋🏽", + "issues": [] + }, + { + "name": "a length over by code points reports code points", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "maxLength": 1 + } + }, + "schema": "subject", + "value": "👋🏽", + "issues": [ + { + "code": "maxLength", + "path": [], + "params": { + "maxLength": 1, + "length": 2 + } + } + ] + }, + { + "name": "a pattern that does not match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[A-Z]{2}$" + } + }, + "schema": "subject", + "value": "gb", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^[A-Z]{2}$" + } + } + ] + }, + { + "name": "a pattern without anchors matches anywhere in the string", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "[0-9]" + } + }, + "schema": "subject", + "value": "a1b", + "issues": [] + }, + { + "name": "a timestamp", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time" + } + }, + "schema": "subject", + "value": "2026-01-31T09:00:00Z", + "issues": [] + }, + { + "name": "a date alone is not a timestamp", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time" + } + }, + "schema": "subject", + "value": "2026-01-31", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "date-time" + } + } + ] + }, + { + "name": "a version", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.2.3", + "issues": [] + }, + { + "name": "a version can be short, as the version operators read it", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.2", + "issues": [] + }, + { + "name": "five parts are not a version", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.2.3.4.5", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "semver" + } + } + ] + }, + { + "name": "a version with a trailing newline is not a version", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "semver" + } + }, + "schema": "subject", + "value": "1.0.0\n", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "semver" + } + } + ] + }, + { + "name": "too few items", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "minItems": 1 + } + }, + "schema": "subject", + "value": [], + "issues": [ + { + "code": "minItems", + "path": [], + "params": { + "minItems": 1, + "count": 0 + } + } + ] + }, + { + "name": "too many items", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "maxItems": 2 + } + }, + "schema": "subject", + "value": [ + "a", + "b", + "c" + ], + "issues": [ + { + "code": "maxItems", + "path": [], + "params": { + "maxItems": 2, + "count": 3 + } + } + ] + }, + { + "name": "a repeated item names the first repeat", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "integer" + }, + "uniqueItems": true + } + }, + "schema": "subject", + "value": [ + 1, + 2, + 1 + ], + "issues": [ + { + "code": "uniqueItems", + "path": [], + "params": { + "index": 2 + } + } + ] + }, + { + "name": "repeats compare objects by value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "object", + "properties": { + "a": { + "type": "integer" + } + } + }, + "uniqueItems": true + } + }, + "schema": "subject", + "value": [ + { + "a": 1 + }, + { + "a": 1 + } + ], + "issues": [ + { + "code": "uniqueItems", + "path": [], + "params": { + "index": 1 + } + } + ] + }, + { + "name": "an array without items holds strings", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array" + } + }, + "schema": "subject", + "value": [ + "a", + 1 + ], + "issues": [ + { + "code": "type", + "path": [ + 1 + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "each item's issues carry its index", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + }, + "schema": "subject", + "value": [ + 1, + -1, + "x" + ], + "issues": [ + { + "code": "minimum", + "path": [ + 1 + ], + "params": { + "minimum": 0, + "value": -1 + } + }, + { + "code": "type", + "path": [ + 2 + ], + "params": { + "type": "integer", + "received": "string" + } + } + ] + }, + { + "name": "a missing required key is reported at the key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + } + ] + }, + { + "name": "a key named like an inherited property is not present until given", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "constructor": { + "type": "string" + } + }, + "required": [ + "constructor" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "constructor" + ], + "params": { + "key": "constructor" + } + } + ] + }, + { + "name": "an unlisted key is reported at the key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "a": { + "type": "string" + } + } + } + }, + "schema": "subject", + "value": { + "a": "x", + "b": 1 + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "properties with no keys take no keys", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": {} + } + }, + "schema": "subject", + "value": { + "a": "x" + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "a" + ], + "params": { + "key": "a" + } + } + ] + }, + { + "name": "additionalProperties true takes any other key and value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "a": { + "type": "string" + } + }, + "additionalProperties": true + } + }, + "schema": "subject", + "value": { + "a": "x", + "b": { + "c": [ + 1 + ] + } + }, + "issues": [] + }, + { + "name": "additionalProperties rules every other key's value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": { + "type": "string" + } + } + }, + "schema": "subject", + "value": { + "en": "Hi", + "nl": 1 + }, + "issues": [ + { + "code": "type", + "path": [ + "nl" + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "an object without properties is flat, taking primitive values", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": { + "a": 1, + "b": "x", + "c": null, + "d": true + }, + "issues": [] + }, + { + "name": "a flat object rejects a nested value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object" + } + }, + "schema": "subject", + "value": { + "a": [ + 1 + ] + }, + "issues": [ + { + "code": "type", + "path": [ + "a" + ], + "params": { + "type": "primitive", + "received": "array" + } + } + ] + }, + { + "name": "nested issues carry the full path", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "type": "object", + "properties": { + "city": { + "type": "string", + "minLength": 2 + } + } + } + } + } + }, + "schema": "subject", + "value": { + "address": { + "city": "A" + } + }, + "issues": [ + { + "code": "minLength", + "path": [ + "address", + "city" + ], + "params": { + "minLength": 2, + "length": 1 + } + } + ] + }, + { + "name": "every issue is reported", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "age": { + "type": "integer", + "minimum": 18 + } + }, + "required": [ + "email" + ] + } + }, + "schema": "subject", + "value": { + "age": 12, + "extra": true + }, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + }, + { + "code": "minimum", + "path": [ + "age" + ], + "params": { + "minimum": 18, + "value": 12 + } + }, + { + "code": "additionalProperties", + "path": [ + "extra" + ], + "params": { + "key": "extra" + } + } + ] + }, + { + "name": "a reference validates with the referenced schema, at the field's path", + "schemas": { + "address": { + "hash": "address-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + }, + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "schema": "address" + } + } + } + }, + "schema": "subject", + "value": { + "address": {} + }, + "issues": [ + { + "code": "required", + "path": [ + "address", + "city" + ], + "params": { + "key": "city" + } + } + ] + }, + { + "name": "a reference to a schema the section lacks fails closed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "schema": "address" + } + } + } + }, + "schema": "subject", + "value": { + "address": { + "city": "Leiden" + } + }, + "issues": [ + { + "code": "schemaNotFound", + "path": [ + "address" + ], + "params": { + "schema": "address" + } + } + ] + }, + { + "name": "a key the section lacks fails closed", + "schemas": {}, + "schema": "missing", + "value": "x", + "issues": [ + { + "code": "schemaNotFound", + "path": [], + "params": { + "schema": "missing" + } + } + ] + }, + { + "name": "an enum without a type takes its values, whatever their types", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 1, + "one", + null + ] + } + }, + "schema": "subject", + "value": "one", + "issues": [] + }, + { + "name": "an enum without a type reports enum for any other value", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 1, + "one", + null + ] + } + }, + "schema": "subject", + "value": true, + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + 1, + "one", + null + ] + } + } + ] + }, + { + "name": "a const without a type compares an object by value", + "schemas": { + "subject": { + "hash": "subject-1", + "const": { + "tier": 2 + } + } + }, + "schema": "subject", + "value": { + "tier": 2 + }, + "issues": [] + }, + { + "name": "a const without a type reports const for another object", + "schemas": { + "subject": { + "hash": "subject-1", + "const": { + "tier": 2 + } + } + }, + "schema": "subject", + "value": { + "tier": 3 + }, + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": { + "tier": 2 + } + } + } + ] + }, + { + "name": "a nullable value takes null", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "maxLength": 3 + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": null, + "issues": [] + }, + { + "name": "a nullable value's own branch reports its issues", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "maxLength": 3 + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": "abcd", + "issues": [ + { + "code": "maxLength", + "path": [], + "params": { + "maxLength": 3, + "length": 4 + } + } + ] + }, + { + "name": "a value no branch's type takes fails the oneOf", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "maxLength": 3 + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 0 + } + } + ] + }, + { + "name": "an integer branch selected by a fraction reports its type", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "integer" + }, + { + "type": "string" + } + ] + } + }, + "schema": "subject", + "value": 1.5, + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "integer", + "received": "number" + } + } + ] + }, + { + "name": "branches of one type count the matches, and two is too many", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "minLength": 2 + }, + { + "type": "string", + "pattern": "^a" + } + ] + } + }, + "schema": "subject", + "value": "ab", + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 2 + } + } + ] + }, + { + "name": "branches of one type count the matches, and none fails", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "minLength": 2 + }, + { + "type": "string", + "pattern": "^a" + } + ] + } + }, + "schema": "subject", + "value": "b", + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 0 + } + } + ] + }, + { + "name": "branches of one type count the matches, and one passes", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "string", + "minLength": 2 + }, + { + "type": "string", + "pattern": "^a" + } + ] + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "a oneOf of consts takes one of them", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "const": "free" + }, + { + "const": "pro" + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": null, + "issues": [] + }, + { + "name": "a oneOf of consts reports enum, with its values, as an enum does", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "const": "free" + }, + { + "const": "pro" + }, + { + "const": null + } + ] + } + }, + "schema": "subject", + "value": "gold", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "free", + "pro", + null + ] + } + } + ] + }, + { + "name": "an object branch selected by type reports its fields' issues", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "type": "object", + "properties": { + "code": { + "type": "string" + } + }, + "required": [ + "code" + ] + }, + { + "type": "array" + } + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "code" + ], + "params": { + "key": "code" + } + } + ] + }, + { + "name": "a mutation applies when its input condition matches, and names itself", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": [ + { + "input": "accountType", + "operator": "equals", + "value": "business" + } + ], + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "accountType": "business" + }, + "issues": [ + { + "code": "required", + "path": [ + "taxId" + ], + "params": { + "key": "taxId" + }, + "mutation": "business" + } + ] + }, + { + "name": "a mutation does not apply when its input condition does not match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": [ + { + "input": "accountType", + "operator": "equals", + "value": "business" + } + ], + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "accountType": "personal" + }, + "issues": [] + }, + { + "name": "a mutation reads the context", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 10 + } + }, + "mutations": [ + { + "key": "dutch", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 3 + } + ] + } + ] + } + }, + "schema": "subject", + "context": { + "country": "nl" + }, + "value": { + "name": "Ada L" + }, + "issues": [ + { + "code": "maxLength", + "path": [ + "name" + ], + "params": { + "maxLength": 3, + "length": 5 + }, + "mutation": "dutch" + } + ] + }, + { + "name": "a mutation whose context does not match leaves the base rules", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 10 + } + }, + "mutations": [ + { + "key": "dutch", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 3 + } + ] + } + ] + } + }, + "schema": "subject", + "context": { + "country": "de" + }, + "value": { + "name": "Ada L" + }, + "issues": [] + }, + { + "name": "a mutation reads a segment", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "maxLength": 10 + } + }, + "mutations": [ + { + "key": "paying", + "conditions": "paying", + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 20 + } + ] + } + ] + } + }, + "schema": "subject", + "segments": { + "paying": { + "hash": "paying-1", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "paid" + } + ] + } + }, + "context": { + "plan": "paid" + }, + "value": { + "name": "Grace Brewster " + }, + "issues": [] + }, + { + "name": "every matching mutation applies, in order, and the last to change a rule names its issue", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "mutations": [ + { + "key": "first", + "conditions": [ + { + "input": "name", + "operator": "exists" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 10 + } + ] + }, + { + "key": "second", + "conditions": [ + { + "input": "name", + "operator": "exists" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "name", + "maxLength" + ], + "value": 5 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "name": "Lovelace" + }, + "issues": [ + { + "code": "maxLength", + "path": [ + "name" + ], + "params": { + "maxLength": 5, + "length": 8 + }, + "mutation": "second" + } + ] + }, + { + "name": "valueFrom compares two inputs", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": "a", + "confirmPassword": "b" + }, + "issues": [ + { + "code": "maxLength", + "path": [ + "confirmPassword" + ], + "params": { + "maxLength": 0, + "length": 1 + }, + "mutation": "mismatch" + } + ] + }, + { + "name": "valueFrom matches nothing when the inputs agree", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": "a", + "confirmPassword": "a" + }, + "issues": [] + }, + { + "name": "an object in value is a value, never a read", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "equals", + "value": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": "a", + "confirmPassword": "a" + }, + "issues": [] + }, + { + "name": "matches never takes its pattern from valueFrom", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "mutations": [ + { + "key": "mismatch", + "conditions": [ + { + "input": "confirmPassword", + "operator": "matches", + "valueFrom": { + "input": "password" + } + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "confirmPassword", + "maxLength" + ], + "value": 0 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "password": ".*", + "confirmPassword": "anything" + }, + "issues": [] + }, + { + "name": "an issue entry reports when its conditions match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "lovelace", + "confirmPassword": "lovelaced" + }, + "issues": [ + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "an issue entry reports nothing when its conditions do not match", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "lovelace", + "confirmPassword": "lovelace" + }, + "issues": [] + }, + { + "name": "an issue of shape holds every issue entry back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "password": "lovelace", + "confirmPassword": "other" + }, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + } + ] + }, + { + "name": "other issues hold no issue entry back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "short", + "confirmPassword": "other" + }, + "issues": [ + { + "code": "minLength", + "path": [ + "password" + ], + "params": { + "minLength": 8, + "length": 5 + } + }, + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "an issue entry guarded by the context reports for matching users", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "shippingCountry": { + "type": "string" + }, + "billingCountry": { + "type": "string" + } + }, + "issues": [ + { + "key": "dutchShipping", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + }, + { + "input": "shippingCountry", + "operator": "notEquals", + "valueFrom": { + "input": "billingCountry" + } + } + ], + "path": "shippingCountry", + "message": "We ship Dutch orders to the billing country only" + } + ] + } + }, + "schema": "subject", + "context": { + "country": "nl" + }, + "value": { + "shippingCountry": "DE", + "billingCountry": "NL" + }, + "issues": [ + { + "code": "refine", + "path": [ + "shippingCountry" + ], + "params": { + "refine": "dutchShipping" + } + } + ] + }, + { + "name": "an issue entry guarded by the context never reports for other users", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "shippingCountry": { + "type": "string" + }, + "billingCountry": { + "type": "string" + } + }, + "issues": [ + { + "key": "dutchShipping", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + }, + { + "input": "shippingCountry", + "operator": "notEquals", + "valueFrom": { + "input": "billingCountry" + } + } + ], + "path": "shippingCountry", + "message": "We ship Dutch orders to the billing country only" + } + ] + } + }, + "schema": "subject", + "context": { + "country": "de" + }, + "value": { + "shippingCountry": "DE", + "billingCountry": "NL" + }, + "issues": [] + }, + { + "name": "input paths are relative to the node a mutation sits on", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "address": { + "schema": "postal" + } + } + }, + "postal": { + "hash": "postal-1", + "type": "object", + "properties": { + "country": { + "type": "string" + }, + "state": { + "type": "string" + } + }, + "mutations": [ + { + "key": "unitedStates", + "conditions": [ + { + "input": "country", + "operator": "equals", + "value": "US" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "required" + ], + "value": [ + "state" + ] + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "address": { + "country": "US" + } + }, + "issues": [ + { + "code": "required", + "path": [ + "address", + "state" + ], + "params": { + "key": "state" + }, + "mutation": "unitedStates" + } + ] + }, + { + "name": "a mutation can change a node's issues, and names the issue they report", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "mutations": [ + { + "key": "paid", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "paid" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "issues" + ], + "value": [ + { + "key": "nowhere", + "conditions": [ + { + "input": "city", + "operator": "equals", + "value": "Nowhere" + } + ], + "path": "city", + "message": "Name a real city" + } + ] + } + ] + } + ] + } + }, + "schema": "subject", + "context": { + "plan": "paid" + }, + "value": { + "city": "Nowhere" + }, + "issues": [ + { + "code": "refine", + "path": [ + "city" + ], + "params": { + "refine": "nowhere" + }, + "mutation": "paid" + } + ] + }, + { + "name": "a timestamp enum still checks the format", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time", + "enum": [ + "soon" + ] + } + }, + "schema": "subject", + "value": "soon", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "date-time" + } + } + ] + }, + { + "name": "a timestamp const still checks the format", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "format": "date-time", + "const": "soon" + } + }, + "schema": "subject", + "value": "soon", + "issues": [ + { + "code": "format", + "path": [], + "params": { + "format": "date-time" + } + } + ] + } + ] +} diff --git a/conformance/sdk-sections.json b/conformance/sdk-sections.json new file mode 100644 index 0000000..7fcfb50 --- /dev/null +++ b/conformance/sdk-sections.json @@ -0,0 +1,941 @@ +{ + "kind": "featurevisor.sdk-sections", + "schemaVersion": 1, + "evaluationCases": [ + { + "name": "a schemas section changes no evaluation", + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "signUp-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + } + }, + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "checkout" + ], + "value": true + }, + { + "method": "getVariation", + "args": [ + "checkout" + ], + "value": "treatment" + }, + { + "method": "getVariable", + "args": [ + "checkout", + "label" + ], + "value": "Pay now" + }, + { + "method": "getVariable", + "args": [ + "banner" + ], + "value": "Hello" + }, + { + "method": "isEnabled", + "args": [ + "off" + ], + "value": false + } + ] + }, + { + "name": "a section of any name, and top level values that are not objects, change no evaluation", + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "signUp-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + }, + "flows": { + "onboarding": { + "hash": "onboarding-1", + "steps": [ + "welcome", + "plan" + ] + } + }, + "note": "kept", + "list": [ + 1, + 2 + ] + }, + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "checkout" + ], + "value": true + }, + { + "method": "getVariation", + "args": [ + "checkout" + ], + "value": "treatment" + }, + { + "method": "getVariable", + "args": [ + "checkout", + "label" + ], + "value": "Pay now" + }, + { + "method": "getVariable", + "args": [ + "banner" + ], + "value": "Hello" + }, + { + "method": "isEnabled", + "args": [ + "off" + ], + "value": false + } + ] + }, + { + "name": "a datafile given as a string with sections evaluates the same", + "datafile": "{\"schemaVersion\":\"4\",\"revision\":\"1\",\"segments\":{},\"features\":{\"checkout\":{\"hash\":\"checkout-1\",\"bucketBy\":\"userId\",\"traffic\":[{\"key\":\"all\",\"conditions\":\"*\",\"percentage\":100000,\"variation\":\"treatment\"}],\"variablesSchema\":{\"label\":{\"type\":\"string\",\"defaultValue\":\"Pay\"}},\"variations\":[{\"value\":\"control\"},{\"value\":\"treatment\",\"variables\":{\"label\":\"Pay now\"}}]},\"off\":{\"hash\":\"off-1\",\"bucketBy\":\"userId\",\"traffic\":[]}},\"variables\":{\"banner\":{\"hash\":\"banner-1\",\"type\":\"string\",\"defaultValue\":\"Hello\"}},\"schemas\":{\"signUp\":{\"hash\":\"signUp-1\",\"type\":\"object\",\"properties\":{\"email\":{\"type\":\"string\"}},\"required\":[\"email\"]}}}", + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "checkout" + ], + "value": true + }, + { + "method": "getVariation", + "args": [ + "checkout" + ], + "value": "treatment" + }, + { + "method": "getVariable", + "args": [ + "checkout", + "label" + ], + "value": "Pay now" + }, + { + "method": "getVariable", + "args": [ + "banner" + ], + "value": "Hello" + }, + { + "method": "isEnabled", + "args": [ + "off" + ], + "value": false + } + ] + }, + { + "name": "a schema 2 datafile with a schemas section evaluates as before", + "datafile": { + "schemaVersion": "2", + "revision": "1", + "segments": {}, + "features": { + "legacy": { + "hash": "legacy-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "segments": "*", + "percentage": 100000 + } + ] + } + }, + "schemas": { + "signUp": { + "hash": "signUp-1", + "type": "object", + "properties": { + "email": { + "type": "string" + } + }, + "required": [ + "email" + ] + } + } + }, + "context": { + "userId": "user-1" + }, + "results": [ + { + "method": "isEnabled", + "args": [ + "legacy" + ], + "value": true + } + ] + } + ], + "carriageCases": [ + { + "name": "a merge keeps every section and merges it by entry, and a replace keeps exactly what came", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "s1" + }, + "address": { + "hash": "a1" + } + } + } + }, + "expectInitial": { + "entryKeys": { + "schemas": [ + "signUp", + "address" + ], + "flows": [] + }, + "entries": [ + { + "section": "schemas", + "key": "signUp", + "value": { + "hash": "s1" + } + } + ] + }, + "operations": [ + { + "action": "setDatafile", + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "signUp": { + "hash": "s2" + } + } + }, + "expect": { + "sections": { + "schemas": [ + "signUp" + ] + }, + "entryKeys": { + "schemas": [ + "signUp", + "address" + ] + }, + "entries": [ + { + "section": "schemas", + "key": "signUp", + "value": { + "hash": "s2" + } + }, + { + "section": "schemas", + "key": "address", + "value": { + "hash": "a1" + } + } + ] + } + }, + { + "action": "setDatafile", + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "3", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": { + "schemas": [] + }, + "entryKeys": { + "schemas": [ + "signUp", + "address" + ] + } + } + }, + { + "action": "setDatafile", + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "4", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "schemas": { + "coupon": { + "hash": "c1" + } + } + }, + "expect": { + "sections": { + "schemas": [ + "signUp", + "address", + "coupon" + ] + }, + "entryKeys": { + "schemas": [ + "coupon" + ] + }, + "entries": [ + { + "section": "schemas", + "key": "signUp", + "value": null + } + ] + } + }, + { + "action": "setDatafile", + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "5", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": { + "schemas": [ + "coupon" + ] + }, + "entryKeys": { + "schemas": [] + } + } + } + ] + }, + { + "name": "datafiles without sections report none", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + } + }, + "expectInitial": { + "entryKeys": { + "schemas": [] + } + }, + "operations": [ + { + "action": "setDatafile", + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": {} + } + }, + { + "action": "setDatafile", + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "3", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + } + }, + "expect": { + "sections": {} + } + } + ] + }, + { + "name": "the SDK's own keys and top level values that are not objects are never sections", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": {}, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000, + "variation": "treatment" + } + ], + "variablesSchema": { + "label": { + "type": "string", + "defaultValue": "Pay" + } + }, + "variations": [ + { + "value": "control" + }, + { + "value": "treatment", + "variables": { + "label": "Pay now" + } + } + ] + }, + "off": { + "hash": "off-1", + "bucketBy": "userId", + "traffic": [] + } + }, + "variables": { + "banner": { + "hash": "banner-1", + "type": "string", + "defaultValue": "Hello" + } + }, + "note": "kept", + "list": [ + 1, + 2 + ] + } + }, + "expectInitial": { + "entryKeys": { + "note": [], + "list": [], + "features": [], + "segments": [], + "variables": [] + }, + "entries": [ + { + "section": "features", + "key": "checkout", + "value": null + } + ] + }, + "operations": [] + } + ] +} diff --git a/featurevisor-schemas/pom.xml b/featurevisor-schemas/pom.xml new file mode 100644 index 0000000..921c713 --- /dev/null +++ b/featurevisor-schemas/pom.xml @@ -0,0 +1,78 @@ + + + 4.0.0 + + + com.featurevisor + featurevisor-parent + ${revision} + ../pom.xml + + + featurevisor-schemas + jar + + Featurevisor Schemas for Java + Validate data against the schemas a Featurevisor datafile carries + https://github.com/featurevisor/featurevisor-java + + + scm:git:git://github.com/featurevisor/featurevisor-java.git + scm:git:ssh://github.com:featurevisor/featurevisor-java.git + https://github.com/featurevisor/featurevisor-java + HEAD + + + + + com.featurevisor + featurevisor-java + ${project.version} + + + com.fasterxml.jackson.core + jackson-databind + + + org.junit.jupiter + junit-jupiter + test + + + + + + + src/test/resources + + + ${project.basedir}/../conformance + conformance + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + + org.apache.maven.plugins + maven-source-plugin + + + org.apache.maven.plugins + maven-javadoc-plugin + + + org.codehaus.mojo + flatten-maven-plugin + + + + diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/CheckInfo.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/CheckInfo.java new file mode 100644 index 0000000..75f1e72 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/CheckInfo.java @@ -0,0 +1,36 @@ +package com.featurevisor.schemas; + +import java.util.Map; + +/** What a check in code gets besides the value at its path. */ +public final class CheckInfo { + private final Object input; + private final Map context; + + CheckInfo(Object input, Map context) { + this.input = input; + this.context = context; + } + + /** + * The whole value being validated, as maps, lists and primitives. For a + * search or a lookup outside validation, the values {@code withInput} gave, + * or null without them. + */ + public Object getInput() { return input; } + + /** The context validation uses: the instance's, with any given to the call merged over it. */ + public Map getContext() { return context; } + + /** The value at a path in the input, such as {@code password} or {@code items.0.name}, or null. */ + public Object read(String path) { + Object current = input; + for (Paths.Step step : Paths.parse(path)) { + if (step.kind == Paths.Kind.KEY && current instanceof Map) current = ((Map) current).get(step.key); + else if (step.kind == Paths.Kind.INDEX && current instanceof java.util.List + && step.index < ((java.util.List) current).size()) current = ((java.util.List) current).get(step.index); + else return null; + } + return current; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java new file mode 100644 index 0000000..c7e3e81 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java @@ -0,0 +1,244 @@ +package com.featurevisor.schemas; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** What a handle derives from its node: constraints, choices, kind, field order and annotations. */ +final class Derived { + private Derived() {} + + private static Set identitySet() { + return Collections.newSetFromMap(new IdentityHashMap<>()); + } + + /** + * The branch a nullable field's rules come from: a {@code oneOf} whose other + * branches only allow {@code null}, such as {@code oneOf: [{ type: string }, { const: null }]}. + */ + static Map nonNullBranch(Map node, Resolver resolve) { + if (!(node.get("oneOf") instanceof List)) return node; + List> branches = new ArrayList<>(); + for (Object branch : (List) node.get("oneOf")) { + Map resolved = Engine.resolveNode(branch, resolve); + if (resolved == null) continue; + if (resolved.containsKey("const") && resolved.get("const") == null) continue; + branches.add(resolved); + } + return branches.size() == 1 ? branches.get(0) : null; + } + + static boolean isObjectNode(Map node) { + if (node == null) return false; + Object type = node.get("type"); + return "object".equals(type) || (type == null && node.get("properties") instanceof Map); + } + + /** Whether a node takes {@code null}: a {@code const: null}, an {@code enum} listing it, or a {@code oneOf} branch that does. */ + static boolean takesNull(Object node, Resolver resolve, Set seen) { + Map resolved = Engine.resolveNode(node, resolve); + if (resolved == null || !seen.add(resolved)) return false; + if (resolved.containsKey("const")) return resolved.get("const") == null; + if (resolved.get("enum") instanceof List) return ((List) resolved.get("enum")).contains(null); + if (resolved.get("oneOf") instanceof List) { + for (Object branch : (List) resolved.get("oneOf")) if (takesNull(branch, resolve, seen)) return true; + } + return false; + } + + /** Whether a choice is between booleans, such as {@code const: true} for accepting terms. */ + private static boolean isBooleanChoice(List values) { + if (values == null) return false; + boolean some = false; + for (Object value : values) { + if (value instanceof Boolean) some = true; + else if (value != null) return false; + } + return some; + } + + /** + * Whether an input left empty fails a field's rules, as {@code required} tells a + * browser. An unchecked box reads as false and a required list with nothing + * chosen as an empty list, so each passes unless its rules say otherwise. + */ + private static boolean emptyFails(Map rules, Resolver resolve) { + if ("boolean".equals(rules.get("type"))) return false; + if ("array".equals(rules.get("type"))) return rules.get("minItems") instanceof Number && Json.number(rules.get("minItems")) > 0; + List values = valuesOf(rules, resolve); + return !isBooleanChoice(values) || !values.contains(false); + } + + private static Integer integer(Object value) { + return value instanceof Number ? (int) Math.min(Integer.MAX_VALUE, Json.number(value)) : null; + } + + static FieldConstraints constraints(Object node, boolean required, Resolver resolve) { + Map resolved = Engine.resolveNode(node, resolve); + Map rules = resolved == null ? null : nonNullBranch(resolved, resolve); + boolean isRequired = required && !takesNull(resolved, resolve, identitySet()) && (rules == null || emptyFails(rules, resolve)); + if (rules == null) return isRequired ? new FieldConstraints(true, null, null, null, null, null, false) : FieldConstraints.NONE; + Object type = rules.get("type"); + Integer minLength = null, maxLength = null; + Number min = null, max = null, step = null; + boolean multiple = false; + if ("string".equals(type)) { + minLength = integer(rules.get("minLength")); + maxLength = integer(rules.get("maxLength")); + } else if ("integer".equals(type) || "number".equals(type)) { + if (rules.get("minimum") instanceof Number) min = (Number) rules.get("minimum"); + if (rules.get("maximum") instanceof Number) max = (Number) rules.get("maximum"); + if ("integer".equals(type)) step = 1; + } else if ("array".equals(type)) { + multiple = true; + } + return new FieldConstraints(isRequired, minLength, maxLength, min, max, step, multiple); + } + + /** An object's fields' constraints by dot path, nested objects included and lists left to their rows' handles. */ + static Map fieldConstraints(Object node, Resolver resolve) { + Map resolved = Engine.resolveNode(node, resolve); + Map result = new LinkedHashMap<>(); + if (isObjectNode(resolved)) collectConstraints(resolved, "", resolve, result, identitySet()); + return Collections.unmodifiableMap(result); + } + + private static void collectConstraints(Map node, String prefix, Resolver resolve, + Map result, Set seen) { + if (!seen.add(node)) return; + Map properties = Json.map(node.get("properties")); + if (properties == null) return; + List required = node.get("required") instanceof List ? (List) node.get("required") : List.of(); + for (Map.Entry entry : properties.entrySet()) { + String path = prefix + entry.getKey(); + result.put(path, constraints(entry.getValue(), required.contains(entry.getKey()), resolve)); + Map child = Engine.resolveNode(entry.getValue(), resolve); + if (isObjectNode(child)) collectConstraints(child, path + ".", resolve, result, seen); + } + } + + /** + * A node's choices in the order its rules list them, each as its value with + * what the schema says about it: an {@code enum} value's entry in the + * {@code options} annotation beside it, or a {@code const} branch's own + * annotations in a {@code oneOf} of consts. Null when the node lists no + * choices. A multiple select's choices are its items'. + */ + private static List choicesOf(Object node, Resolver resolve, boolean branch, Set seen) { + Map resolved = Engine.resolveNode(node, resolve); + if (resolved == null || !seen.add(resolved)) return null; + if (resolved.get("enum") instanceof List) { + List choices = new ArrayList<>(); + for (Object value : (List) resolved.get("enum")) choices.add(new SchemaOption(value, Engine.optionEntry(resolved, value))); + return choices; + } + if (resolved.containsKey("const")) { + return List.of(new SchemaOption(resolved.get("const"), branch ? Engine.annotationsOf(node, resolve) : null)); + } + if (resolved.get("oneOf") instanceof List) { + // Only a list of choices gives its branches' annotations to the choices. Any other branch's are a field's. + boolean list = Engine.isConstList(resolved, resolve); + List choices = new ArrayList<>(); + for (Object each : (List) resolved.get("oneOf")) { + List found = choicesOf(each, resolve, list, seen); + if (found == null) return null; + for (SchemaOption option : found) { + boolean listed = false; + for (SchemaOption other : choices) if (Json.same(other.getValue(), option.getValue())) listed = true; + if (!listed) choices.add(option); + } + } + return choices; + } + if ("array".equals(resolved.get("type")) && resolved.containsKey("items")) { + return choicesOf(resolved.get("items"), resolve, false, seen); + } + return null; + } + + private static List valuesOf(Object node, Resolver resolve) { + List choices = choicesOf(node, resolve, false, identitySet()); + if (choices == null) return null; + List values = new ArrayList<>(); + for (SchemaOption choice : choices) values.add(choice.getValue()); + return values; + } + + /** A node's own choices, empty when it lists none. */ + static List options(Object node, Resolver resolve) { + List choices = choicesOf(node, resolve, false, identitySet()); + return choices == null ? List.of() : Collections.unmodifiableList(choices); + } + + /** An object's fields' choices by dot path, only for fields that list some. */ + static Map> fieldOptions(Object node, Resolver resolve) { + Map resolved = Engine.resolveNode(node, resolve); + Map> result = new LinkedHashMap<>(); + if (isObjectNode(resolved)) collectOptions(resolved, "", resolve, result, identitySet()); + return Collections.unmodifiableMap(result); + } + + private static void collectOptions(Map node, String prefix, Resolver resolve, + Map> result, Set seen) { + if (!seen.add(node)) return; + Map properties = Json.map(node.get("properties")); + if (properties == null) return; + for (Map.Entry entry : properties.entrySet()) { + String path = prefix + entry.getKey(); + List choices = choicesOf(entry.getValue(), resolve, false, identitySet()); + if (choices != null) result.put(path, Collections.unmodifiableList(choices)); + Map child = Engine.resolveNode(entry.getValue(), resolve); + if (isObjectNode(child)) collectOptions(child, path + ".", resolve, result, seen); + } + } + + /** The keys of an object's fields, the ones its {@code order} lists first, then the rest as written. */ + static List fieldKeys(Object node, Resolver resolve) { + Map resolved = Engine.resolveNode(node, resolve); + Map properties = resolved == null ? null : Json.map(resolved.get("properties")); + if (properties == null) return List.of(); + List keys = new ArrayList<>(properties.keySet()); + Map annotations = Engine.annotationsOf(node, resolve); + List ordered = new ArrayList<>(); + if (annotations != null && annotations.get("order") instanceof List) { + for (Object key : (List) annotations.get("order")) { + if (key instanceof String && keys.contains(key) && !ordered.contains(key)) ordered.add((String) key); + } + } + for (String key : keys) if (!ordered.contains(key)) ordered.add(key); + return Collections.unmodifiableList(ordered); + } + + /** A node's annotations, over those of a schema it references. */ + static Map annotations(Object node, Resolver resolve) { + Map annotations = Engine.annotationsOf(node, resolve); + return annotations == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(annotations)); + } + + /** What a node's rules make a field, or null for a {@code oneOf} of shapes. */ + static FieldKind kind(Object node, Resolver resolve) { + Map resolved = Engine.resolveNode(node, resolve); + if (resolved == null) return null; + if (resolved.get("enum") instanceof List || resolved.containsKey("const") || Engine.isConstList(resolved, resolve)) { + return isBooleanChoice(valuesOf(resolved, resolve)) ? FieldKind.BOOLEAN : FieldKind.SELECT; + } + if (resolved.get("oneOf") instanceof List) { + // A nullable field is what its other branch is. + Map rules = nonNullBranch(resolved, resolve); + return rules == null ? null : kind(rules, resolve); + } + Object type = resolved.get("type"); + if ("string".equals(type)) { + Object format = resolved.get("format"); + return "date-time".equals(format) ? FieldKind.DATE_TIME : "semver".equals(format) ? FieldKind.VERSION : FieldKind.TEXT; + } + if ("array".equals(type)) return kind(resolved.get("items"), resolve) == FieldKind.SELECT ? FieldKind.MULTISELECT : FieldKind.LIST; + if ("integer".equals(type) || "number".equals(type)) return FieldKind.NUMBER; + if ("boolean".equals(type)) return FieldKind.BOOLEAN; + return isObjectNode(resolved) ? FieldKind.OBJECT : null; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java new file mode 100644 index 0000000..66b1b71 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java @@ -0,0 +1,739 @@ +package com.featurevisor.schemas; + +import com.featurevisor.sdk.CompareVersions; +import com.featurevisor.sdk.ConditionReader; +import com.featurevisor.sdk.Conditions; +import com.featurevisor.sdk.VariableMutations; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** Compiles schema nodes, as the datafile holds them, into validators: the port of the JavaScript package's engine. */ +final class Engine { + private Engine() {} + + /** Issues after which an object's {@code issues} could not trust the values they compare. */ + private static final Set SHAPE_CODES = new HashSet<>(Arrays.asList( + "type", "required", "enum", "const", "additionalProperties", "oneOf", "schemaNotFound")); + + static void report(Run run, Position at, String code, Map params) { + report(run, at, code, params, at.path, at, null); + } + + static void report(Run run, Position at, String code, Map params, List path, + Messages.Lookup lookup, String ownMessage) { + run.failed = true; + if (SHAPE_CODES.contains(code)) run.shape++; + if (run.trial) return; + // The field's title, so a message can say `{title} is required`. + if (lookup.title != null) { + params = new LinkedHashMap<>(params); + params.put("title", lookup.title); + } + String message = Messages.choose(code, params, path, lookup, run.sources, ownMessage); + SchemaIssue issue = new SchemaIssue(message, new ArrayList<>(path), code, params, run.schema, null); + if (run.translate != null) { + String translated = run.translate.translate(issue, run.sources.info); + if (translated != null) issue = issue.withMessage(translated); + } + run.issues.add(issue); + } + + static Map params(Object... pairs) { + Map params = new LinkedHashMap<>(); + for (int index = 0; index < pairs.length; index += 2) params.put((String) pairs[index], pairs[index + 1]); + return params; + } + + /** A node's annotations, over those of the schema it references, so the reference's own win. */ + static Map annotationsOf(Object node, Resolver resolve) { + return annotationsOf(node, resolve, new HashSet<>()); + } + + private static Map annotationsOf(Object node, Resolver resolve, Set seen) { + Map map = Json.map(node); + if (map == null) return null; + Map own = Json.map(map.get("annotations")); + String schema = Json.string(map.get("schema")); + if (schema == null || !seen.add(schema)) return own; + Map referenced = annotationsOf(resolve.node(schema), resolve, seen); + if (referenced != null && own != null) { + Map merged = new LinkedHashMap<>(referenced); + merged.putAll(own); + return merged; + } + return own != null ? own : referenced; + } + + /** A node's {@code title} annotation, through the schema it references. */ + static String titleOf(Object node, Resolver resolve) { + Map annotations = annotationsOf(node, resolve); + return annotations == null ? null : Json.string(annotations.get("title")); + } + + /** What an {@code enum}'s {@code options} annotation says about one value, keyed by the value, or its JSON text. */ + static Map optionEntry(Map node, Object value) { + Map options = Json.map(Json.get(node.get("annotations"), "options")); + if (options == null) return null; + String key = value instanceof String ? (String) value : Json.stringify(value); + return Json.map(options.get(key)); + } + + /** Each choice's title, when every choice has one, for an {@code enum} issue's {@code titles}. */ + private static void putTitles(Map params, List> entries) { + List titles = new ArrayList<>(); + for (Map entry : entries) { + Object title = entry == null ? null : entry.get("title"); + if (!(title instanceof String)) return; + titles.add(title); + } + if (!titles.isEmpty()) params.put("titles", titles); + } + + /** Schema messages around a field: its own node's, and a referenced schema's root's. */ + static List ownScopes(Object node, int base, Resolver resolve, List scopes) { + return ownScopes(node, base, resolve, scopes, new HashSet<>()); + } + + private static List ownScopes(Object node, int base, Resolver resolve, List scopes, + Set seen) { + Map map = Json.map(node); + if (map == null) return scopes; + Map messages = Json.map(map.get("messages")); + if (messages != null) scopes.add(new Messages.Scope(messages, base)); + String schema = Json.string(map.get("schema")); + if (schema != null && seen.add(schema)) { + ownScopes(resolve.node(schema), base, resolve, scopes, seen); + } + return scopes; + } + + /** The node a reference resolves to, through any chain of references. */ + static Map resolveNode(Object node, Resolver resolve) { + Set seen = new HashSet<>(); + Object current = node; + while (true) { + Map map = Json.map(current); + if (map == null) return null; + String schema = Json.string(map.get("schema")); + if (schema == null) return map; + if (!seen.add(schema)) return null; + current = resolve.node(schema); + } + } + + /** The kinds of value a branch takes, or null when the branch alone cannot say. */ + private static Set branchKinds(Map resolved) { + if (resolved.get("oneOf") instanceof List) return null; + Object type = resolved.get("type"); + if (type != null && !Boolean.FALSE.equals(type) && !"".equals(type)) { + return new HashSet<>(List.of("integer".equals(type) ? "number" : String.valueOf(type))); + } + if (resolved.containsKey("const")) return new HashSet<>(List.of(Json.kindOf(resolved.get("const")))); + if (resolved.get("enum") instanceof List) { + Set kinds = new HashSet<>(); + for (Object option : (List) resolved.get("enum")) kinds.add(Json.kindOf(option)); + return kinds; + } + return null; + } + + /** Whether a node is a {@code oneOf} whose every branch is a {@code const}, a list of choices like an {@code enum}. */ + static boolean isConstList(Map node, Resolver resolve) { + List branches = Json.list(node.get("oneOf")); + if (branches == null || branches.isEmpty()) return false; + for (Object branch : branches) { + Map resolved = resolveNode(branch, resolve); + if (resolved == null || !resolved.containsKey("const")) return false; + } + return true; + } + + /** A {@code oneOf} of consts, which reports {@code enum} with its values, as an {@code enum} does. */ + private static Validator compileConstList(Map node, Resolver resolve) { + List branches = (List) node.get("oneOf"); + return (value, run, at) -> { + List options = new ArrayList<>(); + for (Object branch : branches) { + Map resolved = resolveNode(branch, resolve); + options.add(resolved == null ? null : resolved.get("const")); + } + for (Object option : options) if (Json.same(value, option)) return; + List> entries = new ArrayList<>(); + for (Object branch : branches) entries.add(annotationsOf(branch, resolve)); + Map params = params("options", options); + putTitles(params, entries); + report(run, at, "enum", params); + }; + } + + /** The kinds each branch takes, kept until a branch's reference resolves to another schema. */ + private static final class OneOfKinds { + final List> nodes; + final List> kinds; + final boolean disjoint; + + OneOfKinds(List> nodes, List> kinds, boolean disjoint) { + this.nodes = nodes; + this.kinds = kinds; + this.disjoint = disjoint; + } + } + + private static Validator compileOneOf(Map node, Resolver resolve) { + if (isConstList(node, resolve)) return compileConstList(node, resolve); + List branchNodes = (List) node.get("oneOf"); + List branches = new ArrayList<>(); + for (Object branch : branchNodes) branches.add(compileNode(branch, resolve)); + OneOfKinds[] cached = new OneOfKinds[1]; + + return (value, run, at) -> { + List> nodes = new ArrayList<>(); + for (Object branch : branchNodes) nodes.add(resolveNode(branch, resolve)); + OneOfKinds kinds = cached[0]; + if (kinds == null || !sameNodes(kinds.nodes, nodes)) { + List> sets = new ArrayList<>(); + boolean all = true; + for (Map resolved : nodes) { + Set set = resolved == null ? null : branchKinds(resolved); + if (set == null) all = false; + sets.add(set); + } + boolean disjoint = all; + for (int index = 0; disjoint && index < sets.size(); index++) { + for (int other = 0; other < sets.size(); other++) { + if (other == index) continue; + for (String kind : sets.get(index)) { + if (sets.get(other).contains(kind)) { disjoint = false; break; } + } + } + } + kinds = new OneOfKinds(nodes, sets, disjoint); + cached[0] = kinds; + } + + if (kinds.disjoint) { + // The value's type selects a branch, whose own issues are the ones reported. + String kind = Json.kindOf(value); + for (int index = 0; index < kinds.kinds.size(); index++) { + if (kinds.kinds.get(index).contains(kind)) { + branches.get(index).validate(value, run, at); + return; + } + } + report(run, at, "oneOf", params("matches", 0)); + return; + } + + int matches = 0; + for (Validator branch : branches) { + Run trial = run.trial(); + branch.validate(value, trial, at); + if (!trial.failed) matches++; + } + if (matches != 1) report(run, at, "oneOf", params("matches", matches)); + }; + } + + private static boolean sameNodes(List> first, List> second) { + for (int index = 0; index < first.size(); index++) if (first.get(index) != second.get(index)) return false; + return true; + } + + private static Integer integerKeyword(Map node, String key) { + Object value = node.get(key); + return value instanceof Number ? (int) Math.min(Integer.MAX_VALUE, Json.number(value)) : null; + } + + private static Validator compileString(Map node, Resolver resolve) { + Object minLength = node.get("minLength") instanceof Number ? node.get("minLength") : null; + Object maxLength = node.get("maxLength") instanceof Number ? node.get("maxLength") : null; + Object format = node.get("format"); + String source = Json.string(node.get("pattern")); + Pattern pattern = source == null ? null : Patterns.compile(source); + + return (value, run, at) -> { + String text = (String) value; + if ("date-time".equals(format) && Conditions.getPortableTimestamp(text) == null) { + report(run, at, "format", params("format", format)); + } else if ("semver".equals(format) && !CompareVersions.isValidVersion(text)) { + report(run, at, "format", params("format", format)); + } + if (minLength != null || maxLength != null) { + int length = Json.codePointLength(text); + if (minLength != null && length < Json.number(minLength)) { + report(run, at, "minLength", params("minLength", minLength, "length", length)); + } + if (maxLength != null && length > Json.number(maxLength)) { + report(run, at, "maxLength", params("maxLength", maxLength, "length", length)); + } + } + if (source != null) { + if (pattern == null) { + // A pattern Java cannot compile fails closed, since no value can be shown to match it. + resolve.unsupportedPattern(source); + report(run, at, "pattern", params("pattern", source)); + } else if (!pattern.matcher(text).find()) { + report(run, at, "pattern", params("pattern", source)); + } + } + }; + } + + private static Validator compileNumber(Map node) { + Object minimum = node.get("minimum") instanceof Number ? node.get("minimum") : null; + Object maximum = node.get("maximum") instanceof Number ? node.get("maximum") : null; + return (value, run, at) -> { + double number = Json.number(value); + if (minimum != null && number < Json.number(minimum)) report(run, at, "minimum", params("minimum", minimum, "value", value)); + if (maximum != null && number > Json.number(maximum)) report(run, at, "maximum", params("maximum", maximum, "value", value)); + }; + } + + private static Validator compileArray(Map node, Resolver resolve) { + Object minItems = node.get("minItems") instanceof Number ? node.get("minItems") : null; + Object maxItems = node.get("maxItems") instanceof Number ? node.get("maxItems") : null; + Validator items = node.containsKey("items") ? compileNode(node.get("items"), resolve) : null; + boolean unique = Boolean.TRUE.equals(node.get("uniqueItems")); + return (value, run, at) -> { + List list = (List) value; + if (minItems != null && list.size() < Json.number(minItems)) { + report(run, at, "minItems", params("minItems", minItems, "count", list.size())); + } + if (maxItems != null && list.size() > Json.number(maxItems)) { + report(run, at, "maxItems", params("maxItems", maxItems, "count", list.size())); + } + if (unique) { + outer: + for (int index = 1; index < list.size(); index++) { + for (int earlier = 0; earlier < index; earlier++) { + if (Json.same(list.get(earlier), list.get(index))) { + report(run, at, "uniqueItems", params("index", index)); + break outer; + } + } + } + } + List mpath = append(at.mpath, "[]"); + for (int index = 0; index < list.size(); index++) { + Position item = new Position(append(at.path, index), mpath, at.scopes, null); + if (items != null) items.validate(list.get(index), run, item); + else if (!(list.get(index) instanceof String)) { + // An array without `items` holds strings only. + report(run, item, "type", params("type", "string", "received", Json.kindOf(list.get(index)))); + } + } + }; + } + + /** An object's messages for a key it has no field for, which has no title of its own. */ + private static Messages.Lookup untitled(Position at) { + return new Messages.Lookup(at.mpath, at.scopes, null, null); + } + + private static Validator compileObject(Map node, Resolver resolve) { + Map properties = Json.map(node.get("properties")); + Map compiled = new LinkedHashMap<>(); + if (properties != null) { + for (Map.Entry entry : properties.entrySet()) { + compiled.put(entry.getKey(), compileNode(entry.getValue(), resolve)); + } + } + List required = new ArrayList<>(); + if (node.get("required") instanceof List) { + for (Object key : (List) node.get("required")) if (key instanceof String) required.add((String) key); + } + boolean hasAdditional = node.containsKey("additionalProperties"); + Object additional = node.get("additionalProperties"); + Validator compiledAdditional = hasAdditional && !Boolean.TRUE.equals(additional) ? compileNode(additional, resolve) : null; + + return (value, run, at) -> { + Map object = (Map) value; + + if (properties != null) { + for (String key : required) { + if (object.containsKey(key)) continue; + // A missing key's issue is at the key, worded by the messages for that field, with its title. + List mpath = append(at.mpath, key); + List scopes = new ArrayList<>(at.scopes); + ownScopes(properties.get(key), mpath.size(), resolve, scopes); + report(run, at, "required", params("key", key), append(at.path, key), + new Messages.Lookup(mpath, scopes, titleOf(properties.get(key), resolve), null), null); + } + } + + for (Map.Entry entry : object.entrySet()) { + String key = String.valueOf(entry.getKey()); + Object child = entry.getValue(); + Validator property = compiled.get(key); + if (property != null) { + property.validate(child, run, new Position(append(at.path, key), append(at.mpath, key), at.scopes, null)); + } else if (Boolean.TRUE.equals(additional)) { + continue; + } else if (compiledAdditional != null) { + compiledAdditional.validate(child, run, new Position(append(at.path, key), append(at.mpath, "*"), at.scopes, null)); + } else if (properties != null) { + // An extra key has no field of its own, so the object that rejects it words its issue, without a title. + report(run, at, "additionalProperties", params("key", key), append(at.path, key), untitled(at), null); + } else if (!Json.isPrimitive(child)) { + // Without `properties` or `additionalProperties`, an object is flat. + report(run, at, "type", params("type", "primitive", "received", Json.kindOf(child)), + append(at.path, key), untitled(at), null); + } + } + }; + } + + private static boolean typeMatches(String type, Object value) { + switch (type) { + case "string": return value instanceof String; + case "integer": return Json.isInteger(value); + case "number": return Json.isFiniteNumber(value); + case "boolean": return value instanceof Boolean; + case "array": return value instanceof List; + case "object": return value instanceof Map; + default: return true; + } + } + + /** + * References a walk follows inside one another. Only a schema that references itself + * without reading deeper into the value gets this far, so the walk fails closed there. + */ + static final int MAX_REFERENCE_DEPTH = 128; + + private static Validator compileRules(Map node, Resolver resolve) { + String reference = Json.string(node.get("schema")); + if (reference != null) { + return (value, run, at) -> { + if (run.depth >= MAX_REFERENCE_DEPTH) { + resolve.referenceTooDeep(run.schema); + report(run, at, "refineError", new LinkedHashMap<>()); + return; + } + Resolver.Resolved target = resolve.resolve(reference); + if (target == null) { + report(run, at, "schemaNotFound", params("schema", reference)); + return; + } + run.depth++; + try { + target.validate.validate(value, run, at); + } finally { + run.depth--; + } + }; + } + + if (node.get("oneOf") instanceof List) return compileOneOf(node, resolve); + + // A listed timestamp must still be one, so its typed rules run after the value matches. + Validator typed = "date-time".equals(node.get("format")) ? compileTyped(node, resolve) : null; + + if (node.containsKey("const")) { + Object constant = node.get("const"); + return (value, run, at) -> { + if (!Json.same(value, constant)) report(run, at, "const", params("const", constant)); + else if (typed != null) typed.validate(value, run, at); + }; + } + + if (node.get("enum") instanceof List) { + List options = (List) node.get("enum"); + return (value, run, at) -> { + for (Object option : options) { + if (Json.same(value, option)) { + if (typed != null) typed.validate(value, run, at); + return; + } + } + List> entries = new ArrayList<>(); + for (Object option : options) entries.add(optionEntry(node, option)); + Map params = params("options", new ArrayList<>(options)); + putTitles(params, entries); + report(run, at, "enum", params); + }; + } + + return compileTyped(node, resolve); + } + + /** A node's rules by its type: the type itself, then the keywords that type takes. */ + private static Validator compileTyped(Map node, Resolver resolve) { + String type = Json.string(node.get("type")); + boolean known = type != null && List.of("string", "integer", "number", "boolean", "array", "object").contains(type); + // With a type, only its own keywords can apply, so only they are compiled. + Validator string = type == null || type.equals("string") ? compileString(node, resolve) : null; + Validator number = type == null || type.equals("integer") || type.equals("number") ? compileNumber(node) : null; + Validator array = type == null || type.equals("array") ? compileArray(node, resolve) : null; + Validator object = type == null || type.equals("object") ? compileObject(node, resolve) : null; + + return (value, run, at) -> { + if (known && !typeMatches(type, value)) { + report(run, at, "type", params("type", type, "received", Json.kindOf(value))); + return; + } + if (value instanceof String) { if (string != null) string.validate(value, run, at); } + else if (value instanceof Number) { if (number != null) number.validate(value, run, at); } + else if (value instanceof List) { if (array != null) array.validate(value, run, at); } + else if (value instanceof Map) { if (object != null) object.validate(value, run, at); } + }; + } + + /** The value at a dot path inside a value, for {@code input} leaves, or {@link ConditionReader#ABSENT}. */ + static Object readInput(Object value, String path) { + Object current = value; + for (String part : path.split("\\.", -1)) { + if (current instanceof Map) { + Map map = (Map) current; + if (!map.containsKey(part)) return ConditionReader.ABSENT; + current = map.get(part); + } else if (current instanceof List) { + // A list's own keys are its indexes, as JavaScript reads `items.0.name`. + List list = (List) current; + if (!part.matches("0|[1-9][0-9]{0,8}") || Integer.parseInt(part) >= list.size()) { + return "length".equals(part) ? list.size() : ConditionReader.ABSENT; + } + current = list.get(Integer.parseInt(part)); + } else { + return ConditionReader.ABSENT; + } + } + return current; + } + + /** A reader of the value at a node, so a mutation in {@code address} reads the address's own fields. */ + static ConditionReader inputReader(Object value) { + return path -> readInput(value, path); + } + + /** + * Where the rule an issue reports sits in a node's rules, such as + * {@code properties.taxId.pattern}, and whether the walk reached it, which it + * does not through a reference or a {@code oneOf}. + */ + private static boolean ruleOf(Object rules, List path, String code, List at) { + // A missing or an extra key is a rule of the object around it. + boolean parent = code.equals("required") || code.equals("additionalProperties"); + List steps = parent ? path.subList(0, path.size() - 1) : path; + Object current = rules; + for (Object step : steps) { + Map node = Json.map(current); + Map properties = node == null ? null : Json.map(node.get("properties")); + if (step instanceof String && properties != null && properties.containsKey(step)) { + at.add("properties"); + at.add(step); + current = properties.get(step); + } else if (step instanceof Integer && node != null && node.get("items") instanceof Map) { + at.add("items"); + current = node.get("items"); + } else if (node != null && node.get("additionalProperties") instanceof Map) { + at.add("additionalProperties"); + current = node.get("additionalProperties"); + } else { + return false; + } + } + if (code.equals("required")) at.add("required"); + else if (code.equals("additionalProperties")) { + at.add("properties"); + at.add(path.get(path.size() - 1)); + } else at.add(code); + return true; + } + + /** Whether an operation's path reaches a rule, as a prefix of it or, when the rule was reached, beyond it. */ + private static boolean reaches(List operation, List rule, boolean whole) { + for (int index = 0; index < Math.min(operation.size(), rule.size()); index++) { + Object part = operation.get(index); + // A selector picks an item by its fields, as any item can. + if (part instanceof Map) continue; + if (!samePart(part, rule.get(index))) return false; + } + return operation.size() <= rule.size() || whole; + } + + private static boolean samePart(Object part, Object rule) { + if (part instanceof Number && rule instanceof Number) return Json.number(part) == Json.number(rule); + return part != null && part.equals(rule); + } + + @SuppressWarnings("unchecked") + private static List> mutationsOf(Map node) { + List> mutations = new ArrayList<>(); + if (node.get("mutations") instanceof List) { + for (Object mutation : (List) node.get("mutations")) { + mutations.add(mutation instanceof Map ? (Map) mutation : new LinkedHashMap<>()); + } + } + return mutations; + } + + static boolean hasMutations(Object node) { + Object mutations = Json.get(node, "mutations"); + return mutations instanceof List && !((List) mutations).isEmpty(); + } + + /** Which of a node's mutations match the value at it, as an id such as {@code 0,2,}. */ + static String matchingMutations(Map node, Object value, Map context, Resolver resolve, + String schema) { + List> mutations = mutationsOf(node); + ConditionReader input = inputReader(value); + StringBuilder id = new StringBuilder(); + for (int index = 0; index < mutations.size(); index++) { + if (resolve.match(mutations.get(index).get("conditions"), context, input, schema)) id.append(index).append(','); + } + return id.toString(); + } + + /** A node's rules with the mutations an id names applied in order, without {@code mutations}, the same object for the same id. */ + @SuppressWarnings("unchecked") + static Map mutatedRules(Map node, String id, Resolver resolve) { + return resolve.mutated(node, id, () -> { + List> mutations = mutationsOf(node); + Object rules = new LinkedHashMap<>(node); + ((Map) rules).remove("mutations"); + for (String index : id.split(",")) { + if (index.isEmpty()) continue; + Object operations = mutations.get(Integer.parseInt(index)).get("operations"); + rules = VariableMutations.applyVariableOperations(rules, operations instanceof List ? (List) operations : null); + } + return (Map) rules; + }); + } + + private static final class Variant { + final Validator validate; + final Map rules; + final List matched; + + Variant(Validator validate, Map rules, List matched) { + this.validate = validate; + this.rules = rules; + this.matched = matched; + } + } + + /** + * A node whose rules change under conditions: each value is validated against + * the node with every mutation whose conditions match applied, in order. Each + * combination of matches compiles once and is kept for the node. An issue whose + * rule a matching mutation set or changed names the last such mutation. + */ + private static Validator compileMutations(Map node, Resolver resolve) { + List> mutations = mutationsOf(node); + Map variants = new ConcurrentHashMap<>(); + return (value, run, at) -> { + String id = matchingMutations(node, value, run.sources.info.getContext(), resolve, run.schema); + Variant variant = variants.get(id); + if (variant == null) { + Map rules = mutatedRules(node, id, resolve); + List matched = new ArrayList<>(); + for (String index : id.split(",")) if (!index.isEmpty()) matched.add(Integer.parseInt(index)); + variant = new Variant(compileNode(rules, resolve), rules, matched); + variants.put(id, variant); + } + int start = run.issues.size(); + variant.validate.validate(value, run, at); + if (variant.matched.isEmpty()) return; + for (int position = start; position < run.issues.size(); position++) { + SchemaIssue issue = run.issues.get(position); + // A mutation inside the node applies last, so its claim stands. + if (issue.getMutation() != null) continue; + List relative = issue.getPath().subList(Math.min(at.path.size(), issue.getPath().size()), issue.getPath().size()); + List rule = new ArrayList<>(); + boolean whole = ruleOf(variant.rules, relative, issue.getCode(), rule); + for (int index = variant.matched.size() - 1; index >= 0; index--) { + Map mutation = mutations.get(variant.matched.get(index)); + if (setsRule(mutation, issue, rule, whole)) { + run.issues.set(position, issue.withMutation(Json.string(mutation.get("key")))); + break; + } + } + } + }; + } + + /** Whether a mutation set or changed the rule an issue reports, or, for an issue entry, the node's {@code issues}. */ + private static boolean setsRule(Map mutation, SchemaIssue issue, List rule, boolean whole) { + if (!(mutation.get("operations") instanceof List)) return false; + for (Object operation : (List) mutation.get("operations")) { + List path = Json.list(Json.get(operation, "path")); + if (path == null) continue; + if (issue.getCode().equals("refine") ? path.contains("issues") : reaches(path, rule, whole)) return true; + } + return false; + } + + /** + * An object's {@code issues}: after its own rules, unless an issue of shape + * sits anywhere inside it, each entry whose conditions match reports its issue + * at its path, with that field's title and the messages around it. + */ + private static Validator compileIssues(Map node, Validator rules, Resolver resolve) { + List entries = (List) node.get("issues"); + return (value, run, at) -> { + int shape = run.shape; + rules.validate(value, run, at); + if (run.shape != shape || !(value instanceof Map)) return; + ConditionReader input = inputReader(value); + for (Object item : entries) { + Map entry = Json.map(item); + if (entry == null) continue; + if (!resolve.match(entry.get("conditions"), run.sources.info.getContext(), input, run.schema)) continue; + String path = Json.string(entry.get("path")); + List parts = path == null || path.isEmpty() ? List.of() : Arrays.asList(path.split("\\.", -1)); + List scopes = new ArrayList<>(at.scopes); + Object field = node; + for (int index = 0; index < parts.size(); index++) { + Map resolved = resolveNode(field, resolve); + Map properties = resolved == null ? null : Json.map(resolved.get("properties")); + field = properties != null ? properties.get(parts.get(index)) : null; + ownScopes(field, at.mpath.size() + index + 1, resolve, scopes); + } + List issuePath = new ArrayList<>(at.path); + issuePath.addAll(parts); + List mpath = new ArrayList<>(at.mpath); + mpath.addAll(parts); + report(run, at, "refine", params("refine", entry.get("key")), issuePath, + new Messages.Lookup(mpath, scopes, parts.isEmpty() ? at.title : titleOf(field, resolve), + Json.string(entry.get("message"))), null); + } + }; + } + + /** Compiles a schema node into a validator, with its messages and title in scope. */ + static Validator compileNode(Object value, Resolver resolve) { + Map node = Json.map(value); + if (node == null) return Validator.NONE; + if (hasMutations(node)) return compileMutations(node, resolve); + Validator own = compileRules(node, resolve); + Validator rules = node.get("issues") instanceof List && !((List) node.get("issues")).isEmpty() + ? compileIssues(node, own, resolve) : own; + Map messages = Json.map(node.get("messages")); + String title = Json.string(Json.get(node.get("annotations"), "title")); + if (messages == null && title == null) return rules; + return (input, run, at) -> { + List scopes = at.scopes; + if (messages != null) { + scopes = new ArrayList<>(at.scopes); + scopes.add(new Messages.Scope(messages, at.mpath.size())); + } + // A reference's own title wins over the title of the schema it references. + rules.validate(input, run, new Position(at.path, at.mpath, scopes, at.title != null ? at.title : title)); + }; + } + + static List append(List list, T item) { + List copy = new ArrayList<>(list.size() + 1); + copy.addAll(list); + copy.add(item); + return copy; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldConstraints.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldConstraints.java new file mode 100644 index 0000000..0bbc5b6 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldConstraints.java @@ -0,0 +1,69 @@ +package com.featurevisor.schemas; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; + +/** + * The HTML validation attributes a field's rules imply, such as + * {@code required} and {@code maxlength}, for a template to render on its input. + * Each is null when the rules do not set it. + */ +public final class FieldConstraints { + static final FieldConstraints NONE = new FieldConstraints(false, null, null, null, null, null, false); + + private final boolean required; + private final Integer minLength; + private final Integer maxLength; + private final Number min; + private final Number max; + private final Number step; + private final boolean multiple; + + FieldConstraints(boolean required, Integer minLength, Integer maxLength, Number min, Number max, Number step, boolean multiple) { + this.required = required; + this.minLength = minLength; + this.maxLength = maxLength; + this.min = min; + this.max = max; + this.step = step; + this.multiple = multiple; + } + + /** Whether an input left empty fails the rules. */ + public boolean isRequired() { return required; } + public Integer getMinLength() { return minLength; } + public Integer getMaxLength() { return maxLength; } + public Number getMin() { return min; } + public Number getMax() { return max; } + /** 1 for an integer. */ + public Number getStep() { return step; } + /** Whether the field is a list, as a multiple select is. */ + public boolean isMultiple() { return multiple; } + + /** The constraints as HTML attributes, such as {@code required} and {@code maxlength}, only those set. */ + public Map toAttributes() { + Map attributes = new LinkedHashMap<>(); + if (required) attributes.put("required", true); + if (minLength != null) attributes.put("minlength", minLength); + if (maxLength != null) attributes.put("maxlength", maxLength); + if (min != null) attributes.put("min", min); + if (max != null) attributes.put("max", max); + if (step != null) attributes.put("step", step); + if (multiple) attributes.put("multiple", true); + return Collections.unmodifiableMap(attributes); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof FieldConstraints)) return false; + return toAttributes().equals(((FieldConstraints) other).toAttributes()); + } + + @Override + public int hashCode() { return Objects.hash(toAttributes()); } + + @Override + public String toString() { return "FieldConstraints" + toAttributes(); } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java new file mode 100644 index 0000000..62b80bc --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java @@ -0,0 +1,24 @@ +package com.featurevisor.schemas; + +/** What a field's rules make it, for choosing an input. */ +public enum FieldKind { + TEXT("text"), + DATE_TIME("date-time"), + VERSION("version"), + NUMBER("number"), + BOOLEAN("boolean"), + SELECT("select"), + MULTISELECT("multiselect"), + OBJECT("object"), + LIST("list"); + + private final String value; + + FieldKind(String value) { this.value = value; } + + /** The kind as the JavaScript package names it, such as {@code date-time}. */ + public String getValue() { return value; } + + @Override + public String toString() { return value; } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FlattenedIssues.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FlattenedIssues.java new file mode 100644 index 0000000..4f1f4f8 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FlattenedIssues.java @@ -0,0 +1,35 @@ +package com.featurevisor.schemas; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Issues' messages grouped by field, in the shape of Zod's {@code flattenError}. */ +public final class FlattenedIssues { + private final List formErrors; + private final Map> fieldErrors; + + private FlattenedIssues(List formErrors, Map> fieldErrors) { + this.formErrors = Collections.unmodifiableList(formErrors); + this.fieldErrors = Collections.unmodifiableMap(fieldErrors); + } + + static FlattenedIssues of(List issues) { + List form = new ArrayList<>(); + Map> fields = new LinkedHashMap<>(); + for (SchemaIssue issue : issues) { + if (issue.getPath().isEmpty()) form.add(issue.getMessage()); + else fields.computeIfAbsent(issue.getField(), key -> new ArrayList<>()).add(issue.getMessage()); + } + fields.replaceAll((key, messages) -> Collections.unmodifiableList(messages)); + return new FlattenedIssues(form, fields); + } + + /** Messages about the value as a whole. */ + public List getFormErrors() { return formErrors; } + + /** Messages by field name with dots, such as {@code displayName} or {@code items.0.name}. */ + public Map> getFieldErrors() { return fieldErrors; } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java new file mode 100644 index 0000000..0a07fc9 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java @@ -0,0 +1,61 @@ +package com.featurevisor.schemas; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * What a form brings to a schema's handle: its own messages by field, + * refinements, and option sources. Build one once and reuse it, since + * {@link Schemas#get(String, HandleOptions)} keeps a handle per options object. + */ +public final class HandleOptions { + private final Map messages = new LinkedHashMap<>(); + private final List refinements = new ArrayList<>(); + private final List optionSources = new ArrayList<>(); + + /** + * A message for an issue code at a field, such as + * {@code message("email", "required", "Enter your email")}. An empty field is + * the value itself, {@code items[].name} every item's name, and {@code labels.*} + * every value of an open object. + */ + public HandleOptions message(String field, String code, String template) { + return put(field, code, template); + } + + public HandleOptions message(String field, String code, SchemaMessage message) { + return put(field, code, message); + } + + @SuppressWarnings("unchecked") + private HandleOptions put(String field, String code, Object message) { + Map node = messages; + for (String step : Paths.messagePath(field)) { + Object child = node.get(step); + if (!(child instanceof Map)) { + child = new LinkedHashMap(); + node.put(step, child); + } + node = (Map) child; + } + node.put(code, message); + return this; + } + + public HandleOptions refine(Refinement... refinements) { + Collections.addAll(this.refinements, refinements); + return this; + } + + public HandleOptions optionSource(OptionSource... sources) { + Collections.addAll(this.optionSources, sources); + return this; + } + + Map getMessages() { return messages; } + List getRefinements() { return refinements; } + List getOptionSources() { return optionSources; } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/IssueTranslator.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/IssueTranslator.java new file mode 100644 index 0000000..af063a9 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/IssueTranslator.java @@ -0,0 +1,7 @@ +package com.featurevisor.schemas; + +/** The last step for every issue, such as translating its chosen message. Returning null keeps the message. */ +@FunctionalInterface +public interface IssueTranslator { + String translate(SchemaIssue issue, MessageInfo info); +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Json.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Json.java new file mode 100644 index 0000000..d8a5fea --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Json.java @@ -0,0 +1,253 @@ +package com.featurevisor.schemas; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * Values as JSON has them, the way the JavaScript package reads them: maps with + * string keys, lists, strings, numbers compared as doubles, booleans and null. + */ +final class Json { + private static final ObjectMapper MAPPER = new ObjectMapper(); + + private Json() {} + + static boolean isMap(Object value) { + return value instanceof Map; + } + + @SuppressWarnings("unchecked") + static Map map(Object value) { + return value instanceof Map ? (Map) value : null; + } + + static List list(Object value) { + return value instanceof List ? (List) value : null; + } + + /** A key's value in a map, or null without the key or the map. */ + static Object get(Object map, String key) { + return map instanceof Map ? ((Map) map).get(key) : null; + } + + static boolean has(Object map, String key) { + return map instanceof Map && ((Map) map).containsKey(key); + } + + static String string(Object value) { + return value instanceof String ? (String) value : null; + } + + /** A number's value as a double, as JavaScript holds every number. */ + static double number(Object value) { + return ((Number) value).doubleValue(); + } + + static boolean isNumber(Object value) { + return value instanceof Number; + } + + static boolean isFiniteNumber(Object value) { + return value instanceof Number && Double.isFinite(number(value)); + } + + static boolean isInteger(Object value) { + if (!isFiniteNumber(value)) return false; + double number = number(value); + return Math.rint(number) == number; + } + + static boolean isPrimitive(Object value) { + return value == null || value instanceof String || value instanceof Boolean || isFiniteNumber(value); + } + + /** A string's length in code points, as JSON Schema counts it, so an emoji counts one and a lone surrogate one. */ + static int codePointLength(String value) { + return value.codePointCount(0, value.length()); + } + + /** Deep equality of JSON values: lists item by item, maps key by key in any order, numbers by value. */ + static boolean same(Object first, Object second) { + if (first == second) return true; + if (first == null || second == null) return false; + if (first instanceof Number && second instanceof Number) return number(first) == number(second); + if (first instanceof String && second instanceof String) return first.equals(second); + if (first instanceof Boolean && second instanceof Boolean) return first.equals(second); + if (first instanceof List && second instanceof List) { + List one = (List) first; + List other = (List) second; + if (one.size() != other.size()) return false; + for (int index = 0; index < one.size(); index++) { + if (!same(one.get(index), other.get(index))) return false; + } + return true; + } + if (first instanceof Map && second instanceof Map) { + Map one = (Map) first; + Map other = (Map) second; + if (one.size() != other.size()) return false; + for (Map.Entry entry : one.entrySet()) { + if (!other.containsKey(entry.getKey()) || !same(entry.getValue(), other.get(entry.getKey()))) return false; + } + return true; + } + return false; + } + + /** The kind of a value, as an issue names what it received. */ + static String kindOf(Object value) { + if (value == null) return "null"; + if (value instanceof List) return "array"; + if (value instanceof Map) return "object"; + if (value instanceof String) return "string"; + if (value instanceof Boolean) return "boolean"; + if (value instanceof Number) { + double number = number(value); + if (Double.isFinite(number)) return "number"; + return Double.isNaN(number) ? "NaN" : number > 0 ? "Infinity" : "-Infinity"; + } + // A value JSON cannot hold, such as an Instant, is named by its class, as JavaScript names a Date. + return value.getClass().getSimpleName().toLowerCase(); + } + + /** + * A value as maps, lists and primitives, the same object when it already is + * one. A Jackson {@code JsonNode}, an array or a collection is converted, and + * any other object, such as a request record, through Jackson. + */ + static Object plain(Object value) { + if (isPlain(value, 0)) return value; + return convert(value); + } + + private static boolean isPlain(Object value, int depth) { + if (value == null || value instanceof String || value instanceof Boolean || value instanceof Number) return true; + if (depth > 256) return false; + if (value instanceof List) { + for (Object item : (List) value) if (!isPlain(item, depth + 1)) return false; + return true; + } + if (value instanceof Map) { + for (Map.Entry entry : ((Map) value).entrySet()) { + if (!(entry.getKey() instanceof String) || !isPlain(entry.getValue(), depth + 1)) return false; + } + return true; + } + return false; + } + + private static Object convert(Object value) { + if (value == null || value instanceof String || value instanceof Boolean || value instanceof Number) return value; + if (value instanceof JsonNode) return MAPPER.convertValue(value, Object.class); + if (value instanceof Map) { + Map copy = new LinkedHashMap<>(); + for (Map.Entry entry : ((Map) value).entrySet()) { + copy.put(String.valueOf(entry.getKey()), convert(entry.getValue())); + } + return copy; + } + if (value instanceof Collection) { + List copy = new ArrayList<>(); + for (Object item : (Collection) value) copy.add(convert(item)); + return copy; + } + if (value.getClass().isArray()) { + List copy = new ArrayList<>(); + for (int index = 0; index < Array.getLength(value); index++) copy.add(convert(Array.get(value, index))); + return copy; + } + try { + return MAPPER.convertValue(value, Object.class); + } catch (IllegalArgumentException unconvertible) { + // Kept as it is, so an issue names its kind. + return value; + } + } + + /** A number as JavaScript writes it: {@code 2} for 2.0, {@code 0.0001}, {@code 1e+21}. */ + static String numberText(Number value) { + double number = value.doubleValue(); + if (Double.isNaN(number)) return "NaN"; + if (Double.isInfinite(number)) return number > 0 ? "Infinity" : "-Infinity"; + if (number == 0) return "0"; + double magnitude = Math.abs(number); + if (magnitude >= 1e21 || magnitude < 1e-6) { + String text = Double.toString(number); + int exponent = text.indexOf('E'); + String mantissa = text.substring(0, exponent); + if (mantissa.endsWith(".0")) mantissa = mantissa.substring(0, mantissa.length() - 2); + String power = text.substring(exponent + 1); + return mantissa + "e" + (power.startsWith("-") ? power : "+" + power); + } + return new BigDecimal(Double.toString(number)).stripTrailingZeros().toPlainString(); + } + + /** JSON text as JavaScript's {@code JSON.stringify} writes it, for messages. */ + static String stringify(Object value) { + StringBuilder out = new StringBuilder(); + write(out, value); + return out.toString(); + } + + private static void write(StringBuilder out, Object value) { + if (value == null) { + out.append("null"); + } else if (value instanceof String) { + writeString(out, (String) value); + } else if (value instanceof Number) { + double number = ((Number) value).doubleValue(); + out.append(Double.isFinite(number) ? numberText((Number) value) : "null"); + } else if (value instanceof Boolean) { + out.append(value); + } else if (value instanceof List) { + out.append('['); + Iterator items = ((List) value).iterator(); + while (items.hasNext()) { + write(out, items.next()); + if (items.hasNext()) out.append(','); + } + out.append(']'); + } else if (value instanceof Map) { + out.append('{'); + Iterator> entries = ((Map) value).entrySet().iterator(); + while (entries.hasNext()) { + Map.Entry entry = entries.next(); + writeString(out, String.valueOf(entry.getKey())); + out.append(':'); + write(out, entry.getValue()); + if (entries.hasNext()) out.append(','); + } + out.append('}'); + } else { + writeString(out, String.valueOf(value)); + } + } + + private static void writeString(StringBuilder out, String text) { + out.append('"'); + for (int index = 0; index < text.length(); index++) { + char character = text.charAt(index); + switch (character) { + case '"': out.append("\\\""); break; + case '\\': out.append("\\\\"); break; + case '\n': out.append("\\n"); break; + case '\r': out.append("\\r"); break; + case '\t': out.append("\\t"); break; + case '\b': out.append("\\b"); break; + case '\f': out.append("\\f"); break; + default: + if (character < 0x20) out.append(String.format("\\u%04x", (int) character)); + else out.append(character); + } + } + out.append('"'); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/MessageInfo.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/MessageInfo.java new file mode 100644 index 0000000..004ccd8 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/MessageInfo.java @@ -0,0 +1,20 @@ +package com.featurevisor.schemas; + +import java.util.Map; +import java.util.function.Supplier; + +/** What a message function and a translator get besides the issue: the context validation uses. */ +public final class MessageInfo { + private final Supplier> context; + private Map merged; + + MessageInfo(Supplier> context) { + this.context = context; + } + + /** The instance's context, with any given to the validation merged over it, merged only when read. */ + public Map getContext() { + if (merged == null) merged = context.get(); + return merged; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Messages.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Messages.java new file mode 100644 index 0000000..0b56e93 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Messages.java @@ -0,0 +1,229 @@ +package com.featurevisor.schemas; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** How issues are worded: the form's messages, the schema's, the application's, then the default. */ +final class Messages { + private Messages() {} + + /** Messages from a schema's {@code messages}, for issues below {@code base}, the depth of the node carrying them. */ + static final class Scope { + final Map messages; + final int base; + + Scope(Map messages, int base) { + this.messages = messages; + this.base = base; + } + } + + /** + * Where an issue's message is looked for: the field's message path, with + * {@code []} for items and {@code *} for an open object's values, the schema + * messages around it, the field's title and an issue entry's own message. + */ + static class Lookup { + final List mpath; + final List scopes; + final String title; + final String own; + + Lookup(List mpath, List scopes, String title, String own) { + this.mpath = mpath; + this.scopes = scopes; + this.title = title; + this.own = own; + } + } + + /** What wording an instance and a form bring, for one validation. */ + static final class Sources { + final Map form; + final Map app; + final MessageInfo info; + + Sources(Map form, Map app, MessageInfo info) { + this.form = form; + this.app = app; + this.info = info; + } + } + + private static Map navigate(Map messages, List steps, int from) { + Object node = messages; + for (int index = from; index < steps.size(); index++) { + if (!(node instanceof Map)) return null; + node = ((Map) node).get(steps.get(index)); + } + return Json.map(node); + } + + private static String formatParam(Object value) { + if (value instanceof List) { + List parts = new ArrayList<>(); + for (Object item : (List) value) parts.add(formatParam(item)); + return String.join(", ", parts); + } + if (value instanceof String) return (String) value; + if (value == null) return "null"; + if (value instanceof Number) return Json.numberText((Number) value); + if (value instanceof Boolean) return value.toString(); + return Json.stringify(value); + } + + private static final Pattern PLACEHOLDER = Pattern.compile("\\{\\{|\\}\\}|\\{([^{}]*)\\}"); + + /** Fills {@code {name}} from params. Lists are joined with commas, and {@code {{} and {@code }}} write braces. */ + static String fillTemplate(String template, Map params) { + Matcher matcher = PLACEHOLDER.matcher(template); + StringBuilder out = new StringBuilder(); + int last = 0; + while (matcher.find()) { + out.append(template, last, matcher.start()); + String match = matcher.group(); + if (match.equals("{{")) out.append('{'); + else if (match.equals("}}")) out.append('}'); + else { + String name = matcher.group(1); + // A name the params lack fills nothing, as `undefined` does in JavaScript. + out.append(params.containsKey(name) ? formatParam(params.get(name)) : ""); + } + last = matcher.end(); + } + out.append(template, last, template.length()); + return out.toString(); + } + + private static String apply(Object message, Map params, MessageInfo info) { + return message instanceof SchemaMessage + ? ((SchemaMessage) message).format(Collections.unmodifiableMap(params), info) + : fillTemplate((String) message, params); + } + + private static String typeName(Object type) { + switch (String.valueOf(type)) { + case "string": return "a string"; + case "integer": return "an integer"; + case "number": return "a number"; + case "boolean": return "a boolean"; + case "object": return "an object"; + case "array": return "an array"; + case "primitive": return "a string, number, boolean or null"; + default: return String.valueOf(type); + } + } + + private static String subject(List path) { + return path.isEmpty() ? "Value" : "Value at " + Json.stringify(Paths.format(path)); + } + + private static String items(Object count) { + return count instanceof Number && Json.number(count) == 1 ? "item" : "items"; + } + + private static String text(Object value) { + return formatParam(value); + } + + /** The default wording of each issue, in lint's English. */ + static String defaultMessage(String code, Map params, List path) { + String at = subject(path); + switch (code) { + case "type": + return at + " must be " + typeName(params.get("type")) + " (got " + params.get("received") + ")."; + case "const": + return at + " must equal " + Json.stringify(params.get("const")) + "."; + case "enum": { + Object listed = params.containsKey("titles") ? params.get("titles") : params.get("options"); + // An option source's lookup knows no list to name. + if (!(listed instanceof List)) return at + " is not one of its choices."; + List names = new ArrayList<>(); + for (Object option : (List) listed) names.add(option instanceof String ? (String) option : Json.stringify(option)); + return at + " must be one of " + String.join(", ", names) + "."; + } + case "minimum": + return at + " must be at least " + text(params.get("minimum")) + " (got " + text(params.get("value")) + ")."; + case "maximum": + return at + " must be at most " + text(params.get("maximum")) + " (got " + text(params.get("value")) + ")."; + case "minLength": + return at + " must be at least " + text(params.get("minLength")) + " characters long (got " + params.get("length") + ")."; + case "maxLength": + return at + " must be at most " + text(params.get("maxLength")) + " characters long (got " + params.get("length") + ")."; + case "pattern": + return at + " does not match the expected pattern."; + case "format": + return "date-time".equals(params.get("format")) + ? at + " must be a timestamp such as 2026-01-31T09:00:00Z." + : at + " must be a version such as 1.2.3."; + case "minItems": + return at + " must have at least " + text(params.get("minItems")) + " " + items(params.get("minItems")) + " (got " + params.get("count") + ")."; + case "maxItems": + return at + " must have at most " + text(params.get("maxItems")) + " " + items(params.get("maxItems")) + " (got " + params.get("count") + ")."; + case "uniqueItems": + return at + " must not repeat items (item " + params.get("index") + " repeats an earlier one)."; + case "required": + return at + " is required."; + case "additionalProperties": + return at + " is not allowed."; + case "oneOf": + return Integer.valueOf(0).equals(params.get("matches")) + ? at + " does not match any of the allowed shapes." + : at + " must match exactly one of the allowed shapes (matched " + params.get("matches") + ")."; + case "refine": + return at + " is not valid."; + case "refineError": + return at + " could not be checked."; + case "schemaNotFound": + return params.containsKey("field") + ? "Field " + Json.stringify(params.get("field")) + " was not found in schema " + Json.stringify(params.get("schema")) + "." + : "Schema " + Json.stringify(params.get("schema")) + " was not found."; + default: + return at + " is not valid."; + } + } + + private static final Pattern LIST_PLACEHOLDER = Pattern.compile("\\{(options|titles)\\}"); + + /** + * The message an issue carries, the first of: a check's own message, the + * form's for the field, the schema's from the outside in, an issue entry's + * own, the application's for the code, and the default. A message is for the + * field it names, never for fields inside it. + */ + static String choose(String code, Map params, List path, Lookup lookup, + Sources sources, String ownMessage) { + if (ownMessage != null) return fillTemplate(ownMessage, params); + // An option source's `enum` names no list, so a wording that fills one in is passed over. + boolean listless = code.equals("enum") && !params.containsKey("options") && !params.containsKey("titles"); + + Map formMessages = sources.form == null ? null : navigate(sources.form, lookup.mpath, 0); + Object form = formMessages == null ? null : formMessages.get(code); + if ((form instanceof String || form instanceof SchemaMessage) && fits(form, listless)) { + return apply(form, params, sources.info); + } + + for (Scope scope : lookup.scopes) { + if (scope.base > lookup.mpath.size()) continue; + Map scopeMessages = navigate(scope.messages, lookup.mpath, scope.base); + Object schemaMessage = scopeMessages == null ? null : scopeMessages.get(code); + if (schemaMessage instanceof String && fits(schemaMessage, listless)) { + return fillTemplate((String) schemaMessage, params); + } + } + if (lookup.own != null && fits(lookup.own, listless)) return fillTemplate(lookup.own, params); + + Object app = sources.app == null ? null : sources.app.get(code); + if (app != null && fits(app, listless)) return apply(app, params, sources.info); + + return defaultMessage(code, params, path); + } + + private static boolean fits(Object message, boolean listless) { + return !listless || !(message instanceof String) || !LIST_PLACEHOLDER.matcher((String) message).find(); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/OptionSource.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/OptionSource.java new file mode 100644 index 0000000..446689e --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/OptionSource.java @@ -0,0 +1,113 @@ +package com.featurevisor.schemas; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletionStage; + +/** + * Choices for a field that come from the application, such as cities from a + * service: {@code search} suggests them as a person types, and {@code lookup} + * checks a value when validating, which fails with {@code enum} when it finds + * nothing. + * + *
{@code
+ * OptionSource.of("cities", "city")
+ *     .search((query, info) -> cities.search(query))
+ *     .lookup((value, info) -> cities.find((String) value))
+ * }
+ */ +public final class OptionSource { + /** Suggestions for a query: values, or maps with a {@code value} and what to show, such as a {@code title}. */ + @FunctionalInterface + public interface Search { + List search(String query, CheckInfo info); + } + + @FunctionalInterface + public interface AsyncSearch { + CompletionStage> search(String query, CheckInfo info); + } + + /** + * The choice for a value, or null, or false, when there is none. A map is + * what the source says about it, such as its {@code title}. + */ + @FunctionalInterface + public interface Lookup { + Object lookup(Object value, CheckInfo info); + } + + @FunctionalInterface + public interface AsyncLookup { + CompletionStage lookup(Object value, CheckInfo info); + } + + private final String key; + private final String path; + private final List reads; + private final String message; + private final Search search; + private final AsyncSearch asyncSearch; + private final Lookup lookup; + private final AsyncLookup asyncLookup; + + private OptionSource(String key, String path, List reads, String message, + Search search, AsyncSearch asyncSearch, Lookup lookup, AsyncLookup asyncLookup) { + this.key = key; + this.path = path == null ? "" : path; + this.reads = reads; + this.message = message; + this.search = search; + this.asyncSearch = asyncSearch; + this.lookup = lookup; + this.asyncLookup = asyncLookup; + } + + /** A source for the field at a path, such as {@code city}, or {@code tags[]} for a list's items. */ + public static OptionSource of(String key, String path) { + return new OptionSource(key, path, Collections.emptyList(), null, null, null, null, null); + } + + public OptionSource search(Search search) { + return new OptionSource(key, path, reads, message, search, null, lookup, asyncLookup); + } + + public OptionSource searchAsync(AsyncSearch search) { + return new OptionSource(key, path, reads, message, null, search, lookup, asyncLookup); + } + + public OptionSource lookup(Lookup lookup) { + return new OptionSource(key, path, reads, message, search, asyncSearch, lookup, null); + } + + public OptionSource lookupAsync(AsyncLookup lookup) { + return new OptionSource(key, path, reads, message, search, asyncSearch, null, lookup); + } + + /** The fields besides its own it reads, such as a country for cities. */ + public OptionSource reads(String... paths) { + return new OptionSource(key, path, Collections.unmodifiableList(Arrays.asList(paths)), message, + search, asyncSearch, lookup, asyncLookup); + } + + /** The message when a lookup finds nothing. */ + public OptionSource message(String message) { + return new OptionSource(key, path, reads, message, search, asyncSearch, lookup, asyncLookup); + } + + public String getKey() { return key; } + public String getPath() { return path; } + public List getReads() { return reads; } + public String getMessage() { return message; } + public boolean canSearch() { return search != null || asyncSearch != null; } + public boolean canLookup() { return lookup != null || asyncLookup != null; } + + Object runSearch(String query, CheckInfo info) { + return asyncSearch != null ? asyncSearch.search(query, info) : search.search(query, info); + } + + Object runLookup(Object value, CheckInfo info) { + return asyncLookup != null ? asyncLookup.lookup(value, info) : lookup.lookup(value, info); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java new file mode 100644 index 0000000..dc8ca4d --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java @@ -0,0 +1,138 @@ +package com.featurevisor.schemas; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +/** Field paths as form libraries write them: {@code address.city}, {@code items.0.name}, {@code items[].name}, {@code labels.*}. */ +final class Paths { + private Paths() {} + + enum Kind { KEY, INDEX, ITEMS, VALUES } + + /** One step of a field path: an object key, an array index, every item, or every value of an open object. */ + static final class Step { + final Kind kind; + final String key; + final int index; + + private Step(Kind kind, String key, int index) { + this.kind = kind; + this.key = key; + this.index = index; + } + + static Step key(String key) { return new Step(Kind.KEY, key, -1); } + static Step index(int index) { return new Step(Kind.INDEX, null, index); } + static final Step ITEMS = new Step(Kind.ITEMS, null, -1); + static final Step VALUES = new Step(Kind.VALUES, null, -1); + + /** The step as a path part: its key, its index, {@code []} or {@code *}. */ + Object part() { + switch (kind) { + case KEY: return key; + case INDEX: return index; + case ITEMS: return "[]"; + default: return "*"; + } + } + } + + private static final Pattern INDEX = Pattern.compile("0|[1-9][0-9]*"); + + /** A number after a dot or in brackets is an index, so {@code items.0} and {@code items[0]} are the same. */ + static List parse(String path) { + List steps = new ArrayList<>(); + if (path == null || path.isEmpty()) return steps; + int index = 0; + StringBuilder key = new StringBuilder(); + while (index < path.length()) { + char character = path.charAt(index); + if (character == '.') { + flush(key, steps); + index++; + } else if (character == '[') { + flush(key, steps); + int end = path.indexOf(']', index); + String inside = end == -1 ? path.substring(index + 1) : path.substring(index + 1, end); + if (inside.isEmpty()) steps.add(Step.ITEMS); + else if (inside.equals("*")) steps.add(Step.VALUES); + else if (isIndex(inside)) steps.add(Step.index(Integer.parseInt(inside))); + else steps.add(Step.key(inside.replaceAll("^[\"']|[\"']$", ""))); + index = end == -1 ? path.length() : end + 1; + } else { + key.append(character); + index++; + } + } + flush(key, steps); + return steps; + } + + private static boolean isIndex(String text) { + return text.length() < 10 && INDEX.matcher(text).matches(); + } + + private static void flush(StringBuilder key, List steps) { + if (key.length() == 0) return; + String text = key.toString(); + if (text.equals("*")) steps.add(Step.VALUES); + else if (isIndex(text)) steps.add(Step.index(Integer.parseInt(text))); + else steps.add(Step.key(text)); + key.setLength(0); + } + + /** A path as a field name with dots, such as {@code items.0.name}. */ + static String format(List path) { + StringBuilder text = new StringBuilder(); + for (Object part : path) { + if (text.length() > 0) text.append('.'); + text.append(part); + } + return text.toString(); + } + + /** A handle's path, such as {@code items[].name}. */ + static String formatSteps(List steps) { + List parts = new ArrayList<>(); + for (Step step : steps) parts.add(step.part()); + return format(parts).replace(".[]", "[]"); + } + + /** The message path of a field: keys, {@code []} for items and {@code *} for an open object's values. */ + static List messagePath(String field) { + List mpath = new ArrayList<>(); + for (Step step : parse(field)) { + mpath.add(step.kind == Kind.KEY ? step.key : step.kind == Kind.VALUES ? "*" : "[]"); + } + return mpath; + } + + /** Whether {@code inner} is {@code outer} or a path inside it. */ + static boolean isAtOrInside(List inner, List outer) { + if (inner.size() < outer.size()) return false; + for (int index = 0; index < outer.size(); index++) { + if (!String.valueOf(inner.get(index)).equals(String.valueOf(outer.get(index)))) return false; + } + return true; + } + + /** Whether a concrete path matches a path with {@code []} and {@code *} steps, at or inside it. */ + static boolean matchesSteps(List path, List steps) { + if (path.size() < steps.size()) return false; + for (int index = 0; index < steps.size(); index++) { + Step step = steps.get(index); + String part = String.valueOf(path.get(index)); + if (step.kind == Kind.INDEX && !part.equals(String.valueOf(step.index))) return false; + if (step.kind == Kind.KEY && !part.equals(step.key)) return false; + } + return true; + } + + /** The steps of a concrete path, for finding the field it names in a schema. */ + static List stepsOf(List path) { + List steps = new ArrayList<>(); + for (Object part : path) steps.add(part instanceof Integer ? Step.index((Integer) part) : Step.key(String.valueOf(part))); + return steps; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java new file mode 100644 index 0000000..120daa3 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java @@ -0,0 +1,139 @@ +package com.featurevisor.schemas; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Pattern; + +/** + * Schema patterns, written for JavaScript's {@code RegExp} without flags, + * compiled to mean the same in {@code java.util.regex}. Without the rewrites, + * Java's {@code $} matches before a final line break, its {@code \s} misses + * Unicode spaces, its {@code .} refuses U+0085, its {@code [} nests classes and + * its {@code {} fails where JavaScript reads a literal brace. + * + *

One difference stays: JavaScript without flags reads a string in UTF-16 + * units, so {@code ^.$} refuses an emoji there and accepts it here. + */ +final class Patterns { + private Patterns() {} + + /** JavaScript's whitespace and line terminators, for {@code \s}. */ + private static final String SPACES = "\\t\\n\\x0B\\f\\r \\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{2028}\\x{2029}\\x{202F}\\x{205F}\\x{3000}\\x{FEFF}"; + /** Everything else, for {@code \S} inside a class. */ + private static final String NOT_SPACES = "\\x{0}-\\x{8}\\x{E}-\\x{1F}\\x{21}-\\x{9F}\\x{A1}-\\x{167F}\\x{1681}-\\x{1FFF}" + + "\\x{200B}-\\x{2027}\\x{202A}-\\x{202E}\\x{2030}-\\x{205E}\\x{2060}-\\x{2FFF}\\x{3001}-\\x{FEFE}\\x{FF00}-\\x{10FFFF}"; + private static final String NOT_DIGITS = "\\x{0}-\\x{2F}\\x{3A}-\\x{10FFFF}"; + private static final String NOT_WORD = "\\x{0}-\\x{2F}\\x{3A}-\\x{40}\\x{5B}-\\x{5E}\\x{60}\\x{7B}-\\x{10FFFF}"; + + private static final Object FAILED = new Object(); + private static final Map CACHE = new ConcurrentHashMap<>(); + + /** The pattern compiled, or null when Java cannot compile it. */ + static Pattern compile(String source) { + Object cached = CACHE.get(source); + if (cached == null) { + try { + cached = Pattern.compile(translate(source)); + } catch (IllegalArgumentException failed) { + cached = FAILED; + } + if (CACHE.size() < 4096) CACHE.put(source, cached); + } + return cached == FAILED ? null : (Pattern) cached; + } + + /** JavaScript's pattern in Java's syntax. */ + static String translate(String source) { + StringBuilder out = new StringBuilder(); + boolean inClass = false; + int length = source.length(); + for (int index = 0; index < length; index++) { + char current = source.charAt(index); + if (current == '\\' && index + 1 < length) { + char code = source.charAt(++index); + switch (code) { + case 'd': out.append(inClass ? "0-9" : "[0-9]"); break; + case 'D': out.append(inClass ? NOT_DIGITS : "[^0-9]"); break; + case 'w': out.append(inClass ? "A-Za-z0-9_" : "[A-Za-z0-9_]"); break; + case 'W': out.append(inClass ? NOT_WORD : "[^A-Za-z0-9_]"); break; + case 's': out.append(inClass ? SPACES : "[" + SPACES + "]"); break; + case 'S': out.append(inClass ? NOT_SPACES : "[^" + SPACES + "]"); break; + case 'v': out.append("\\x0B"); break; + case 'b': out.append(inClass ? "\\x08" : "\\b"); break; + case 'B': out.append(inClass ? "B" : "\\B"); break; + case 'n': case 'r': case 't': case 'f': out.append('\\').append(code); break; + case 'c': case 'x': case 'u': out.append('\\').append(code); break; + case '0': + if (index + 1 < length && Character.isDigit(source.charAt(index + 1))) out.append("\\0"); + else out.append("\\x00"); + break; + default: + if (Character.isDigit(code)) { + // A back reference, which lint refuses in delivered schemas. + out.append('\\').append(code); + } else if (Character.isLetter(code)) { + // Without flags JavaScript reads an unknown escape, such as `\p`, as the letter. + out.append(code); + } else { + out.append('\\').append(code); + } + } + continue; + } + if (inClass) { + if (current == ']') inClass = false; + // Java nests classes on `[` and intersects them on `&&`, where JavaScript reads the characters. + if (current == '[' || current == '&') out.append('\\'); + out.append(current); + continue; + } + switch (current) { + case '[': + if (source.startsWith("[^]", index)) { + // Any character, as JavaScript reads an empty negated class. + out.append("[\\x{0}-\\x{10FFFF}]"); + index += 2; + } else if (source.startsWith("[]", index)) { + // Nothing, as JavaScript reads an empty class. + out.append("(?!)"); + index += 1; + } else { + inClass = true; + out.append('['); + if (index + 1 < length && source.charAt(index + 1) == '^') { + out.append('^'); + index++; + } + } + break; + case '.': out.append("[^\\n\\r\\x{2028}\\x{2029}]"); break; + case '$': out.append("\\z"); break; + case '{': { + int end = quantifierEnd(source, index); + if (end == -1) out.append("\\{"); + else { + out.append(source, index, end + 1); + index = end; + } + break; + } + case '}': out.append("\\}"); break; + default: out.append(current); + } + } + return out.toString(); + } + + /** Where a `{` that starts `{n}`, `{n,}` or `{n,m}` ends, which JavaScript reads as a quantifier, or -1. */ + private static int quantifierEnd(String source, int start) { + int index = start + 1; + int digits = 0; + while (index < source.length() && Character.isDigit(source.charAt(index))) { index++; digits++; } + if (digits == 0 || index >= source.length()) return -1; + if (source.charAt(index) == '}') return index; + if (source.charAt(index) != ',') return -1; + index++; + while (index < source.length() && Character.isDigit(source.charAt(index))) index++; + return index < source.length() && source.charAt(index) == '}' ? index : -1; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java new file mode 100644 index 0000000..3e93a03 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java @@ -0,0 +1,18 @@ +package com.featurevisor.schemas; + +import java.util.List; + +/** Where validation is in a value: its path, its message path and the schema messages around it. */ +final class Position extends Messages.Lookup { + final List path; + + Position(List path, List mpath, List scopes, String title) { + super(mpath, scopes, title, null); + this.path = path; + } + + Position(List path, Messages.Lookup lookup) { + super(lookup.mpath, lookup.scopes, lookup.title, lookup.own); + this.path = path; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Refinement.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Refinement.java new file mode 100644 index 0000000..873295a --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Refinement.java @@ -0,0 +1,87 @@ +package com.featurevisor.schemas; + +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CompletionStage; + +/** + * A check in code that rules cannot express, such as whether a username is + * taken: it gets the value at its path and passes with {@code true}. It runs + * after the rules, and only where they found no issue at or inside its path, + * nor in a field it {@link #reads}. + * + *
{@code
+ * Refinement.of("passwordsMatch", "confirm", (value, info) -> value.equals(info.read("password")))
+ *     .reads("password")
+ *     .message("Passwords must match")
+ * }
+ */ +public final class Refinement { + /** A check that answers at once. */ + @FunctionalInterface + public interface Check { + boolean test(Object value, CheckInfo info); + } + + /** A check that answers later, such as one asking a server. */ + @FunctionalInterface + public interface AsyncCheck { + CompletionStage test(Object value, CheckInfo info); + } + + private final String key; + private final String path; + private final List reads; + private final String message; + private final Check check; + private final AsyncCheck asyncCheck; + + private Refinement(String key, String path, List reads, String message, Check check, AsyncCheck asyncCheck) { + this.key = key; + this.path = path == null ? "" : path; + this.reads = reads; + this.message = message; + this.check = check; + this.asyncCheck = asyncCheck; + } + + /** A check of the whole value. */ + public static Refinement of(String key, Check check) { + return of(key, "", check); + } + + /** A check of the value at a path, such as {@code confirm}, {@code items[].name} or {@code labels.*}. */ + public static Refinement of(String key, String path, Check check) { + return new Refinement(key, path, Collections.emptyList(), null, check, null); + } + + public static Refinement async(String key, AsyncCheck check) { + return async(key, "", check); + } + + public static Refinement async(String key, String path, AsyncCheck check) { + return new Refinement(key, path, Collections.emptyList(), null, null, check); + } + + /** The fields besides its own it reads, so their issues hold it back. */ + public Refinement reads(String... paths) { + return new Refinement(key, path, Collections.unmodifiableList(Arrays.asList(paths)), message, check, asyncCheck); + } + + /** Its message, a template that schema messages for its key can replace. */ + public Refinement message(String message) { + return new Refinement(key, path, reads, message, check, asyncCheck); + } + + public String getKey() { return key; } + public String getPath() { return path; } + public List getReads() { return reads; } + public String getMessage() { return message; } + public boolean isAsync() { return asyncCheck != null; } + + /** Its answer: a Boolean, or a stage that completes with one. */ + Object run(Object value, CheckInfo info) { + return asyncCheck != null ? asyncCheck.test(value, info) : (Object) check.test(value, info); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java new file mode 100644 index 0000000..591e1a9 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java @@ -0,0 +1,35 @@ +package com.featurevisor.schemas; + +import com.featurevisor.sdk.ConditionReader; +import java.util.Map; + +/** Schemas of the current datafile by key, compiled, with the matcher conditions use and the caches of mutated rules. */ +interface Resolver { + /** A compiled schema and its node, or null when the datafile has none. */ + Resolved resolve(String key); + + /** A schema's node, without compiling it, for what reads a node: references, annotations and messages. */ + Map node(String key); + + /** Reports, once, a schema that follows references deeper than any value can need, which fails the value. */ + void referenceTooDeep(String schema); + + /** Answers conditions with the SDK's engine, for the schema being validated. */ + boolean match(Object conditions, Map context, ConditionReader input, String schema); + + /** A node's rules with a combination of its mutations applied, the same object for the same combination. */ + Map mutated(Map node, String id, java.util.function.Supplier> make); + + /** Reports, once, a pattern Java cannot compile, which fails every value. */ + void unsupportedPattern(String pattern); + + final class Resolved { + final Map node; + final Validator validate; + + Resolved(Map node, Validator validate) { + this.node = node; + this.validate = validate; + } + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java new file mode 100644 index 0000000..f8b2995 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java @@ -0,0 +1,44 @@ +package com.featurevisor.schemas; + +import java.util.ArrayList; +import java.util.List; + +/** One validation: where issues go and how they are worded. */ +final class Run { + final String schema; + final List issues; + final Messages.Sources sources; + final IssueTranslator translate; + /** Counting {@code oneOf} branches only notes whether a branch failed, without wording anything. */ + final boolean trial; + boolean failed; + /** How many issues of shape were found, which hold back the {@code issues} of every object around them. */ + int shape; + /** How many references the walk follows at this point, which only a value nested as deep can need. */ + int depth; + + Run(String schema, Messages.Sources sources, IssueTranslator translate) { + this(schema, new ArrayList<>(), sources, translate, false); + } + + private Run(String schema, List issues, Messages.Sources sources, IssueTranslator translate, boolean trial) { + this.schema = schema; + this.issues = issues; + this.sources = sources; + this.translate = translate; + this.trial = trial; + } + + /** A run for one {@code oneOf} branch, which only notes whether it fails. */ + Run trial() { + Run trial = new Run(schema, new ArrayList<>(), sources, translate, true); + trial.shape = shape; + trial.depth = depth; + return trial; + } + + /** The same run without the translator, for knowing which fields have issues. */ + Run untranslated() { + return new Run(schema, new ArrayList<>(), sources, null, false); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java new file mode 100644 index 0000000..981bbdb --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -0,0 +1,729 @@ +package com.featurevisor.schemas; + +import com.featurevisor.sdk.FeaturevisorUnsubscribe; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutionException; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +/** + * A schema's handle, or a field's. Everything it does reads the current + * datafile when it is used, so one handle stays right for the life of an + * application, and handles are safe to share between threads. + * + *
{@code
+ * SchemaHandle signUp = schemas.get("signUp");
+ * ValidationResult result = signUp.validate(request);
+ * FieldConstraints email = signUp.at("email").getConstraints();
+ * }
+ */ +public final class SchemaHandle { + private enum CheckKind { REFINE, LOOKUP } + + /** A check in code, with its path read once, relative to the handle that runs it. */ + private static final class Check { + final Object owner; + final CheckKind kind; + final List steps; + final List> reads; + + Check(Object owner, CheckKind kind, List steps, List> reads) { + this.owner = owner; + this.kind = kind; + this.steps = steps; + this.reads = reads; + } + } + + /** A view's input and context, and the depth of the handle {@code withInput} was called on, where the input sits. */ + private static final class View { + final Object values; + final Map context; + final int from; + + View(Object values, Map context, int from) { + this.values = values; + this.context = context; + this.from = from; + } + } + + /** What a handle needs from the instance that made it. */ + static final class Context { + final Store store; + final SchemasOptions options; + final Schemas schemas; + + Context(Store store, SchemasOptions options, Schemas schemas) { + this.store = store; + this.options = options; + this.schemas = schemas; + } + } + + private static final class Located { + final Validator validate; + final Object node; + final Messages.Lookup lookup; + + Located(Validator validate, Object node, Messages.Lookup lookup) { + this.validate = validate; + this.node = node; + this.lookup = lookup; + } + } + + private static final class Described { + final Object node; + final boolean required; + + Described(Object node, boolean required) { + this.node = node; + this.required = required; + } + } + + /** The node, in a view resolved, and what members derived from it, until the datafile changes. */ + private static final class Memo { + final Object entry; + final String revision; + final Described described; + final Map made = new ConcurrentHashMap<>(); + + Memo(Object entry, String revision, Described described) { + this.entry = entry; + this.revision = revision; + this.described = described; + } + } + + private final Context context; + private final String key; + private final List steps; + private final String path; + private final HandleOptions options; + private final View view; + private final Map handles = new ConcurrentHashMap<>(); + private volatile Memo memo; + + SchemaHandle(Context context, String key, HandleOptions options) { + this(context, key, options, List.of(), null); + } + + private SchemaHandle(Context context, String key, HandleOptions options, List steps, View view) { + this.context = context; + this.key = key; + this.options = options; + this.steps = Collections.unmodifiableList(new ArrayList<>(steps)); + this.view = view; + this.path = Paths.formatSteps(steps); + } + + /** The schema's key, such as {@code signUp}. */ + public String getKey() { return key; } + + /** The field's path in its schema, such as {@code address.city} or {@code items[].name}, or empty for the schema. */ + public String getPath() { return path; } + + /** Its own key in the object it sits in, such as {@code city}, or empty for the schema itself. */ + public String getName() { + if (steps.isEmpty()) return ""; + return String.valueOf(steps.get(steps.size() - 1).part()); + } + + // Validation + + /** Validates a value: maps, lists and primitives, a Jackson {@code JsonNode}, or an object Jackson can convert. */ + public ValidationResult validate(Object value) { + return validate(value, null); + } + + /** + * Validates a value with a context merged over the instance's. Checks in code + * that answer later are waited for, so prefer {@link #validateAsync} for those + * where blocking a thread matters. + */ + public ValidationResult validate(Object value, Map context) { + CompletableFuture result = validateAsync(value, context); + try { + return result.get(); + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + result.cancel(true); + throw new CompletionException(interrupted); + } catch (ExecutionException failed) { + Throwable cause = failed.getCause(); + if (cause instanceof RuntimeException) throw (RuntimeException) cause; + if (cause instanceof Error) throw (Error) cause; + throw new CompletionException(cause); + } + } + + public CompletableFuture validateAsync(Object value) { + return validateAsync(value, null); + } + + /** + * Validates a value, completing when every check in code has answered. The + * rules and checks that answer at once run on the calling thread. + */ + public CompletableFuture validateAsync(Object value, Map context) { + Object input = Json.plain(value); + Run run = run(context); + Located located = applyRules(input, run); + List checks = located == null ? List.of() : checks(); + if (checks.isEmpty()) return CompletableFuture.completedFuture(new ValidationResult(value, run.issues)); + return runChecks(value, input, context, run, located, checks); + } + + public boolean isValid(Object value) { + return validate(value).isValid(); + } + + public boolean isValid(Object value, Map context) { + return validate(value, context).isValid(); + } + + /** The value, or a {@link SchemaValidationException} with the issues found. */ + public Object parse(Object value) { + return parse(value, null); + } + + public Object parse(Object value, Map context) { + ValidationResult result = validate(value, context); + if (!result.isValid()) throw new SchemaValidationException(key, result.getIssues()); + return value; + } + + /** The schema's own rules, without checks in code, which always answers at once. */ + public ValidationResult validateRules(Object value) { + return validateRules(value, null); + } + + public ValidationResult validateRules(Object value, Map context) { + Run run = run(context); + applyRules(Json.plain(value), run); + return new ValidationResult(value, run.issues); + } + + /** Whether the handle has checks in code, which can make validation wait for an answer. */ + public boolean hasChecks() { + return !checks().isEmpty(); + } + + private Run run(Map given) { + // A view's context, with one given to the call merged over it. + Map merged = given; + if (view != null && view.context != null) { + merged = new LinkedHashMap<>(view.context); + if (given != null) merged.putAll(given); + } + Map finalContext = merged; + MessageInfo info = new MessageInfo(() -> context.store.f.getContext(finalContext)); + return new Run(key, new Messages.Sources(options == null ? null : options.getMessages(), + context.options.getMessages(), info), context.options.getTranslator()); + } + + /** + * Where this handle's field sits in its schema, or null when the datafile lacks + * it. In a view, the fields around it read the view's values, with the value + * being validated in the field's place. + */ + private Located locate(Object value, Run run) { + Store store = context.store; + Resolver.Resolved root = store.resolve(key); + if (root == null) return null; + Store.Walk walk = view == null ? null : new Store.Walk( + Views.place(view.values, steps.subList(view.from, steps.size()), value), view.from, + Views.adjuster(store, run.sources.info.getContext(), key)); + Store.Location field = Store.locate(store, root.node, steps, List.of(), List.of(), walk); + if (field == null) return null; + return new Located(store.compile(field.node), field.node, new Messages.Lookup(field.mpath, field.scopes, null, null)); + } + + private Located applyRules(Object value, Run run) { + Located located = locate(value, run); + if (located == null) { + context.store.reportMissing(key); + Position position = new Position(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null); + Engine.report(run, position, "schemaNotFound", + steps.isEmpty() ? Engine.params("schema", key) : Engine.params("schema", key, "field", path)); + return null; + } + located.validate.validate(value, run, new Position(new ArrayList<>(), located.lookup.mpath, located.lookup.scopes, null)); + return located; + } + + /** Whether a source's step reaches a handle's: {@code []} every index, {@code *} every key. */ + private static boolean reaches(Paths.Step step, Paths.Step own) { + switch (step.kind) { + case ITEMS: return own.kind == Paths.Kind.ITEMS || own.kind == Paths.Kind.INDEX; + case VALUES: return own.kind == Paths.Kind.VALUES || own.kind == Paths.Kind.KEY; + case KEY: return own.kind == Paths.Kind.KEY && own.key.equals(step.key); + default: return own.kind == Paths.Kind.INDEX && own.index == step.index; + } + } + + /** Whether this is a field's handle in a view taken at the schema's root, whose values are the whole input. */ + private boolean inRootView() { + return !steps.isEmpty() && view != null && view.from == 0; + } + + private static List> parseReads(List reads) { + List> parsed = new ArrayList<>(); + for (String read : reads) parsed.add(Paths.parse(read)); + return parsed; + } + + /** The checks in code this handle runs, its sources' lookups first, then its refinements, its own or a field's share. */ + private List checks() { + List checks = new ArrayList<>(); + if (options == null) return checks; + for (OptionSource source : options.getOptionSources()) { + if (source.canLookup()) add(checks, source, CheckKind.LOOKUP, Paths.parse(source.getPath()), parseReads(source.getReads())); + } + for (Refinement refinement : options.getRefinements()) { + add(checks, refinement, CheckKind.REFINE, Paths.parse(refinement.getPath()), parseReads(refinement.getReads())); + } + return checks; + } + + private void add(List checks, Object owner, CheckKind kind, List ownerSteps, List> reads) { + if (steps.isEmpty()) { + checks.add(new Check(owner, kind, ownerSteps, reads)); + return; + } + // A field's handle carries the checks at or inside it. One that reads other + // fields needs the whole input, which only a view from the schema's root holds. + if ((!reads.isEmpty() && !inRootView()) || ownerSteps.size() < steps.size()) return; + for (int index = 0; index < steps.size(); index++) { + if (!reaches(ownerSteps.get(index), steps.get(index))) return; + } + checks.add(new Check(owner, kind, ownerSteps.subList(steps.size(), ownerSteps.size()), reads)); + } + + private static final class Target { + final List path; + final Object value; + + Target(List path, Object value) { + this.path = path; + this.value = value; + } + } + + /** The concrete paths a check's steps reach in a value, with the value at each. */ + private static void expand(Object value, List steps, int index, List path, List found) { + if (index == steps.size()) { + found.add(new Target(path, value)); + return; + } + Paths.Step step = steps.get(index); + if (step.kind == Paths.Kind.ITEMS) { + List list = Json.list(value); + if (list != null) for (int at = 0; at < list.size(); at++) expand(list.get(at), steps, index + 1, Engine.append(path, at), found); + return; + } + if (step.kind == Paths.Kind.VALUES) { + Map map = Json.map(value); + if (map != null) for (Map.Entry entry : map.entrySet()) { + expand(entry.getValue(), steps, index + 1, Engine.append(path, entry.getKey()), found); + } + return; + } + if (step.kind == Paths.Kind.INDEX) { + List list = Json.list(value); + if (list != null && step.index < list.size()) expand(list.get(step.index), steps, index + 1, Engine.append(path, step.index), found); + return; + } + Map map = Json.map(value); + if (map != null && map.containsKey(step.key)) expand(map.get(step.key), steps, index + 1, Engine.append(path, step.key), found); + } + + /** Whether a lookup found a choice: anything but null, false and an empty Optional. */ + private static boolean found(Object answer) { + if (answer instanceof Optional) return ((Optional) answer).isPresent(); + return answer != null && !Boolean.FALSE.equals(answer); + } + + private static Object unwrap(Object answer) { + return answer instanceof Optional ? ((Optional) answer).orElse(null) : answer; + } + + private CompletableFuture runChecks(Object original, Object value, Map given, + Run run, Located located, List checks) { + Map contextValue = run.sources.info.getContext(); + List ruleIssues = new ArrayList<>(run.issues); + // In a view from the root, a field's checks see the whole input with the value in its place, + // as they would validating the schema, and the issues of the fields they read hold them back. + boolean whole = inRootView(); + Object input = whole ? Views.place(view.values, steps, value) : value; + List readIssues = whole ? rootRuleIssues(input, given) : ruleIssues; + CheckInfo info = new CheckInfo(input, contextValue); + // Each check's issues keep their place, whatever order answers arrive in. + List> slots = new ArrayList<>(); + List> pending = new ArrayList<>(); + + for (Check check : checks) { + List targets = new ArrayList<>(); + expand(value, check.steps, 0, new ArrayList<>(), targets); + for (Target target : targets) { + if (blocked(target, check, ruleIssues, readIssues)) continue; + List slot = new ArrayList<>(); + slots.add(slot); + Object outcome; + try { + outcome = check.kind == CheckKind.REFINE + ? ((Refinement) check.owner).run(target.value, info) + : ((OptionSource) check.owner).runLookup(target.value, info); + } catch (RuntimeException failed) { + reportCheck(run, located, slot, "refineError", check, target.path); + continue; + } + if (outcome instanceof CompletionStage) { + pending.add(((CompletionStage) outcome).toCompletableFuture().handle((answer, error) -> { + if (error != null) reportCheck(run, located, slot, "refineError", check, target.path); + else if (!passes(check.kind, answer)) reportCheck(run, located, slot, failure(check.kind), check, target.path); + return null; + })); + } else if (!passes(check.kind, outcome)) { + reportCheck(run, located, slot, failure(check.kind), check, target.path); + } + } + } + + Supplier finish = () -> { + List issues = new ArrayList<>(ruleIssues); + for (List slot : slots) issues.addAll(slot); + return new ValidationResult(original, issues); + }; + // Checks that answered at once have nothing left to wait for. + if (pending.isEmpty()) return CompletableFuture.completedFuture(finish.get()); + CompletableFuture result = CompletableFuture.allOf(pending.toArray(new CompletableFuture[0])) + .thenApply(done -> finish.get()); + // Cancelling the validation cancels what it waits for. + result.whenComplete((done, error) -> { + if (result.isCancelled()) for (CompletableFuture future : pending) future.cancel(true); + }); + return result; + } + + private static boolean blocked(Target target, Check check, List ruleIssues, List readIssues) { + for (SchemaIssue issue : ruleIssues) if (Paths.isAtOrInside(issue.getPath(), target.path)) return true; + for (List read : check.reads) { + for (SchemaIssue issue : readIssues) if (Paths.matchesSteps(issue.getPath(), read)) return true; + } + return false; + } + + /** A refinement passes with {@code true}, and a lookup when it finds a choice, which {@code enum} reports otherwise. */ + private static boolean passes(CheckKind kind, Object answer) { + return kind == CheckKind.REFINE ? Boolean.TRUE.equals(answer) : found(answer); + } + + private static String failure(CheckKind kind) { + return kind == CheckKind.REFINE ? "refine" : "enum"; + } + + /** The schema's own rules on a whole input, untranslated, for knowing which fields have issues. */ + private List rootRuleIssues(Object input, Map given) { + Resolver.Resolved root = context.store.resolve(key); + if (root == null) return List.of(); + Run run = run(given).untranslated(); + root.validate.validate(input, run, new Position(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null)); + return run.issues; + } + + private void reportCheck(Run run, Located located, List slot, String code, Check check, List at) { + Resolver resolve = context.store; + Store.Location field = Store.locate(resolve, located.node, Paths.stepsOf(at), located.lookup.mpath, located.lookup.scopes, null); + Messages.Lookup lookup; + if (field != null) { + lookup = new Messages.Lookup(field.mpath, field.scopes, Engine.titleOf(field.node, resolve), null); + } else { + List mpath = new ArrayList<>(located.lookup.mpath); + for (Object part : at) mpath.add(String.valueOf(part)); + lookup = new Messages.Lookup(mpath, located.lookup.scopes, null, null); + } + String ownerKey = check.owner instanceof Refinement ? ((Refinement) check.owner).getKey() : ((OptionSource) check.owner).getKey(); + String ownerMessage = check.owner instanceof Refinement ? ((Refinement) check.owner).getMessage() : ((OptionSource) check.owner).getMessage(); + String own = code.equals("refineError") ? null : ownerMessage; + Map params = check.kind == CheckKind.REFINE ? Engine.params("refine", ownerKey) : Engine.params("optionSource", ownerKey); + // Answers can arrive on other threads, and the run's list is not theirs to share. + synchronized (run) { + int before = run.issues.size(); + Engine.report(run, new Position(at, lookup), code, params, at, lookup, own); + List added = run.issues.subList(before, run.issues.size()); + slot.addAll(added); + added.clear(); + } + } + + // Fields + + /** The handle for a field at a path, such as {@code address.city}, {@code items[].name} or {@code labels.*}. */ + public SchemaHandle at(String path) { + return handle(path, () -> Paths.parse(path)); + } + + /** + * The handle for one of an object's fields by its key, the same handle + * {@code at} gives when the key reads as itself, and its own for a key such as + * {@code a.b}, {@code *} or {@code 2024}, which a path would read otherwise. + */ + public SchemaHandle child(String key) { + if (key.matches("[^.\\[\\]*\\d][^.\\[\\]]*")) return at(key); + return handle("\u0000" + key, () -> List.of(Paths.Step.key(key))); + } + + private SchemaHandle handle(String id, Supplier> more) { + SchemaHandle field = handles.get(id); + if (field == null) { + List next = new ArrayList<>(steps); + next.addAll(more.get()); + field = new SchemaHandle(context, key, options, next, view); + SchemaHandle existing = handles.putIfAbsent(id, field); + if (existing != null) field = existing; + } + return field; + } + + /** + * The same handle with an input, such as the values a form has so far: its + * members describe the rules with every mutation whose conditions match that + * input, and the context, applied at every depth. + */ + public SchemaHandle withInput(Object input) { + return withInput(input, null); + } + + public SchemaHandle withInput(Object input, Map context) { + return new SchemaHandle(this.context, key, options, steps, new View(Json.plain(input), context, steps.size())); + } + + // What the rules describe + + /** The node this handle describes, in a view with the matching mutations applied at every depth. */ + private Described describe(View view) { + Store store = context.store; + Resolver.Resolved root = store.resolve(key); + if (root == null) return null; + BiFunction adjust = view == null ? null + : Views.adjuster(store, store.f.getContext(view.context), key); + Store.Location field = Store.locate(store, root.node, steps, List.of(), List.of(), + adjust == null ? null : new Store.Walk(view.values, view.from, adjust)); + if (field == null) return null; + if (adjust == null) return new Described(field.node, field.required); + return new Described(Views.resolveTree(field.node, field.value, adjust, store, List.of()), field.required); + } + + /** What a member derives from the node, kept until the datafile changes, since a field's can come from a referenced schema. */ + @SuppressWarnings("unchecked") + private T derive(String kind, BiFunction make, T otherwise) { + Store store = context.store; + Object entry = store.entry(key); + if (entry == null) return otherwise; + String revision = store.api.getRevision(); + Memo current = memo; + if (current == null || current.entry != entry || !java.util.Objects.equals(current.revision, revision)) { + current = new Memo(entry, revision, describe(view)); + memo = current; + } + Described described = current.described; + Object made = current.made.get(kind); + if (made == null) { + made = make.apply(described == null ? null : described.node, described != null && described.required); + if (made == null) made = NULL; + current.made.putIfAbsent(kind, made); + } + return made == NULL ? null : (T) made; + } + + private static final Object NULL = new Object(); + + /** The fields, relative to this handle, that its mutations' and issues' conditions read. */ + public List getReads() { + return derive("reads", (node, required) -> { + Described base = describe(null); + return Collections.unmodifiableList(Views.readsOf(base == null ? null : base.node, context.store)); + }, List.of()); + } + + /** Its annotations, over those of a schema its field references. */ + public Map getAnnotations() { + return derive("annotations", (node, required) -> Derived.annotations(node, context.store), Map.of()); + } + + /** The keys of an object's fields, in its {@code order}. */ + public List getFieldKeys() { + return derive("fieldKeys", (node, required) -> Derived.fieldKeys(node, context.store), List.of()); + } + + /** An object's fields' handles, in its {@code order}, or none for any other value. */ + public List getFields() { + List fields = new ArrayList<>(); + for (String field : getFieldKeys()) fields.add(child(field)); + return Collections.unmodifiableList(fields); + } + + /** The HTML validation attributes its rules imply, with {@code required} from the object it sits in. */ + public FieldConstraints getConstraints() { + return derive("constraints", (node, required) -> Derived.constraints(node, required, context.store), FieldConstraints.NONE); + } + + /** An object's fields' constraints by dot path, such as {@code address.city}, or none for any other value. */ + public Map getFieldConstraints() { + return derive("fieldConstraints", (node, required) -> Derived.fieldConstraints(node, context.store), Map.of()); + } + + /** The choices the field allows, in the order its rules list them, empty when it lists none. */ + public List getOptions() { + return derive("options", (node, required) -> Derived.options(node, context.store), List.of()); + } + + /** An object's fields' choices by dot path, for the fields that list some. */ + public Map> getFieldOptions() { + return derive("fieldOptions", (node, required) -> Derived.fieldOptions(node, context.store), Map.of()); + } + + /** The schema's own choice for a value, or null. */ + public SchemaOption option(Object value) { + Object plain = Json.plain(value); + for (SchemaOption option : getOptions()) if (Json.same(option.getValue(), plain)) return option; + return null; + } + + /** What the rules make the field, for choosing an input, or null for a {@code oneOf} of shapes. */ + public FieldKind getKind() { + return derive("kind", (node, required) -> Derived.kind(node, context.store), null); + } + + // Option sources + + /** + * The option source for this handle's field, the first whose path names it, + * or names the items of the list it is, that can do what is asked. + */ + private OptionSource source(boolean search) { + if (options == null) return null; + for (OptionSource source : options.getOptionSources()) { + if (search ? !source.canSearch() : !source.canLookup()) continue; + List sourceSteps = Paths.parse(source.getPath()); + boolean exact = sourceSteps.size() == steps.size(); + boolean holder = sourceSteps.size() == steps.size() + 1 && sourceSteps.get(steps.size()).kind == Paths.Kind.ITEMS; + if (!exact && !holder) continue; + boolean reached = true; + for (int index = 0; index < steps.size(); index++) { + if (!reaches(sourceSteps.get(index), steps.get(index))) { reached = false; break; } + } + if (reached) return source; + } + return null; + } + + /** Whether an option source suggests choices for this field. */ + public boolean canSearch() { + return source(true) != null; + } + + public CompletableFuture> search(String query) { + return search(query, null); + } + + /** Suggestions from the field's option source for a query, empty without a source that searches. */ + public CompletableFuture> search(String query, Map context) { + OptionSource source = source(true); + if (source == null) return CompletableFuture.completedFuture(List.of()); + CheckInfo info = sourceInfo(context); + Object outcome; + try { + outcome = source.runSearch(query, info); + } catch (RuntimeException failed) { + return CompletableFuture.failedFuture(failed); + } + CompletableFuture answer = outcome instanceof CompletionStage + ? ((CompletionStage) outcome).toCompletableFuture() : CompletableFuture.completedFuture(outcome); + return answer.thenApply(list -> { + if (!(list instanceof List)) { + throw new IllegalArgumentException("The search of option source `" + source.getKey() + "` must return a list."); + } + List suggestions = new ArrayList<>(); + for (Object item : (List) list) { + SchemaOption suggestion = toSuggestion(item); + // An object without a `value`, such as `{ id, name }`, would vanish from the list unseen. + if (suggestion == null) { + throw new IllegalArgumentException("The search of option source `" + source.getKey() + + "` must return values, or maps with a `value`."); + } + suggestions.add(suggestion); + } + return Collections.unmodifiableList(suggestions); + }); + } + + private static SchemaOption toSuggestion(Object item) { + if (item instanceof SchemaOption) return (SchemaOption) item; + Object plain = Json.plain(item); + if (!(plain instanceof Map)) return new SchemaOption(plain, null); + Map map = Json.map(plain); + return map.containsKey("value") ? new SchemaOption(map.get("value"), map) : null; + } + + public CompletableFuture lookup(Object value) { + return lookup(value, null); + } + + /** The choice for a value: the schema's own, or else the one the field's option source finds, or null. */ + public CompletableFuture lookup(Object value, Map context) { + SchemaOption own = option(value); + if (own != null) return CompletableFuture.completedFuture(own); + OptionSource source = source(false); + if (source == null) return CompletableFuture.completedFuture(null); + Object plain = Json.plain(value); + Object outcome; + try { + outcome = source.runLookup(plain, sourceInfo(context)); + } catch (RuntimeException failed) { + return CompletableFuture.failedFuture(failed); + } + CompletableFuture answer = outcome instanceof CompletionStage + ? ((CompletionStage) outcome).toCompletableFuture() : CompletableFuture.completedFuture(outcome); + return answer.thenApply(found -> { + if (!found(found)) return null; + Object unwrapped = Json.plain(unwrap(found)); + return new SchemaOption(plain, unwrapped instanceof Map ? Json.map(unwrapped) : null); + }); + } + + private CheckInfo sourceInfo(Map given) { + return new CheckInfo(view == null ? null : view.values, run(given).sources.info.getContext()); + } + + // Changes + + /** Calls back when the datafile changes this handle's schema, until unsubscribed. */ + public FeaturevisorUnsubscribe subscribe(Runnable listener) { + Store store = context.store; + Object[] version = { store.version(key) }; + return context.schemas.listen(() -> { + Object next = store.version(key); + if (java.util.Objects.equals(next, version[0])) return; + version[0] = next; + listener.run(); + }); + } + + @Override + public String toString() { + return "SchemaHandle{" + key + (path.isEmpty() ? "" : " at " + path) + "}"; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaIssue.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaIssue.java new file mode 100644 index 0000000..d39f225 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaIssue.java @@ -0,0 +1,70 @@ +package com.featurevisor.schemas; + +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** One problem with a value, with what an application needs to word it. */ +public final class SchemaIssue { + private final String message; + private final List path; + private final String code; + private final Map params; + private final String schema; + private final String mutation; + + SchemaIssue(String message, List path, String code, Map params, String schema, String mutation) { + this.message = message; + this.path = Collections.unmodifiableList(path); + this.code = code; + this.params = Collections.unmodifiableMap(params); + this.schema = schema; + this.mutation = mutation; + } + + /** The message, from the form's, the schema's or the application's messages, or the default. */ + public String getMessage() { return message; } + + /** Where the issue is in the value: keys as strings and list indexes as integers. Empty for the value itself. */ + public List getPath() { return path; } + + /** What went wrong, such as {@code required}, {@code minLength} or {@code refine}. */ + public String getCode() { return code; } + + /** What a message can name, such as {@code minLength} and {@code length}, and the field's {@code title}. */ + public Map getParams() { return params; } + + /** The key of the schema validated, such as {@code signUp}. */ + public String getSchema() { return schema; } + + /** The key of the mutation that set or changed the rule, or null when none did. */ + public String getMutation() { return mutation; } + + /** The path as a field name with dots, such as {@code items.0.name}. */ + public String getField() { return Paths.format(path); } + + SchemaIssue withMessage(String text) { + return new SchemaIssue(text, path, code, params, schema, mutation); + } + + SchemaIssue withMutation(String key) { + return new SchemaIssue(message, path, code, params, schema, key); + } + + @Override + public boolean equals(Object other) { + if (!(other instanceof SchemaIssue)) return false; + SchemaIssue issue = (SchemaIssue) other; + return message.equals(issue.message) && path.equals(issue.path) && code.equals(issue.code) + && params.equals(issue.params) && schema.equals(issue.schema) && Objects.equals(mutation, issue.mutation); + } + + @Override + public int hashCode() { return Objects.hash(message, path, code, params, schema, mutation); } + + @Override + public String toString() { + return (path.isEmpty() ? "" : getField() + ": ") + message + " (" + code + ")"; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaMessage.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaMessage.java new file mode 100644 index 0000000..5e4bf01 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaMessage.java @@ -0,0 +1,9 @@ +package com.featurevisor.schemas; + +import java.util.Map; + +/** A message worded in code from an issue's params, such as one that reads the context's locale. */ +@FunctionalInterface +public interface SchemaMessage { + String format(Map params, MessageInfo info); +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaOption.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaOption.java new file mode 100644 index 0000000..c0718d7 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaOption.java @@ -0,0 +1,48 @@ +package com.featurevisor.schemas; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * A choice a field allows, as its value with what the schema says about it, + * such as its {@code title}, or one an option source found. + */ +public final class SchemaOption { + private final Object value; + private final Map fields; + + SchemaOption(Object value, Map entry) { + Map fields = new LinkedHashMap<>(); + // The value first, as a console shows it, and never one an entry gives. + fields.put("value", value); + if (entry != null) entry.forEach((key, item) -> { if (!"value".equals(key)) fields.put(key, item); }); + this.value = value; + this.fields = Collections.unmodifiableMap(fields); + } + + public Object getValue() { return value; } + + /** Its {@code title}, or null without one. */ + public String getTitle() { + Object title = fields.get("title"); + return title instanceof String ? (String) title : null; + } + + /** One of what the schema or the source says about the choice, such as {@code description}. */ + public Object get(String field) { return fields.get(field); } + + /** The value and everything said about it, {@code value} first. */ + public Map asMap() { return fields; } + + @Override + public boolean equals(Object other) { + return other instanceof SchemaOption && Json.same(fields, ((SchemaOption) other).fields); + } + + @Override + public int hashCode() { return String.valueOf(value).hashCode(); } + + @Override + public String toString() { return "SchemaOption" + fields; } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaValidationException.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaValidationException.java new file mode 100644 index 0000000..69d0dc9 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaValidationException.java @@ -0,0 +1,24 @@ +package com.featurevisor.schemas; + +import java.util.List; + +/** Thrown by {@code parse} when a value fails, with the issues found. */ +public class SchemaValidationException extends RuntimeException { + private final String schema; + private final List issues; + + SchemaValidationException(String schema, List issues) { + super((schema + ": " + (issues.size() == 1 ? "1 issue" : issues.size() + " issues") + ". " + + (issues.isEmpty() ? "" : issues.get(0).getMessage())).trim()); + this.schema = schema; + this.issues = issues; + } + + /** The key of the schema validated, such as {@code signUp}. */ + public String getSchema() { return schema; } + + public List getIssues() { return issues; } + + /** The issues by field, for an error response. */ + public FlattenedIssues flatten() { return FlattenedIssues.of(issues); } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java new file mode 100644 index 0000000..29bcd30 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java @@ -0,0 +1,115 @@ +package com.featurevisor.schemas; + +import com.featurevisor.sdk.Featurevisor; +import com.featurevisor.sdk.FeaturevisorEventName; +import com.featurevisor.sdk.FeaturevisorUnsubscribe; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentHashMap; + +/** + * Validates data against the schemas a Featurevisor instance's datafile + * carries. It holds no copy of them: every handle reads the current datafile + * when it is used, so a new datafile takes effect at the next validation. + * + *
{@code
+ * Schemas schemas = Schemas.create(f);
+ * ValidationResult result = schemas.validate("signUp", request);
+ * if (!result.isValid()) return badRequest(result.flatten());
+ * }
+ */ +public final class Schemas implements AutoCloseable { + /** The first featurevisor-java release whose modules can read datafile sections, which this package needs. */ + static final String FIRST_RELEASE = "5.1.0"; + + private final Store store; + private final SchemaHandle.Context context; + private final Map handles = new ConcurrentHashMap<>(); + private final Set listeners = ConcurrentHashMap.newKeySet(); + + private Schemas(Featurevisor f, SchemasOptions options) { + this.store = new Store(f); + this.context = new SchemaHandle.Context(store, options == null ? new SchemasOptions() : options, this); + } + + /** Schemas for the instance {@code Featurevisor.createFeaturevisor} returns. Pass a child's context to validate instead of a child. */ + public static Schemas create(Featurevisor f) { + return new Schemas(f, null); + } + + public static Schemas create(Featurevisor f, SchemasOptions options) { + return new Schemas(f, options); + } + + /** A schema's handle, the same one for the same key. */ + public SchemaHandle get(String key) { + SchemaHandle handle = handles.get(key); + if (handle == null) { + handle = new SchemaHandle(context, key, null); + SchemaHandle existing = handles.putIfAbsent(key, handle); + if (existing != null) handle = existing; + } + return handle; + } + + /** A schema's handle with a form's messages, refinements and option sources. */ + public SchemaHandle get(String key, HandleOptions options) { + return options == null ? get(key) : new SchemaHandle(context, key, options); + } + + public ValidationResult validate(String key, Object value) { + return get(key).validate(value); + } + + public ValidationResult validate(String key, Object value, Map context) { + return get(key).validate(value, context); + } + + public boolean isValid(String key, Object value) { + return get(key).isValid(value); + } + + public boolean isValid(String key, Object value, Map context) { + return get(key).isValid(value, context); + } + + /** The value, or a {@link SchemaValidationException} with the issues found. */ + public Object parse(String key, Object value) { + return get(key).parse(value); + } + + public Object parse(String key, Object value, Map context) { + return get(key).parse(value, context); + } + + /** The keys of the schemas the datafile carries. */ + public List getKeys() { + return store.keys(); + } + + /** Whether the datafile carries a schema. */ + public boolean has(String key) { + return store.entry(key) != null; + } + + /** Calls back on every datafile the SDK instance accepts, until closed. */ + FeaturevisorUnsubscribe listen(Runnable callback) { + FeaturevisorUnsubscribe[] stop = new FeaturevisorUnsubscribe[1]; + FeaturevisorUnsubscribe subscription = store.f.on(FeaturevisorEventName.DATAFILE_SET, details -> callback.run()); + stop[0] = () -> { + listeners.remove(stop[0]); + subscription.unsubscribe(); + }; + listeners.add(stop[0]); + return stop[0]; + } + + /** Stops every subscription and removes the module from the SDK instance. */ + @Override + public void close() { + for (FeaturevisorUnsubscribe stop : listeners.toArray(new FeaturevisorUnsubscribe[0])) stop.unsubscribe(); + listeners.clear(); + store.close(); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemasOptions.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemasOptions.java new file mode 100644 index 0000000..64764c1 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemasOptions.java @@ -0,0 +1,36 @@ +package com.featurevisor.schemas; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Options for every schema of a {@link Schemas} instance: a message per issue + * code, used where neither a form nor a schema words the issue, and a + * translator that every issue's message passes through last. + */ +public final class SchemasOptions { + private final Map messages = new LinkedHashMap<>(); + private IssueTranslator translator; + + /** A template such as {@code "Use at least {minLength} characters"} for an issue code. */ + public SchemasOptions message(String code, String template) { + messages.put(code, template); + return this; + } + + /** A message in code for an issue code. */ + public SchemasOptions message(String code, SchemaMessage message) { + messages.put(code, message); + return this; + } + + public SchemasOptions translator(IssueTranslator translator) { + this.translator = translator; + return this; + } + + Map getMessages() { return Collections.unmodifiableMap(messages); } + + IssueTranslator getTranslator() { return translator; } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java new file mode 100644 index 0000000..bad6db8 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java @@ -0,0 +1,335 @@ +package com.featurevisor.schemas; + +import com.featurevisor.sdk.ConditionReader; +import com.featurevisor.sdk.Featurevisor; +import com.featurevisor.sdk.FeaturevisorDiagnostic; +import com.featurevisor.sdk.FeaturevisorEventName; +import com.featurevisor.sdk.FeaturevisorLogLevel; +import com.featurevisor.sdk.FeaturevisorModule; +import com.featurevisor.sdk.FeaturevisorModuleApi; +import com.featurevisor.sdk.FeaturevisorUnsubscribe; +import com.featurevisor.sdk.MatchConditionsOptions; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.BiFunction; +import java.util.function.Supplier; + +/** + * What a {@link Schemas} instance reads through its SDK instance: the module + * API, and schemas compiled by the entry the datafile holds, so a datafile that + * changes one compiles it again and references resolve at call time. + */ +final class Store implements Resolver { + static final String SECTION = "schemas"; + + final Featurevisor f; + final FeaturevisorModuleApi api; + private final Runnable removeModule; + private FeaturevisorUnsubscribe stopListening; + + private static final class Compiled { + final Object entry; + final Validator validate; + + Compiled(Object entry, Validator validate) { + this.entry = entry; + this.validate = validate; + } + } + + /** A key that compares by identity, for caches of the datafile's own nodes. */ + private static final class Identity { + final Object value; + + Identity(Object value) { this.value = value; } + + @Override public boolean equals(Object other) { return other instanceof Identity && ((Identity) other).value == value; } + @Override public int hashCode() { return System.identityHashCode(value); } + } + + private final Map compiled = new ConcurrentHashMap<>(); + private volatile Map>> mutated = new ConcurrentHashMap<>(); + private volatile Map nodes = new ConcurrentHashMap<>(); + private final Set reported = ConcurrentHashMap.newKeySet(); + private final Set reportedPatterns = ConcurrentHashMap.newKeySet(); + private final Set reportedDepths = ConcurrentHashMap.newKeySet(); + + /** SDK instances whose schemas module holds the package's name, which only one module on an instance can. */ + private static final Map NAMED = Collections.synchronizedMap(new WeakHashMap<>()); + private static final String NAME = "@featurevisor/schemas"; + + private final boolean named; + + Store(Featurevisor f) { + if (f == null) throw new IllegalArgumentException("Schemas need a Featurevisor instance"); + this.f = f; + AtomicReference captured = new AtomicReference<>(); + boolean takesName = NAMED.putIfAbsent(f, Boolean.TRUE) == null; + // A module without evaluation hooks costs evaluations nothing. + Runnable remove = f.addModule(new FeaturevisorModule(takesName ? NAME : null).setup(captured::set)); + if (remove == null && takesName) { + // A module of the same name was added by hand. + NAMED.remove(f); + takesName = false; + remove = f.addModule(new FeaturevisorModule(null).setup(captured::set)); + } + this.named = takesName; + this.removeModule = remove != null ? remove : () -> {}; + FeaturevisorModuleApi moduleApi = captured.get(); + if (moduleApi == null || !readsSections(moduleApi)) { + close(false); + throw new IllegalStateException( + "featurevisor-schemas needs a featurevisor-java whose modules can read datafile sections, " + + Schemas.FIRST_RELEASE + " or later."); + } + this.api = moduleApi; + // Caches keyed by the datafile's nodes start afresh with every datafile, whose + // entries are new objects even when their hashes stay, so they never outgrow one. + this.stopListening = f.on(FeaturevisorEventName.DATAFILE_SET, details -> { + mutated = new ConcurrentHashMap<>(); + nodes = new ConcurrentHashMap<>(); + }); + } + + private static boolean readsSections(FeaturevisorModuleApi api) { + try { + api.getEntryKeys(SECTION); + return true; + } catch (UnsupportedOperationException old) { + return false; + } + } + + void close() { + close(true); + } + + private void close(boolean listening) { + if (listening) stopListening.unsubscribe(); + removeModule.run(); + if (named) NAMED.remove(f); + } + + /** The entry as the datafile holds it, or null. */ + Map entry(String key) { + return Json.map(api.getEntry(SECTION, key)); + } + + List keys() { + return Collections.unmodifiableList(new ArrayList<>(api.getEntryKeys(SECTION))); + } + + /** What changes when the schema does, through the schemas it references too, since its hash covers them. */ + Object version(String key) { + Map node = entry(key); + if (node == null) return null; + Object hash = node.get("hash"); + return hash != null ? hash : node; + } + + @Override + public Map node(String key) { + return entry(key); + } + + /** + * The schema's node and validator, compiled once per entry. Compiling reads only the nodes + * of the schemas it references, so a schema that references itself compiles. + */ + @Override + public Resolved resolve(String key) { + Map node = entry(key); + if (node == null) return null; + Compiled cached = compiled.get(key); + if (cached != null && cached.entry == node) return new Resolved(node, cached.validate); + Validator validate = Engine.compileNode(node, this); + compiled.put(key, new Compiled(node, validate)); + return new Resolved(node, validate); + } + + /** A node's validator, kept per node, since a view's nodes are the same object for the same mutations. */ + Validator compile(Object node) { + if (!(node instanceof Map)) return Engine.compileNode(node, this); + Identity key = new Identity(node); + Map current = nodes; + Validator validate = current.get(key); + if (validate == null) { + validate = Engine.compileNode(node, this); + current.putIfAbsent(key, validate); + } + return validate; + } + + @Override + public boolean match(Object conditions, Map context, ConditionReader input, String schema) { + // Conditions read through the SDK, so a segment means in a schema what it means in a flag. + return api.matchConditions(conditions, context, + new MatchConditionsOptions().type("schema").key(schema).reader("input", input)); + } + + @Override + public Map mutated(Map node, String id, Supplier> make) { + Map>> current = mutated; + Identity key = new Identity(node); + Map> byId = current.get(key); + if (byId == null) { + current.putIfAbsent(key, new ConcurrentHashMap<>()); + byId = current.get(key); + } + Map rules = byId.get(id); + if (rules == null) { + rules = make.get(); + Map existing = byId.putIfAbsent(id, rules); + if (existing != null) rules = existing; + } + return rules; + } + + @Override + public void unsupportedPattern(String pattern) { + if (!reportedPatterns.add(pattern)) return; + api.reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.ERROR) + .code("schema_pattern_unsupported") + .message("Pattern " + Json.stringify(pattern) + " does not compile in Java, so it fails every value.") + .details(Map.of("pattern", pattern))); + } + + @Override + public void referenceTooDeep(String schema) { + if (!reportedDepths.add(schema)) return; + api.reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.ERROR) + .code("schema_reference_depth") + .message("Schema " + Json.stringify(schema) + " follows references more than " + + Engine.MAX_REFERENCE_DEPTH + " deep, so it fails the value. A schema that references itself" + + " must read deeper into the value each time.") + .details(Map.of("schemaKey", schema))); + } + + /** Reports {@code schema_not_found} once per key. */ + void reportMissing(String key) { + if (!reported.add(key)) return; + api.reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.WARN) + .code("schema_not_found") + .message("Schema \"" + key + "\" is not in the datafile. Check that a target delivers it.") + .details(Map.of("schemaKey", key))); + } + + /** A field inside a schema: its node, and the message path and messages around it. */ + static final class Location { + final Object node; + final List mpath; + /** Schema messages of the nodes on the way, not the field's own, which validating it adds. */ + final List scopes; + /** The field's value in a view's values. */ + final Object value; + /** Whether the object the field sits in requires it, after that object's mutations in a view. */ + final boolean required; + + Location(Object node, List mpath, List scopes, Object value, boolean required) { + this.node = node; + this.mpath = mpath; + this.scopes = scopes; + this.value = value; + this.required = required; + } + } + + /** How a view walks: its values, from which step they apply, and what applies a node's matching mutations. */ + static final class Walk { + final Object value; + final int from; + final BiFunction adjust; + + Walk(Object value, int from, BiFunction adjust) { + this.value = value; + this.from = from; + this.adjust = adjust; + } + } + + /** + * Follows a path from a node, through references, {@code properties}, array + * items and the values an open object allows. It stops at {@code oneOf}, and + * gives null for a path the schema does not describe. In a view, each node on + * the way, and each schema it references, has its matching mutations applied + * for the value there. + */ + static Location locate(Resolver resolve, Object root, List steps, List startMpath, + List startScopes, Walk walk) { + Object node = root; + Object value = walk != null ? walk.value : null; + boolean required = false; + List mpath = new ArrayList<>(startMpath); + List scopes = new ArrayList<>(startScopes); + + for (int index = 0; index < steps.size(); index++) { + Paths.Step step = steps.get(index); + BiFunction adjust = walk != null && index >= walk.from ? walk.adjust : null; + // The node's messages, then those of each schema it references, at the same depth. + List seen = new ArrayList<>(); + Object resolved = adjust != null ? adjust.apply(node, value) : node; + Map current; + while (true) { + current = Json.map(resolved); + if (current == null) return null; + Map messages = Json.map(current.get("messages")); + if (messages != null) scopes.add(new Messages.Scope(messages, mpath.size())); + String key = Json.string(current.get("schema")); + if (key == null) break; + if (seen.contains(key)) return null; + seen.add(key); + Object targetNode = resolve.node(key); + resolved = adjust != null ? adjust.apply(targetNode, value) : targetNode; + } + if (current.get("oneOf") instanceof List) return null; + boolean inView = walk != null && index >= walk.from; + + if (step.kind == Paths.Kind.KEY) { + Map properties = Json.map(current.get("properties")); + required = false; + if (properties != null && properties.containsKey(step.key)) { + node = properties.get(step.key); + mpath.add(step.key); + required = current.get("required") instanceof List && ((List) current.get("required")).contains(step.key); + } else if (current.get("additionalProperties") instanceof Map) { + node = current.get("additionalProperties"); + mpath.add("*"); + } else { + return null; + } + if (inView) value = Json.get(value, step.key); + continue; + } + + required = false; + if (step.kind == Paths.Kind.VALUES) { + if (!(current.get("additionalProperties") instanceof Map)) return null; + node = current.get("additionalProperties"); + mpath.add("*"); + // `*` names no one value. + if (inView) value = null; + continue; + } + + // An index or `[]`: every item of an array is described alike. + if (!"array".equals(current.get("type"))) return null; + node = current.containsKey("items") ? current.get("items") : Map.of("type", "string"); + mpath.add("[]"); + if (inView) { + List list = Json.list(value); + value = step.kind == Paths.Kind.INDEX && list != null && step.index < list.size() ? list.get(step.index) : null; + } + } + + return new Location(node, mpath, scopes, value, required); + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/ValidationResult.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/ValidationResult.java new file mode 100644 index 0000000..a194cce --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/ValidationResult.java @@ -0,0 +1,31 @@ +package com.featurevisor.schemas; + +import java.util.Collections; +import java.util.List; + +/** What validating a value found: the value when it passes, or its issues. */ +public final class ValidationResult { + private final Object value; + private final List issues; + + ValidationResult(Object value, List issues) { + this.value = value; + this.issues = Collections.unmodifiableList(issues); + } + + public boolean isValid() { return issues.isEmpty(); } + + /** The issues found, empty when the value passes. */ + public List getIssues() { return issues; } + + /** The value as it was given, whether or not it passed. */ + public Object getValue() { return value; } + + /** The issues by field, for showing them next to inputs or in an error response. */ + public FlattenedIssues flatten() { return FlattenedIssues.of(issues); } + + @Override + public String toString() { + return isValid() ? "ValidationResult{valid}" : "ValidationResult" + issues; + } +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Validator.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Validator.java new file mode 100644 index 0000000..744b383 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Validator.java @@ -0,0 +1,9 @@ +package com.featurevisor.schemas; + +/** A compiled schema node: validates a value at a position, reporting into the run. */ +@FunctionalInterface +interface Validator { + Validator NONE = (value, run, at) -> {}; + + void validate(Object value, Run run, Position at); +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java new file mode 100644 index 0000000..dbf4f02 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java @@ -0,0 +1,163 @@ +package com.featurevisor.schemas; + +import com.fasterxml.jackson.databind.ObjectMapper; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; +import java.util.function.Consumer; + +/** What a handle's members describe with an input: rules with every matching mutation applied, at every depth. */ +final class Views { + private static final ObjectMapper JSON = new ObjectMapper(); + + private Views() {} + + /** Applies a node's mutations whose conditions match the value at it and the context. */ + static BiFunction adjuster(Resolver resolve, Map context, String schema) { + return (node, value) -> { + Map map = Json.map(node); + if (map == null || !Engine.hasMutations(map)) return node; + return Engine.mutatedRules(map, Engine.matchingMutations(map, value, context, resolve, schema), resolve); + }; + } + + private interface ChildMap { + /** A child mapped: a property with its key, items and an open object's values with {@code []} or {@code *}, a branch with neither. */ + Object map(Object child, String key, String many); + } + + /** A copy of a node with each child mapped. */ + private static Map mapChildren(Map node, ChildMap map) { + Map copy = new LinkedHashMap<>(node); + Map properties = Json.map(node.get("properties")); + if (properties != null) { + Map mapped = new LinkedHashMap<>(); + for (Map.Entry entry : properties.entrySet()) { + mapped.put(entry.getKey(), map.map(entry.getValue(), entry.getKey(), null)); + } + copy.put("properties", mapped); + } + if (node.get("items") instanceof Map) copy.put("items", map.map(node.get("items"), null, "[]")); + if (node.get("additionalProperties") instanceof Map) { + copy.put("additionalProperties", map.map(node.get("additionalProperties"), null, "*")); + } + if (node.get("oneOf") instanceof List) { + List branches = new ArrayList<>(); + for (Object branch : (List) node.get("oneOf")) branches.add(map.map(branch, null, null)); + copy.put("oneOf", branches); + } + return copy; + } + + /** + * A node's subtree for a value, with the matching mutations applied at every + * node for the value there. References are inlined, so each use of a schema, + * such as a billing and a shipping address, resolves for its own value. Items + * and the values of an open object resolve for no value, since each is its own. + */ + static Object resolveTree(Object node, Object value, BiFunction adjust, Resolver resolve, + List seen) { + Object current = adjust.apply(node, value); + Map map = Json.map(current); + if (map == null) return current; + String key = Json.string(map.get("schema")); + if (key == null) { + return mapChildren(map, (child, name, many) -> resolveTree(child, + many != null ? null : name != null ? Json.get(value, name) : value, adjust, resolve, seen)); + } + Map target = seen.contains(key) ? null : resolve.node(key); + if (target == null) return current; + Map inner = Json.map(resolveTree(target, value, adjust, resolve, Engine.append(seen, key))); + // The reference's own annotations win over the referenced schema's, as they do outside a view. + Map result = new LinkedHashMap<>(inner); + Map annotations = new LinkedHashMap<>(); + if (inner.get("annotations") instanceof Map) annotations.putAll(Json.map(inner.get("annotations"))); + if (map.get("annotations") instanceof Map) annotations.putAll(Json.map(map.get("annotations"))); + result.put("annotations", annotations); + return result; + } + + /** A copy of values with a value at a path, so the fields around it read as they will. {@code []} and {@code *} name no one place. */ + static Object place(Object values, List steps, Object value) { + if (steps.isEmpty()) return value; + Paths.Step step = steps.get(0); + List rest = steps.subList(1, steps.size()); + if (step.kind == Paths.Kind.KEY) { + Map copy = new LinkedHashMap<>(); + if (values instanceof Map) ((Map) values).forEach((key, item) -> copy.put(String.valueOf(key), item)); + copy.put(step.key, place(Json.get(values, step.key), rest, value)); + return copy; + } + if (step.kind == Paths.Kind.INDEX) { + List list = values instanceof List ? new ArrayList<>((List) values) : new ArrayList<>(); + while (list.size() <= step.index) list.add(null); + list.set(step.index, place(list.get(step.index), rest, value)); + return list; + } + return values; + } + + /** Calls back with the input paths conditions read, in {@code input} and {@code valueFrom}, through every group. */ + private static void inputsOf(Object conditions, Consumer found) { + // Datafiles can carry conditions as JSON text, as features' are. + if (conditions instanceof String) { + String text = ((String) conditions).stripLeading(); + if (!(text.startsWith("{") || text.startsWith("[") || text.startsWith("\""))) return; + try { + conditions = JSON.readValue(text, Object.class); + } catch (Exception invalid) { + return; + } + } + if (conditions instanceof List) { + for (Object item : (List) conditions) inputsOf(item, found); + return; + } + Map map = Json.map(conditions); + if (map == null) return; + found.accept(map.get("input")); + if (map.get("valueFrom") instanceof Map) found.accept(Json.get(map.get("valueFrom"), "input")); + for (String group : List.of("and", "or", "not")) inputsOf(map.get(group), found); + } + + /** + * The fields, relative to a node, that the conditions of its mutations and + * issues read, at any depth and through references, as {@code at} takes + * paths: {@code accountType}, {@code address.country} or {@code items[].room}. + */ + static List readsOf(Object node, Resolver resolve) { + List reads = new ArrayList<>(); + visit(node, "", new ArrayList<>(), resolve, reads); + return reads; + } + + private static void visit(Object node, String at, List seen, Resolver resolve, List reads) { + Map current = Json.map(node); + if (current == null) return; + for (String list : List.of("mutations", "issues")) { + if (!(current.get(list) instanceof List)) continue; + for (Object entry : (List) current.get(list)) { + inputsOf(Json.get(entry, "conditions"), path -> { + if (!(path instanceof String)) return; + String joined = at.isEmpty() ? (String) path : at + "." + path; + if (!reads.contains(joined)) reads.add(joined); + }); + } + } + String key = Json.string(current.get("schema")); + if (key != null && !seen.contains(key)) { + visit(resolve.node(key), at, Engine.append(seen, key), resolve, reads); + } + mapChildren(current, (child, name, many) -> { + String path = name != null ? join(at, name) : "[]".equals(many) ? at + "[]" : many != null ? join(at, many) : at; + visit(child, path, seen, resolve, reads); + return child; + }); + } + + private static String join(String at, String path) { + return at.isEmpty() ? path : at + "." + path; + } +} diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java new file mode 100644 index 0000000..a840bc6 --- /dev/null +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java @@ -0,0 +1,142 @@ +package com.featurevisor.schemas; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.featurevisor.sdk.Featurevisor; +import com.featurevisor.sdk.FeaturevisorLogLevel; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** + * A datafile the CLI built, with conditions as JSON text, against what the + * JavaScript package answers for it, messages included. Regenerate + * built-datafile-expected.json with the JavaScript package when the datafile changes. + */ +class BuiltDatafileTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private static String resource(String name) throws Exception { + try (InputStream stream = BuiltDatafileTest.class.getResourceAsStream("/" + name)) { + return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + } + } + + private static Featurevisor instance(Map context) throws Exception { + return Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(resource("built-datafile.json")) + .context(context) + .logLevel(FeaturevisorLogLevel.FATAL)); + } + + @Test + @SuppressWarnings("unchecked") + void validatesAsJavaScriptDoes() throws Exception { + JsonNode expected = JSON.readTree(resource("built-datafile-expected.json")); + for (JsonNode testCase : expected.get("cases")) { + Map context = JSON.convertValue(testCase.get("context"), Map.class); + Schemas schemas = Schemas.create(instance(context)); + String schema = testCase.get("schema").asText(); + ValidationResult result = schemas.validate(schema, JSON.convertValue(testCase.get("value"), Object.class)); + List actual = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) { + Map plain = new LinkedHashMap<>(); + plain.put("message", issue.getMessage()); + plain.put("path", issue.getPath()); + plain.put("code", issue.getCode()); + plain.put("params", issue.getParams()); + plain.put("schema", issue.getSchema()); + if (issue.getMutation() != null) plain.put("mutation", issue.getMutation()); + actual.add(plain); + } + assertEquals(canonical(testCase.get("issues")), canonical(actual), schema + " " + testCase.get("value") + " " + context); + } + } + + @Test + void describesFieldsAsJavaScriptDoes() throws Exception { + JsonNode expected = JSON.readTree(resource("built-datafile-expected.json")).get("members"); + Schemas schemas = Schemas.create(instance(Map.of())); + SchemaHandle signUp = schemas.get("signUp"); + SchemaHandle business = signUp.withInput(Map.of("accountType", "business")); + Map handles = new LinkedHashMap<>(); + handles.put("signUp", signUp); + handles.put("accountType", signUp.at("accountType")); + handles.put("displayName", signUp.at("displayName")); + handles.put("taxId", signUp.at("taxId")); + handles.put("businessTaxId", business.at("taxId")); + handles.put("business", business); + handles.put("checkout", schemas.get("checkout")); + handles.put("register", schemas.get("register")); + for (Map.Entry entry : handles.entrySet()) { + SchemaHandle handle = entry.getValue(); + JsonNode wanted = expected.get(entry.getKey()); + String name = entry.getKey(); + boolean object = handle.getKind() == FieldKind.OBJECT; + assertEquals(wanted.get("path").asText(), handle.getPath(), name); + assertEquals(canonical(wanted.get("fieldKeys")), canonical(handle.getFieldKeys()), name + " fieldKeys"); + assertEquals(canonical(wanted.get("kind")), canonical(handle.getKind() == null ? null : handle.getKind().getValue()), name + " kind"); + assertEquals(canonical(wanted.get("reads")), canonical(handle.getReads()), name + " reads"); + assertEquals(canonical(wanted.get("annotations")), canonical(handle.getAnnotations()), name + " annotations"); + Object constraints; + Object options; + if (object) { + Map byField = new LinkedHashMap<>(); + handle.getFieldConstraints().forEach((field, value) -> byField.put(field, constraintsOf(value))); + constraints = byField; + Map choices = new LinkedHashMap<>(); + handle.getFieldOptions().forEach((field, list) -> choices.put(field, optionsOf(list))); + options = choices; + } else { + constraints = constraintsOf(handle.getConstraints()); + options = optionsOf(handle.getOptions()); + } + assertEquals(canonical(wanted.get("constraints")), canonical(constraints), name + " constraints"); + assertEquals(canonical(wanted.get("options")), canonical(options), name + " options"); + } + } + + private static Map constraintsOf(FieldConstraints constraints) { + Map map = new LinkedHashMap<>(); + if (constraints.isRequired()) map.put("required", true); + if (constraints.getMinLength() != null) map.put("minLength", constraints.getMinLength()); + if (constraints.getMaxLength() != null) map.put("maxLength", constraints.getMaxLength()); + if (constraints.getMin() != null) map.put("min", constraints.getMin()); + if (constraints.getMax() != null) map.put("max", constraints.getMax()); + if (constraints.getStep() != null) map.put("step", constraints.getStep()); + if (constraints.isMultiple()) map.put("multiple", true); + return map; + } + + private static List optionsOf(List options) { + List list = new ArrayList<>(); + for (SchemaOption option : options) list.add(option.asMap()); + return list; + } + + /** JSON text with keys sorted and numbers as JavaScript writes them, so values compare by what they mean. */ + private static String canonical(Object value) { + Object plain = value instanceof JsonNode ? JSON.convertValue(value, Object.class) : value; + return Json.stringify(sorted(plain)); + } + + private static Object sorted(Object value) { + if (value instanceof Map) { + Map sorted = new java.util.TreeMap<>(); + ((Map) value).forEach((key, item) -> sorted.put(String.valueOf(key), sorted(item))); + return sorted; + } + if (value instanceof List) { + List list = new ArrayList<>(); + for (Object item : (List) value) list.add(sorted(item)); + return list; + } + return value; + } +} diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java new file mode 100644 index 0000000..04a0302 --- /dev/null +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java @@ -0,0 +1,108 @@ +package com.featurevisor.schemas; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.featurevisor.sdk.Featurevisor; +import com.featurevisor.sdk.FeaturevisorLogLevel; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.stream.Stream; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +/** Runs conformance/schemas-validation.json, the cases every schemas package passes. */ +class SchemasConformanceTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private static JsonNode fixture() throws Exception { + try (InputStream stream = SchemasConformanceTest.class.getResourceAsStream("/conformance/schemas-validation.json")) { + return JSON.readTree(stream); + } + } + + @Test + void isTheVersionThisRunnerKnows() throws Exception { + JsonNode fixture = fixture(); + assertEquals("featurevisor.schemas-validation", fixture.get("kind").asText()); + assertEquals(2, fixture.get("schemaVersion").asInt()); + assertTrue(fixture.get("cases").size() > 0); + } + + @TestFactory + Stream cases() throws Exception { + List tests = new ArrayList<>(); + for (JsonNode testCase : fixture().get("cases")) { + tests.add(DynamicTest.dynamicTest(testCase.get("name").asText(), () -> run(testCase))); + } + return tests.stream(); + } + + @SuppressWarnings("unchecked") + private static void run(JsonNode testCase) throws Exception { + ObjectNode datafile = JSON.createObjectNode(); + datafile.put("schemaVersion", "4"); + datafile.put("revision", "1"); + datafile.set("segments", testCase.has("segments") ? testCase.get("segments") : JSON.createObjectNode()); + datafile.set("features", JSON.createObjectNode()); + datafile.set("variables", JSON.createObjectNode()); + datafile.set("schemas", testCase.get("schemas")); + Map context = testCase.has("context") ? JSON.convertValue(testCase.get("context"), Map.class) : Map.of(); + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(JSON.writeValueAsString(datafile)) + .context(context) + .logLevel(FeaturevisorLogLevel.FATAL)); + Schemas schemas = Schemas.create(f); + Object value = JSON.convertValue(testCase.get("value"), Object.class); + + List expected = new ArrayList<>(); + for (JsonNode issue : testCase.get("issues")) expected.add(portable(JSON.convertValue(issue, Map.class))); + Collections.sort(expected); + + // Twice, so a compiled schema answers as a fresh one does. + for (int run = 0; run < 2; run++) { + ValidationResult result = schemas.validate(testCase.get("schema").asText(), value); + List actual = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) { + Map portable = new LinkedHashMap<>(); + portable.put("code", issue.getCode()); + portable.put("path", issue.getPath()); + portable.put("params", issue.getParams()); + if (issue.getMutation() != null) portable.put("mutation", issue.getMutation()); + actual.add(portable(portable)); + } + Collections.sort(actual); + assertEquals(expected, actual, testCase.get("name").asText()); + } + } + + /** An issue's portable fields as canonical JSON text: keys sorted, numbers as JavaScript writes them. */ + private static String portable(Map issue) { + Map fields = new LinkedHashMap<>(); + for (String field : List.of("code", "path", "params", "mutation")) if (issue.containsKey(field)) fields.put(field, issue.get(field)); + return Json.stringify(canonical(fields)); + } + + private static Object canonical(Object value) { + if (value instanceof Map) { + Map sorted = new TreeMap<>(); + ((Map) value).forEach((key, item) -> sorted.put(String.valueOf(key), canonical(item))); + return sorted; + } + if (value instanceof List) { + List list = new ArrayList<>(); + for (Object item : (List) value) list.add(canonical(item)); + return list; + } + return value; + } +} diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java new file mode 100644 index 0000000..c765ae4 --- /dev/null +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -0,0 +1,311 @@ +package com.featurevisor.schemas; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.featurevisor.sdk.Featurevisor; +import com.featurevisor.sdk.FeaturevisorLogLevel; +import com.featurevisor.sdk.FeaturevisorUnsubscribe; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; +import org.junit.jupiter.api.Test; + +class SchemasTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private static final String SCHEMAS = "{" + + "\"signUp\":{\"hash\":\"s1\",\"type\":\"object\"," + + " \"properties\":{" + + " \"username\":{\"type\":\"string\",\"minLength\":3,\"annotations\":{\"title\":\"Username\"}}," + + " \"password\":{\"type\":\"string\",\"minLength\":8}," + + " \"confirm\":{\"type\":\"string\"}," + + " \"city\":{\"type\":\"string\"}," + + " \"country\":{\"type\":\"string\",\"enum\":[\"nl\",\"de\"]}," + + " \"code\":{\"type\":\"string\",\"pattern\":\"^[A-Z]{2}$\"}," + + " \"tags\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}" + + " }," + + " \"required\":[\"username\",\"password\"]}," + + "\"spaced\":{\"hash\":\"p1\",\"type\":\"string\",\"pattern\":\"^a\\\\sb$\"}," + + "\"braces\":{\"hash\":\"b1\",\"type\":\"string\",\"pattern\":\"^a{$\"}," + + "\"dots\":{\"hash\":\"d1\",\"type\":\"string\",\"pattern\":\"^a.b$\"}," + + "\"broken\":{\"hash\":\"x1\",\"type\":\"string\",\"pattern\":\"(\"}" + + "}"; + + private static String datafile(String revision, String schemas) { + return "{\"schemaVersion\":\"4\",\"revision\":\"" + revision + "\",\"segments\":{},\"features\":{},\"variables\":{},\"schemas\":" + schemas + "}"; + } + + private final List diagnostics = Collections.synchronizedList(new ArrayList<>()); + + private Featurevisor instance() { + return Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile("1", SCHEMAS)) + .logLevel(FeaturevisorLogLevel.WARN) + .onDiagnostic(diagnostic -> diagnostics.add(diagnostic.getCode()))); + } + + private static Map valid() { + return Map.of("username", "ada", "password", "long enough", "confirm", "long enough"); + } + + public static final class Request { + private final String username; + private final String password; + + Request(String username, String password) { + this.username = username; + this.password = password; + } + + public String getUsername() { return username; } + public String getPassword() { return password; } + } + + @Test + void validatesMapsJsonNodesAndObjectsJacksonCanConvert() { + Schemas schemas = Schemas.create(instance()); + assertTrue(schemas.validate("signUp", valid()).isValid()); + assertTrue(schemas.isValid("signUp", JSON.valueToTree(valid()))); + ValidationResult result = schemas.validate("signUp", new Request("ad", "short")); + assertEquals(List.of("minLength", "minLength"), codes(result)); + assertEquals(List.of(List.of("username"), List.of("password")), paths(result)); + // A list can be an array or a collection too. + assertTrue(schemas.isValid("signUp", Map.of("username", "ada", "password", "long enough", "tags", new String[] { "a" }))); + assertTrue(schemas.isValid("signUp", Map.of("username", "ada", "password", "long enough", "tags", new LinkedHashSet<>(List.of("a"))))); + assertEquals("number", schemas.validate("signUp", Map.of("username", 5, "password", "long enough")).getIssues().get(0).getParams().get("received")); + } + + @Test + void parseThrowsWithTheIssuesAndFlattensThem() { + Schemas schemas = Schemas.create(instance()); + Map value = valid(); + assertSame(value, schemas.parse("signUp", value)); + SchemaValidationException error = assertThrows(SchemaValidationException.class, + () -> schemas.parse("signUp", Map.of("password", "x"))); + assertEquals("signUp", error.getSchema()); + assertEquals("signUp: 2 issues. Value at \"username\" is required.", error.getMessage()); + assertEquals(List.of("Value at \"username\" is required."), error.flatten().getFieldErrors().get("username")); + assertEquals(List.of("Value at \"password\" must be at least 8 characters long (got 1)."), + error.flatten().getFieldErrors().get("password")); + } + + @Test + void wordsIssuesFromTheFormTheApplicationAndTheTranslator() { + SchemasOptions options = new SchemasOptions() + .message("required", "{title} is needed") + .message("minLength", (params, info) -> "At least " + params.get("minLength")); + Schemas schemas = Schemas.create(instance(), options); + ValidationResult result = schemas.validate("signUp", Map.of("password", "x")); + assertEquals(List.of("Username is needed", "At least 8"), messages(result)); + + HandleOptions form = new HandleOptions().message("password", "minLength", "Use {minLength} characters or more"); + assertEquals(List.of("Username is needed", "Use 8 characters or more"), + messages(schemas.get("signUp", form).validate(Map.of("password", "x")))); + + Schemas translated = Schemas.create(instance(), new SchemasOptions() + .translator((issue, info) -> issue.getCode().equals("required") ? "Vereist" : null)); + assertEquals("Vereist", translated.validate("signUp", Map.of("password", "long enough")).getIssues().get(0).getMessage()); + } + + @Test + void refinementsRunAfterTheRulesWhereTheyFoundNothing() { + Refinement match = Refinement.of("passwordsMatch", "confirm", (value, info) -> value.equals(info.read("password"))) + .reads("password").message("Passwords must match"); + Refinement taken = Refinement.async("usernameFree", "username", + (value, info) -> CompletableFuture.supplyAsync(() -> !"taken".equals(value))); + Refinement broken = Refinement.of("broken", "city", (value, info) -> { throw new IllegalStateException("down"); }); + SchemaHandle signUp = Schemas.create(instance()).get("signUp", new HandleOptions().refine(match, taken, broken)); + assertTrue(signUp.hasChecks()); + + assertTrue(signUp.validate(valid()).isValid()); + Map wrong = Map.of("username", "taken", "password", "long enough", "confirm", "other", "city", "Utrecht"); + ValidationResult result = signUp.validateAsync(wrong).join(); + assertEquals(List.of("refine", "refine", "refineError"), codes(result)); + assertEquals("Passwords must match", result.getIssues().get(0).getMessage()); + assertEquals(Map.of("refine", "usernameFree", "title", "Username"), result.getIssues().get(1).getParams()); + assertEquals("Value at \"city\" could not be checked.", result.getIssues().get(2).getMessage()); + + // A rule's issue at the field, or in a field a check reads, holds the check back. + ValidationResult held = signUp.validate(Map.of("username", "ab", "password", "short", "confirm", "other")); + assertEquals(List.of("minLength", "minLength"), codes(held)); + // The rules alone never wait. + assertTrue(signUp.validateRules(Map.of("username", "taken", "password", "long enough")).isValid()); + } + + @Test + void optionSourcesLookUpValuesAndSuggestChoices() { + Map cities = Map.of("utrecht", "Utrecht", "rotterdam", "Rotterdam", "amsterdam", "Amsterdam"); + OptionSource source = OptionSource.of("cities", "city") + .search((query, info) -> { + List found = new ArrayList<>(); + cities.forEach((value, title) -> { + if (title.toLowerCase().startsWith(query.toLowerCase())) found.add(Map.of("value", value, "title", title)); + }); + return found; + }) + .lookup((value, info) -> cities.containsKey(value) ? Map.of("title", cities.get(value)) : null); + SchemaHandle signUp = Schemas.create(instance()).get("signUp", new HandleOptions().optionSource(source)); + SchemaHandle city = signUp.at("city"); + + assertTrue(city.canSearch()); + assertFalse(signUp.at("username").canSearch()); + List suggestions = city.search("ut").join(); + assertEquals(1, suggestions.size()); + assertEquals("utrecht", suggestions.get(0).getValue()); + assertEquals("Utrecht", suggestions.get(0).getTitle()); + assertEquals("Rotterdam", city.lookup("rotterdam").join().getTitle()); + assertNull(city.lookup("amstelveen").join()); + // The schema's own choices come first. + assertEquals("nl", signUp.at("country").lookup("nl").join().getValue()); + + Map value = Map.of("username", "ada", "password", "long enough", "city", "amstelveen"); + ValidationResult result = signUp.validate(value); + assertEquals(List.of("enum"), codes(result)); + assertEquals(Map.of("optionSource", "cities"), result.getIssues().get(0).getParams()); + assertEquals("Value at \"city\" is not one of its choices.", result.getIssues().get(0).getMessage()); + + SchemaHandle async = Schemas.create(instance()).get("signUp", new HandleOptions().optionSource( + OptionSource.of("cities", "city").lookupAsync((found, info) -> CompletableFuture.completedFuture(Optional.empty())))); + assertEquals(List.of("enum"), codes(async.validate(value))); + } + + @Test + void patternsMeanWhatTheyMeanInJavaScript() { + Schemas schemas = Schemas.create(instance()); + // A dollar sign is the end of the value, never a final line break. + assertTrue(schemas.isValid("signUp", Map.of("username", "ada", "password", "long enough", "code", "DE"))); + assertFalse(schemas.isValid("signUp", Map.of("username", "ada", "password", "long enough", "code", "DE\n"))); + // A whitespace class takes JavaScript's whitespace, such as a no break space. + assertTrue(schemas.isValid("spaced", "a b")); + assertTrue(schemas.isValid("spaced", "ab")); + // A brace that starts no quantifier is a brace. + assertTrue(schemas.isValid("braces", "a{")); + // A dot takes U+0085, as JavaScript's does, and no line break. + assertTrue(schemas.isValid("dots", "a\u0085b")); + assertFalse(schemas.isValid("dots", "a\nb")); + // A pattern Java cannot compile fails every value, and says so once. + assertEquals(List.of("pattern"), codes(schemas.validate("broken", "x"))); + schemas.validate("broken", "y"); + assertEquals(1, Collections.frequency(diagnostics, "schema_pattern_unsupported")); + } + + @Test + void aMissingSchemaOrFieldIsAnIssueReportedOnce() { + Schemas schemas = Schemas.create(instance()); + ValidationResult missing = schemas.validate("nothing", Map.of()); + assertEquals(List.of("schemaNotFound"), codes(missing)); + assertEquals("Schema \"nothing\" was not found.", missing.getIssues().get(0).getMessage()); + schemas.validate("nothing", Map.of()); + assertEquals(1, Collections.frequency(diagnostics, "schema_not_found")); + assertEquals(Map.of("schema", "signUp", "field", "address.city"), + schemas.get("signUp").at("address.city").validate("x").getIssues().get(0).getParams()); + assertEquals(List.of("signUp", "spaced", "braces", "dots", "broken"), schemas.getKeys()); + assertTrue(schemas.has("signUp")); + assertFalse(schemas.has("nothing")); + } + + @Test + void handlesReadTheCurrentDatafileAndTellWhenTheirSchemaChanges() { + Featurevisor f = instance(); + Schemas schemas = Schemas.create(f); + SchemaHandle signUp = schemas.get("signUp"); + assertSame(signUp, schemas.get("signUp")); + assertSame(signUp.at("username"), signUp.at("username")); + AtomicInteger changes = new AtomicInteger(); + FeaturevisorUnsubscribe stop = signUp.subscribe(changes::incrementAndGet); + assertEquals(3, signUp.at("username").getConstraints().getMinLength()); + + // A datafile that leaves the schema alone changes nothing. + f.setDatafile(datafile("2", "{}")); + assertEquals(0, changes.get()); + f.setDatafile(datafile("3", "{\"signUp\":{\"hash\":\"s2\",\"type\":\"object\",\"properties\":{\"username\":{\"type\":\"string\",\"minLength\":5}}}}")); + assertEquals(1, changes.get()); + assertEquals(5, signUp.at("username").getConstraints().getMinLength()); + assertEquals(List.of("minLength"), codes(signUp.validate(Map.of("username", "ada")))); + stop.unsubscribe(); + f.setDatafile(datafile("4", "{\"signUp\":{\"hash\":\"s3\",\"type\":\"object\"}}")); + assertEquals(1, changes.get()); + } + + @Test + void aSchemaThatReferencesItselfFollowsTheValueAndFailsALoopClosed() { + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile("1", "{" + + "\"list\":{\"hash\":\"l1\",\"type\":\"array\",\"items\":{\"oneOf\":[{\"schema\":\"list\"},{\"type\":\"string\"}]}}," + + "\"tree\":{\"hash\":\"t1\",\"oneOf\":[{\"schema\":\"tree\"},{\"type\":\"string\"}]}}")) + .logLevel(FeaturevisorLogLevel.WARN) + .onDiagnostic(diagnostic -> diagnostics.add(diagnostic.getCode()))); + Schemas schemas = Schemas.create(f); + assertTrue(schemas.isValid("list", List.of("a", List.of("b", List.of("c"))))); + assertEquals(List.of("oneOf"), codes(schemas.validate("list", List.of(1)))); + assertTrue(schemas.isValid("tree", "a")); + assertEquals(List.of("oneOf"), codes(schemas.validate("tree", 1))); + assertEquals(1, Collections.frequency(diagnostics, "schema_reference_depth")); + } + + @Test + void instancesShareAnSdkInstanceAndCloseCleanly() { + Featurevisor f = instance(); + Schemas first = Schemas.create(f); + Schemas second = Schemas.create(f); + assertTrue(first.isValid("signUp", valid())); + assertTrue(second.isValid("signUp", valid())); + assertFalse(diagnostics.contains("duplicate_module")); + first.close(); + assertTrue(second.isValid("signUp", valid())); + try (Schemas third = Schemas.create(f)) { + assertTrue(third.isValid("signUp", valid())); + } + assertFalse(diagnostics.contains("duplicate_module")); + } + + @Test + void validatesFromManyThreadsAtOnce() throws Exception { + Schemas schemas = Schemas.create(instance()); + SchemaHandle signUp = schemas.get("signUp"); + ExecutorService pool = Executors.newFixedThreadPool(8); + List> results = new ArrayList<>(); + for (int index = 0; index < 400; index++) { + int at = index; + results.add(pool.submit(() -> at % 2 == 0 + ? signUp.isValid(valid()) + : !signUp.isValid(Map.of("username", "a", "password", "b")))); + } + for (Future result : results) assertTrue(result.get()); + pool.shutdown(); + assertTrue(pool.awaitTermination(5, TimeUnit.SECONDS)); + } + + private static List codes(ValidationResult result) { + List codes = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) codes.add(issue.getCode()); + return codes; + } + + private static List paths(ValidationResult result) { + List paths = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) paths.add(issue.getPath()); + return paths; + } + + private static List messages(ValidationResult result) { + List messages = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) messages.add(issue.getMessage()); + return messages; + } +} diff --git a/featurevisor-schemas/src/test/resources/built-datafile-expected.json b/featurevisor-schemas/src/test/resources/built-datafile-expected.json new file mode 100644 index 0000000..80f4847 --- /dev/null +++ b/featurevisor-schemas/src/test/resources/built-datafile-expected.json @@ -0,0 +1,548 @@ +{ + "cases": [ + { + "schema": "signUp", + "value": {}, + "context": {}, + "issues": [ + { + "message": "Value at \"accountType\" is required.", + "path": [ + "accountType" + ], + "code": "required", + "params": { + "key": "accountType", + "title": "Account type" + }, + "schema": "signUp" + }, + { + "message": "Value at \"displayName\" is required.", + "path": [ + "displayName" + ], + "code": "required", + "params": { + "key": "displayName", + "title": "Display name" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "business", + "displayName": "A" + }, + "context": {}, + "issues": [ + { + "message": "Value at \"taxId\" is required.", + "path": [ + "taxId" + ], + "code": "required", + "params": { + "key": "taxId", + "title": "VAT number" + }, + "schema": "signUp", + "mutation": "business" + }, + { + "message": "Use at least 2 characters", + "path": [ + "displayName" + ], + "code": "minLength", + "params": { + "minLength": 2, + "length": 1, + "title": "Display name" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "business", + "displayName": "Ada", + "taxId": "x" + }, + "context": {}, + "issues": [ + { + "message": "Enter your VAT number, such as DE123456789", + "path": [ + "taxId" + ], + "code": "pattern", + "params": { + "pattern": "^[A-Z]{2}[0-9]{9}$", + "title": "VAT number" + }, + "schema": "signUp", + "mutation": "business" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "business", + "displayName": "Ada", + "taxId": "DE123456789" + }, + "context": {}, + "issues": [] + }, + { + "schema": "signUp", + "value": { + "accountType": "personal", + "displayName": "Ada", + "extra": 1 + }, + "context": {}, + "issues": [ + { + "message": "Value at \"extra\" is not allowed.", + "path": [ + "extra" + ], + "code": "additionalProperties", + "params": { + "key": "extra" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "other", + "displayName": 5 + }, + "context": {}, + "issues": [ + { + "message": "Value at \"accountType\" must be one of Personal, Business.", + "path": [ + "accountType" + ], + "code": "enum", + "params": { + "options": [ + "personal", + "business" + ], + "titles": [ + "Personal", + "Business" + ], + "title": "Account type" + }, + "schema": "signUp" + }, + { + "message": "Value at \"displayName\" must be a string (got number).", + "path": [ + "displayName" + ], + "code": "type", + "params": { + "type": "string", + "received": "number", + "title": "Display name" + }, + "schema": "signUp" + } + ] + }, + { + "schema": "signUp", + "value": { + "accountType": "personal", + "displayName": "😀😀" + }, + "context": {}, + "issues": [] + }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "plan": "paid" + }, + "issues": [ + { + "message": "Value at \"customsDescription\" is required.", + "path": [ + "customsDescription" + ], + "code": "required", + "params": { + "key": "customsDescription" + }, + "schema": "checkout", + "mutation": "shipsAbroad" + } + ] + }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "plan": "free" + }, + "issues": [] + }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "shippingCountry": "nl" + }, + "context": { + "plan": "paid" + }, + "issues": [] + }, + { + "schema": "register", + "value": { + "password": "short", + "confirmPassword": "x" + }, + "context": {}, + "issues": [ + { + "message": "Value at \"password\" must be at least 8 characters long (got 5).", + "path": [ + "password" + ], + "code": "minLength", + "params": { + "minLength": 8, + "length": 5 + }, + "schema": "register" + }, + { + "message": "Confirmation does not match the password", + "path": [ + "confirmPassword" + ], + "code": "refine", + "params": { + "refine": "passwordsDiffer", + "title": "Confirmation" + }, + "schema": "register" + } + ] + }, + { + "schema": "register", + "value": { + "password": "long enough", + "confirmPassword": "long enough", + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "country": "nl" + }, + "issues": [ + { + "message": "We ship Dutch orders to the billing country only", + "path": [ + "shippingCountry" + ], + "code": "refine", + "params": { + "refine": "dutchShippingCountry" + }, + "schema": "register" + } + ] + }, + { + "schema": "register", + "value": { + "password": "long enough", + "confirmPassword": "long enough", + "billingCountry": "nl", + "shippingCountry": "de" + }, + "context": { + "country": "de" + }, + "issues": [] + }, + { + "schema": "register", + "value": { + "confirmPassword": "x" + }, + "context": {}, + "issues": [ + { + "message": "Value at \"password\" is required.", + "path": [ + "password" + ], + "code": "required", + "params": { + "key": "password" + }, + "schema": "register" + } + ] + }, + { + "schema": "missing", + "value": {}, + "context": {}, + "issues": [ + { + "message": "Schema \"missing\" was not found.", + "path": [], + "code": "schemaNotFound", + "params": { + "schema": "missing" + }, + "schema": "missing" + } + ] + } + ], + "members": { + "signUp": { + "path": "", + "fieldKeys": [ + "accountType", + "displayName", + "taxId" + ], + "constraints": { + "accountType": { + "required": true + }, + "displayName": { + "required": true, + "minLength": 2, + "maxLength": 40 + }, + "taxId": {} + }, + "options": { + "accountType": [ + { + "value": "personal", + "title": "Personal" + }, + { + "value": "business", + "title": "Business" + } + ] + }, + "kind": "object", + "reads": [ + "accountType" + ], + "annotations": { + "title": "Create your account", + "order": [ + "accountType", + "displayName", + "taxId" + ] + } + }, + "accountType": { + "path": "accountType", + "fieldKeys": [], + "constraints": { + "required": true + }, + "options": [ + { + "value": "personal", + "title": "Personal" + }, + { + "value": "business", + "title": "Business" + } + ], + "kind": "select", + "reads": [], + "annotations": { + "title": "Account type", + "options": { + "personal": { + "title": "Personal" + }, + "business": { + "title": "Business" + } + } + } + }, + "displayName": { + "path": "displayName", + "fieldKeys": [], + "constraints": { + "required": true, + "minLength": 2, + "maxLength": 40 + }, + "options": [], + "kind": "text", + "reads": [], + "annotations": { + "title": "Display name", + "examples": [ + "Ada", + "Grace Hopper" + ] + } + }, + "taxId": { + "path": "taxId", + "fieldKeys": [], + "constraints": {}, + "options": [], + "kind": "text", + "reads": [], + "annotations": { + "title": "VAT number" + } + }, + "businessTaxId": { + "path": "taxId", + "fieldKeys": [], + "constraints": { + "required": true + }, + "options": [], + "kind": "text", + "reads": [], + "annotations": { + "title": "VAT number" + } + }, + "business": { + "path": "", + "fieldKeys": [ + "accountType", + "displayName", + "taxId" + ], + "constraints": { + "accountType": { + "required": true + }, + "displayName": { + "required": true, + "minLength": 2, + "maxLength": 40 + }, + "taxId": { + "required": true + } + }, + "options": { + "accountType": [ + { + "value": "personal", + "title": "Personal" + }, + { + "value": "business", + "title": "Business" + } + ] + }, + "kind": "object", + "reads": [ + "accountType" + ], + "annotations": { + "title": "Create your account", + "order": [ + "accountType", + "displayName", + "taxId" + ] + } + }, + "checkout": { + "path": "", + "fieldKeys": [ + "billingCountry", + "shippingCountry", + "customsDescription", + "password", + "confirmPassword" + ], + "constraints": { + "billingCountry": { + "required": true + }, + "shippingCountry": {}, + "customsDescription": {}, + "password": {}, + "confirmPassword": {} + }, + "options": {}, + "kind": "object", + "reads": [ + "shippingCountry", + "billingCountry" + ], + "annotations": {} + }, + "register": { + "path": "", + "fieldKeys": [ + "password", + "confirmPassword", + "shippingCountry", + "billingCountry" + ], + "constraints": { + "password": { + "required": true, + "minLength": 8 + }, + "confirmPassword": {}, + "shippingCountry": {}, + "billingCountry": {} + }, + "options": {}, + "kind": "object", + "reads": [ + "confirmPassword", + "password", + "shippingCountry", + "billingCountry" + ], + "annotations": {} + } + } +} diff --git a/featurevisor-schemas/src/test/resources/built-datafile.json b/featurevisor-schemas/src/test/resources/built-datafile.json new file mode 100644 index 0000000..5bb7417 --- /dev/null +++ b/featurevisor-schemas/src/test/resources/built-datafile.json @@ -0,0 +1 @@ +{"schemaVersion":"4","featurevisorVersion":"4.13.0","revision":"2","segments":{"netherlands":{"conditions":"{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}"},"paying":{"conditions":"{\"attribute\":\"plan\",\"operator\":\"equals\",\"value\":\"paid\"}"}},"features":{},"variables":{},"schemas":{"checkout":{"hash":"gSboXrZWcM","type":"object","properties":{"billingCountry":{"type":"string"},"shippingCountry":{"type":"string"},"customsDescription":{"type":"string"},"password":{"type":"string"},"confirmPassword":{"type":"string"}},"required":["billingCountry"],"mutations":[{"key":"shipsAbroad","conditions":"[{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}},\"paying\"]","operations":[{"op":"appendUnique","path":["required"],"value":"customsDescription"}]}]},"register":{"hash":"XlDf9sip1o","type":"object","properties":{"password":{"type":"string","minLength":8},"confirmPassword":{"type":"string","annotations":{"title":"Confirmation"}},"shippingCountry":{"type":"string"},"billingCountry":{"type":"string"}},"required":["password"],"issues":[{"key":"passwordsDiffer","conditions":"{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}","path":"confirmPassword","message":"{title} does not match the password"},{"key":"dutchShippingCountry","conditions":"[\"netherlands\",{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}}]","path":"shippingCountry","message":"We ship Dutch orders to the billing country only"}]},"signUp":{"hash":"wLXjboTQnZ","type":"object","properties":{"accountType":{"type":"string","enum":["personal","business"],"annotations":{"title":"Account type","options":{"personal":{"title":"Personal"},"business":{"title":"Business"}}}},"displayName":{"type":"string","minLength":2,"maxLength":40,"annotations":{"title":"Display name","examples":["Ada","Grace Hopper"]}},"taxId":{"type":"string","annotations":{"title":"VAT number"}}},"required":["accountType","displayName"],"messages":{"displayName":{"minLength":"Use at least {minLength} characters"}},"annotations":{"title":"Create your account","order":["accountType","displayName","taxId"]},"mutations":[{"key":"business","conditions":"{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}","operations":[{"op":"appendUnique","path":["required"],"value":"taxId"},{"op":"set","path":["properties","taxId","pattern"],"value":"^[A-Z]{2}[0-9]{9}$"},{"op":"set","path":["properties","taxId","messages"],"value":{"pattern":"Enter your VAT number, such as DE123456789"}}]}]}}} \ No newline at end of file diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/CompareVersions.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/CompareVersions.java index 96a16fd..e4b16f7 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/CompareVersions.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/CompareVersions.java @@ -18,6 +18,17 @@ private CompareVersions() {} Pattern.CASE_INSENSITIVE ); + /** Whether the version operators can compare a value, as a schema's {@code format: semver} asks. */ + public static boolean isValidVersion(Object version) { + if (!(version instanceof String)) return false; + try { + compareVersions((String) version, (String) version); + return true; + } catch (RuntimeException invalid) { + return false; + } + } + /** * Compare two semantic version strings * @param v1 First version string diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ConditionReader.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ConditionReader.java new file mode 100644 index 0000000..6d8d8f9 --- /dev/null +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ConditionReader.java @@ -0,0 +1,20 @@ +package com.featurevisor.sdk; + +/** + * Reads the value a kind of condition leaf only a package knows refers to, + * such as {@code { "input": "country", "operator": "equals", "value": "nl" }}, + * which a schemas package answers from the value it validates. + */ +@FunctionalInterface +public interface ConditionReader { + /** What a reader returns when nothing is at the path, which differs from a JSON {@code null}. */ + Object ABSENT = new Object() { + @Override public String toString() { return "ABSENT"; } + }; + + /** + * The value at a leaf's path, such as {@code country} or {@code items.0.room}, + * or {@link #ABSENT} when there is none. + */ + Object read(String path); +} diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java index b343c56..c2716fc 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java @@ -470,6 +470,16 @@ private static boolean after(Object contextValue, Object conditionValue) { return contextDate.isAfter(conditionDate); } + /** + * A portable timestamp, as {@code before}, {@code after} and a schema's + * {@code format: date-time} read it, to the millisecond, or null for any other + * value: years 0001 to 9999, offsets up to 14 hours, and fractions up to nine + * digits. + */ + public static Instant getPortableTimestamp(Object value) { + return parseDate(value); + } + private static Instant parseDate(Object value) { try { return parsePortableDate(value); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DatafileContent.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DatafileContent.java index 4ad75a8..ef6484a 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DatafileContent.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DatafileContent.java @@ -1,5 +1,8 @@ package com.featurevisor.sdk; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.DeserializationFeature; @@ -11,6 +14,8 @@ import java.util.Map; import java.util.HashMap; import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Collections; public class DatafileContent { @JsonProperty("schemaVersion") @@ -32,6 +37,12 @@ public class DatafileContent { @JsonProperty("variables") private Map variables; + /** + * Every other top level key, as decoded, such as {@code schemas}. One whose + * value is an object is a section, whose entries packages read by key. + */ + private Map others; + // Constructors public DatafileContent() {} @@ -88,6 +99,54 @@ public void setFeatures(Map features) { public Map getVariables() { return variables; } public void setVariables(Map variables) { this.variables = variables; } + /** + * The sections of the datafile by name, such as {@code schemas}: top level + * keys besides the SDK's own whose value is an object, as decoded into maps, + * lists, strings, numbers and booleans. Read only. + */ + @JsonIgnore + public Map> getSections() { + if (others == null) return Collections.emptyMap(); + Map> sections = new LinkedHashMap<>(); + for (Map.Entry entry : others.entrySet()) { + Map section = asSection(entry.getValue()); + if (section != null) sections.put(entry.getKey(), section); + } + return Collections.unmodifiableMap(sections); + } + + /** A section by name, such as {@code schemas}, or null when the datafile has none. */ + @JsonIgnore + public Map getSection(String name) { + return others == null ? null : asSection(others.get(name)); + } + + /** + * Sets a top level key besides the SDK's own, such as a section of entries + * for a package. A value that is not a map is carried, and replaced whole. + */ + @JsonAnySetter + public void setSection(String name, Object value) { + if (others == null) others = new LinkedHashMap<>(); + others.put(name, value); + } + + /** Every top level key besides the SDK's own, as decoded, which serializing writes back. */ + @JsonAnyGetter + Map getOthers() { + return others == null ? Collections.emptyMap() : others; + } + + /** Replaces every top level key besides the SDK's own, named so Jackson never reads it as a property. */ + void replaceOthers(Map others) { + this.others = others == null || others.isEmpty() ? null : others; + } + + @SuppressWarnings("unchecked") + static Map asSection(Object value) { + return value instanceof Map ? (Map) value : null; + } + /** * Static method to parse JSON string into DatafileContent object * diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DependencyOf.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DependencyOf.java index de274e9..6d84fb1 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DependencyOf.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/DependencyOf.java @@ -7,11 +7,22 @@ public final class DependencyOf { private final String type; private final String featureKey; private final String variableKey; + private final String key; public DependencyOf(String type, String featureKey, String variableKey) { + this(type, featureKey, variableKey, null); + } + + private DependencyOf(String type, String featureKey, String variableKey, String key) { this.type = type; this.featureKey = featureKey; this.variableKey = variableKey; + this.key = key; + } + + /** A package's entry asking, such as {@code ("schema", "signUp")}. */ + public static DependencyOf ofEntry(String type, String key) { + return new DependencyOf(type, null, null, key); } static DependencyOf from(EvaluateOptions options) { @@ -21,14 +32,17 @@ static DependencyOf from(EvaluateOptions options) { public String getType() { return type; } public String getFeatureKey() { return featureKey; } public String getVariableKey() { return variableKey; } + /** A package entry's key, such as a schema's, or null for a feature or variable. */ + public String getKey() { return key; } @Override public boolean equals(Object other) { if (!(other instanceof DependencyOf)) return false; DependencyOf value = (DependencyOf) other; return Objects.equals(type, value.type) && Objects.equals(featureKey, value.featureKey) - && Objects.equals(variableKey, value.variableKey); + && Objects.equals(variableKey, value.variableKey) + && Objects.equals(key, value.key); } - @Override public int hashCode() { return Objects.hash(type, featureKey, variableKey); } + @Override public int hashCode() { return Objects.hash(type, featureKey, variableKey, key); } } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java index bddc6ce..fb0e16c 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java @@ -287,7 +287,7 @@ private static boolean condition(Object expression, EvaluateOptions options) { if (!(value.get("feature") instanceof String)) return false; EvaluateOptions clean = options.copy().featureKey((String) value.get("feature")) .globalVariable(false).variableKey(null).defaultVariationValue(null) - .defaultVariableValue(null, false); + .defaultVariableValue(null, false).readers(null); boolean enabled = !value.containsKey("enabled") || Boolean.TRUE.equals(value.get("enabled")); if (Boolean.TRUE.equals(readDependency(clean.type(Evaluation.TYPE_FLAG))) != enabled) return false; return !value.containsKey("variation") @@ -296,6 +296,13 @@ private static boolean condition(Object expression, EvaluateOptions options) { if (value.containsKey("attribute")) { return options.getInstanceEvaluationDataProvider().allConditionsAreMatched(expression, options.getContext()); } + // A leaf only a package knows, such as `input`, is read through the package's reader. + Map readers = options.getReaders(); + if (readers != null && !readers.isEmpty()) { + for (Object name : value.keySet()) { + if (readers.containsKey(name)) return readerCondition(value, readers, (String) name, options); + } + } for (String group : List.of("and", "or", "not")) { if (!value.containsKey(group)) continue; if (!(value.get(group) instanceof List) || ((List) value.get(group)).isEmpty()) return false; @@ -310,6 +317,43 @@ private static boolean condition(Object expression, EvaluateOptions options) { return false; } + private static boolean readerCondition(Map leaf, Map readers, String kind, + EvaluateOptions options) { + if (!(leaf.get("operator") instanceof String)) return false; + String operatorName = (String) leaf.get("operator"); + Operator operator; + try { operator = Operator.fromValue(operatorName); } + catch (IllegalArgumentException unknown) { return false; } + // `value` is always a value. `valueFrom` reads the other side, such as another input. + Object compared = leaf.get("value"); + boolean hasCompared = leaf.containsKey("value"); + if (leaf.containsKey("valueFrom")) { + Object from = leaf.get("valueFrom"); + String other = null; + if (from instanceof Map) { + for (Object name : ((Map) from).keySet()) { + if (readers.containsKey(name)) { other = (String) name; break; } + } + } + // A source no reader answers matches nothing, and a pattern read from + // a value is one nobody reviewed, so it never runs. + if (other == null || operatorName.endsWith("atches")) return false; + Object read = readers.get(other).read(String.valueOf(((Map) from).get(other))); + hasCompared = read != ConditionReader.ABSENT; + compared = hasCompared ? read : null; + } + Object read = readers.get(kind).read(String.valueOf(leaf.get(kind))); + boolean present = read != ConditionReader.ABSENT; + if (!hasCompared) { + // Without a value to compare, JavaScript compares with undefined, which only an absent read equals. + if (operator == Operator.EQUALS) return !present; + if (operator == Operator.NOT_EQUALS) return present; + } + String regexFlags = leaf.get("regexFlags") instanceof String ? (String) leaf.get("regexFlags") : ""; + return Conditions.valueIsMatched(present ? read : null, present, operator, compared, regexFlags, + (pattern, flags) -> options.getInstanceEvaluationDataProvider().getRegex(pattern, flags)); + } + private static boolean variableCondition(Object required, EvaluateOptions options) { if (!(required instanceof Map)) return false; Map map = (Map) required; @@ -322,7 +366,8 @@ private static boolean variableCondition(Object required, EvaluateOptions option .defaultVariableValue(null, false) .defaultVariationValue(null) .type(Evaluation.TYPE_VARIABLE) - .variableKey(variableKey); + .variableKey(variableKey) + .readers(null); if (featureValue instanceof String) { value = readDependency(clean.featureKey((String) featureValue).globalVariable(false)); } else { diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java index 7c5e6e8..2bff758 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java @@ -30,6 +30,8 @@ public class EvaluateOptions { private EvaluationSession session; private DependencyOf dependencyOf; private String dependencyPurpose; + /** Readers for leaves only a package can answer, such as {@code input}. */ + private Map readers; interface StickySource { StickyState read(); } static final class StickyState { final Map features; @@ -105,6 +107,8 @@ public void setDefaultVariableValue(Object defaultVariableValue) { this.defaultVariableValueSet = true; } void setSession(EvaluationSession session) { this.session = session; } + Map getReaders() { return readers; } + EvaluateOptions readers(Map value) { this.readers = value; return this; } public void setDependencyOf(DependencyOf dependencyOf) { this.dependencyOf = dependencyOf; } void setStickySource(StickySource source, boolean features, boolean variables) { stickySource = source; @@ -202,6 +206,7 @@ public EvaluateOptions copy() { copy.session = this.session; copy.dependencyOf = this.dependencyOf; copy.dependencyPurpose = this.dependencyPurpose; + copy.readers = this.readers; copy.stickySource = this.stickySource; copy.inheritedStickyFeatures = this.inheritedStickyFeatures; copy.inheritedStickyVariables = this.inheritedStickyVariables; diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java index bcff853..c466cbd 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java @@ -118,6 +118,7 @@ private static FeaturevisorEventDetails getParamsForDatafileSetEvent( details.put("revisionChanged", !Objects.equals(previousDatafileContent.getRevision(), newDatafileContent.getRevision())); details.put("features", newDatafileContent.getFeatures() == null ? new ArrayList<>() : new ArrayList<>(newDatafileContent.getFeatures().keySet())); details.put("variables", newDatafileContent.getVariables() == null ? new ArrayList<>() : new ArrayList<>(newDatafileContent.getVariables().keySet())); + details.put("sections", getChangedSections(previousDatafileContent, newDatafileContent)); details.put("replaced", replace); return details; } @@ -169,8 +170,43 @@ private static FeaturevisorEventDetails getParamsForDatafileSetEvent( currentProvider == null ? Dependencies.create(newDatafileContent) : currentProvider.deriveDependencyIndex(previousProvider)); details.put("features", new ArrayList<>(changedFeatures)); details.put("variables", new ArrayList<>(variableKeys)); + details.put("sections", getChangedSections(previousDatafileContent, newDatafileContent)); details.put("replaced", replace); return details; } + + /** + * The changed entries of every section in either datafile, by hash: added, + * changed or, on replace, removed. The first datafile reports every entry. + */ + static Map> getChangedSections(DatafileContent previous, DatafileContent next) { + Map> before = previous.getSections(); + Map> after = next.getSections(); + Map> sections = new java.util.LinkedHashMap<>(); + if (before.isEmpty() && after.isEmpty()) return sections; + Set names = new java.util.LinkedHashSet<>(before.keySet()); + names.addAll(after.keySet()); + for (String name : names) { + sections.put(name, getChangedEntryKeys( + before.getOrDefault(name, java.util.Collections.emptyMap()), + after.getOrDefault(name, java.util.Collections.emptyMap()))); + } + return sections; + } + + private static List getChangedEntryKeys(Map previous, Map next) { + if (previous.isEmpty()) return new ArrayList<>(next.keySet()); + List keys = new ArrayList<>(); + for (String key : previous.keySet()) { + if (!next.containsKey(key) || hashChanged(entryHash(previous.get(key)), entryHash(next.get(key)))) keys.add(key); + } + for (String key : next.keySet()) if (!previous.containsKey(key)) keys.add(key); + return keys; + } + + private static String entryHash(Object entry) { + Object hash = entry instanceof Map ? ((Map) entry).get("hash") : null; + return hash instanceof String ? (String) hash : null; + } } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java index bca434d..a23049a 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java @@ -311,9 +311,62 @@ public Runnable onDiagnostic(FeaturevisorDiagnosticHandler handler, Featurevisor public void reportDiagnostic(FeaturevisorDiagnostic diagnostic) { Featurevisor.this.reportDiagnostic(diagnostic, module); } + + @Override + public Object getEntry(String section, String key) { + Map entries = Featurevisor.this.evaluationData.getSection(section); + return entries != null && key != null ? entries.get(key) : null; + } + + @Override + public List getEntryKeys(String section) { + Map entries = Featurevisor.this.evaluationData.getSection(section); + return entries != null ? new ArrayList<>(entries.keySet()) : new ArrayList<>(); + } + + @Override + public boolean matchConditions(Object conditions, Map context, MatchConditionsOptions options) { + return Featurevisor.this.matchConditions(conditions, context, options, module); + } }; } + /** A package's conditions, answered in one dependency session of their own. */ + private boolean matchConditions(Object conditions, Map context, + MatchConditionsOptions options, FeaturevisorModule module) { + if (options == null) options = new MatchConditionsOptions(); + String type = options.getType() != null ? options.getType() + : module != null && module.getName() != null ? module.getName() : "package"; + EvaluateOptions evaluateOptions = getEvaluationDependencies(context, null); + if (!options.getReaders().isEmpty()) evaluateOptions.readers(options.getReaders()); + EvaluationSession session = evaluateOptions.getSession(); + // A session opens for this call, so feature and variable leaves read as dependencies of the entry. + boolean ownsRoot = session.beginRoot(DependencyOf.ofEntry(type, options.getKey())); + session.retainCallbackOptions(evaluateOptions); + try { + Object parsed = conditions instanceof String && Normalize.stringified((String) conditions) + ? evaluateOptions.getInstanceEvaluationDataProvider().parseConditionsIfStringified(conditions) + : conditions; + boolean matched = Evaluate.conditionsAreMatched(parsed, evaluateOptions); + session.throwIfFatal(); + return matched; + } catch (RuntimeException | StackOverflowError error) { + Map details = new HashMap<>(); + details.put("type", type); + details.put("key", options.getKey()); + reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.ERROR) + .code("evaluation_error") + .message("matchConditions failed") + .details(details) + .originalError(error), + module); + return false; + } finally { + if (ownsRoot) session.endRoot(); + } + } + private void clearModuleDiagnosticSubscriptions(FeaturevisorModule module) { if (module == null) { return; @@ -540,6 +593,22 @@ private DatafileContent mergeDatafiles(DatafileContent previous, DatafileContent if (incoming.getVariables() != null) { variables.putAll(incoming.getVariables()); } merged.setVariables(variables); + // Sections merge by entry, as segments do. A top level value that is not an + // object is carried and replaced whole. + Map others = new java.util.LinkedHashMap<>(previous.getOthers()); + for (Map.Entry entry : incoming.getOthers().entrySet()) { + Map current = DatafileContent.asSection(others.get(entry.getKey())); + Map next = DatafileContent.asSection(entry.getValue()); + if (current != null && next != null) { + Map section = new java.util.LinkedHashMap<>(current); + section.putAll(next); + others.put(entry.getKey(), section); + } else { + others.put(entry.getKey(), entry.getValue()); + } + } + merged.replaceOthers(others); + return merged; } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java index d16cb3d..ab2eab8 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java @@ -1,5 +1,8 @@ package com.featurevisor.sdk; +import java.util.List; +import java.util.Map; + public interface FeaturevisorModuleApi { String getRevision(); @@ -8,4 +11,38 @@ public interface FeaturevisorModuleApi { Runnable onDiagnostic(FeaturevisorDiagnosticHandler handler, FeaturevisorModuleDiagnosticOptions options); void reportDiagnostic(FeaturevisorDiagnostic diagnostic); + + /** + * An entry of a datafile section, such as {@code getEntry("schemas", "signUp")}, + * as stored and never copied, so treat it as read only. Null when the section + * or the entry is missing. A section is any top level datafile key besides the + * SDK's own whose value is an object. + */ + default Object getEntry(String section, String key) { + throw new UnsupportedOperationException("This module API cannot read datafile sections"); + } + + /** The keys of a datafile section's entries, or an empty list for a missing section. */ + default List getEntryKeys(String section) { + throw new UnsupportedOperationException("This module API cannot read datafile sections"); + } + + /** + * Answers conditions as Core writes them in datafiles, for a package's own + * entries, with the instance's engine: segments, attributes, and feature and + * variable leaves, which read through the getters in one dependency session, + * with sticky values and modules. Readers answer leaves only the package + * knows, such as {@code input}, and {@code valueFrom} naming a reader compares + * two reads. {@code value} is always a value, never read. The context is merged + * over the instance's, as a getter's is. Conditions can be JSON text. A + * condition that cannot be answered, such as a dependency cycle, reports + * {@code evaluation_error} and does not match. + */ + default boolean matchConditions(Object conditions, Map context, MatchConditionsOptions options) { + throw new UnsupportedOperationException("This module API cannot match conditions"); + } + + default boolean matchConditions(Object conditions, Map context) { + return matchConditions(conditions, context, null); + } } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java index a7d3bc5..4ffded4 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java @@ -76,6 +76,8 @@ public ForceResult(Force force, Integer forceIndex) { private Map segments; private Map features; private Map variables; + /** Top level keys besides the SDK's own, such as a {@code schemas} section, kept as the datafile has them. */ + private Map others; private DiagnosticReporter diagnostics; private Dependencies.Index dependencyIndex; @@ -122,6 +124,7 @@ public InstanceEvaluationDataProvider(InstanceEvaluationDataProviderOptions opti this.segments = datafile.getSegments(); this.features = datafile.getFeatures(); this.variables = datafile.getVariables(); + this.others = datafile.getOthers(); if (this.segments == null) { this.segments = new HashMap<>(); } @@ -152,9 +155,15 @@ public DatafileContent getDatafile() { datafile.setSegments(this.segments); datafile.setFeatures(this.features); datafile.setVariables(this.variables); + datafile.replaceOthers(this.others); return datafile; } + /** A section of the datafile by name, such as {@code schemas}, or null when it has none. */ + Map getSection(String name) { + return DatafileContent.asSection(others.get(name)); + } + public Segment getSegment(String segmentKey) { Segment segment = segments.get(segmentKey); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/MatchConditionsOptions.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/MatchConditionsOptions.java new file mode 100644 index 0000000..75a6a6e --- /dev/null +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/MatchConditionsOptions.java @@ -0,0 +1,33 @@ +package com.featurevisor.sdk; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Options for {@link FeaturevisorModuleApi#matchConditions}: what is asking, + * such as {@code type("schema").key("signUp")}, which feature and variable + * leaves see as their {@code dependencyOf}, and readers for leaves only the + * package knows, such as {@code input}. + */ +public final class MatchConditionsOptions { + private String type; + private String key; + private Map readers; + + public MatchConditionsOptions type(String type) { this.type = type; return this; } + public MatchConditionsOptions key(String key) { this.key = key; return this; } + + /** Answers leaves with this key, such as {@code input}, through the reader. */ + public MatchConditionsOptions reader(String name, ConditionReader reader) { + if (readers == null) readers = new LinkedHashMap<>(); + readers.put(name, reader); + return this; + } + + public String getType() { return type; } + public String getKey() { return key; } + public Map getReaders() { + return readers == null ? Collections.emptyMap() : Collections.unmodifiableMap(readers); + } +} diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/VariableMutations.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/VariableMutations.java index b827c42..409923b 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/VariableMutations.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/VariableMutations.java @@ -6,7 +6,9 @@ import java.util.Map; /** Immutable interpreter for compiled variable override operations. */ -final class VariableMutations { +public final class VariableMutations { + private static final com.fasterxml.jackson.databind.ObjectMapper JSON = new com.fasterxml.jackson.databind.ObjectMapper(); + private static final List OPERATIONS = List.of( "set", "append", "prepend", "appendUnique", "removeValue", "before", "after", "remove" ); @@ -14,6 +16,24 @@ final class VariableMutations { private VariableMutations() {} + /** + * Applies compiled operations, such as a schema mutation's, to a copy of a + * value made of maps, lists and primitives, which is left unchanged. Each + * operation is a {@link VariableMutationOperation} or a map as a datafile + * holds it. Throws {@link IllegalArgumentException} for an operation the + * interpreter refuses, such as an unknown {@code op} or an unsafe key. + */ + public static Object applyVariableOperations(Object value, List operations) { + if (operations == null) throw new IllegalArgumentException("Invalid variable mutation operations"); + List typed = new ArrayList<>(operations.size()); + for (Object operation : operations) { + if (operation instanceof VariableMutationOperation) typed.add((VariableMutationOperation) operation); + else if (operation instanceof Map) typed.add(JSON.convertValue(operation, VariableMutationOperation.class)); + else throw new IllegalArgumentException("Invalid variable mutation operation"); + } + return apply(value, typed); + } + static Object apply(Object value, List operations) { if (operations == null) throw new IllegalArgumentException("Invalid variable mutation operations"); Object current = value; diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java new file mode 100644 index 0000000..6ecb416 --- /dev/null +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java @@ -0,0 +1,113 @@ +package com.featurevisor.sdk; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +/** matchConditions on the module API, as the JavaScript SDK's moduleConditions.spec.ts pins it. */ +class ModuleConditionsTest { + private static final String DATAFILE = "{\"schemaVersion\":\"4\",\"revision\":\"1\"," + + "\"segments\":{" + + "\"dutch\":{\"hash\":\"d1\",\"conditions\":[{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}]}," + + "\"payingDutch\":{\"hash\":\"p1\",\"conditions\":{\"and\":[\"dutch\",{\"feature\":\"paid\"}]}}}," + + "\"features\":{\"paid\":{\"hash\":\"f1\",\"bucketBy\":\"userId\"," + + "\"traffic\":[{\"key\":\"everyone\",\"conditions\":\"*\",\"percentage\":100000}]}}," + + "\"variables\":{}}"; + + private final List diagnostics = new ArrayList<>(); + + private FeaturevisorModuleApi setup(FeaturevisorModule... modules) { + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(DATAFILE) + .logLevel(FeaturevisorLogLevel.ERROR) + .context(Map.of("country", "nl")) + .onDiagnostic(diagnostic -> diagnostics.add(diagnostic.getCode()))); + for (FeaturevisorModule module : modules) f.addModule(module); + AtomicReference api = new AtomicReference<>(); + f.addModule(new FeaturevisorModule("@featurevisor/schemas").setup(api::set)); + return api.get(); + } + + private static Map leaf(String input, String operator, Object value) { + Map leaf = new HashMap<>(); + leaf.put("input", input); + leaf.put("operator", operator); + leaf.put("value", value); + return leaf; + } + + @Test + void answersAttributesSegmentsAndFeatureLeavesWithTheInstancesEngine() { + FeaturevisorModuleApi api = setup(); + assertTrue(api.matchConditions("*", Map.of())); + assertTrue(api.matchConditions(List.of(Map.of("attribute", "country", "operator", "equals", "value", "nl")), Map.of())); + assertFalse(api.matchConditions("dutch", Map.of("country", "de"))); + assertTrue(api.matchConditions("payingDutch", Map.of())); + assertFalse(api.matchConditions(Map.of("not", List.of(Map.of("feature", "paid"))), Map.of())); + // Conditions as JSON text, as Core writes them by default. + assertTrue(api.matchConditions("[\"dutch\"]", Map.of())); + assertTrue(diagnostics.isEmpty()); + } + + @Test + void readsLeavesOnlyThePackageKnowsThroughItsReaders() { + FeaturevisorModuleApi api = setup(); + Map value = new HashMap<>(Map.of("accountType", "business", "password", "a", "confirm", "a")); + MatchConditionsOptions readers = new MatchConditionsOptions() + .reader("input", path -> value.containsKey(path) ? value.get(path) : ConditionReader.ABSENT); + + assertTrue(api.matchConditions(Map.of("and", List.of("dutch", leaf("accountType", "equals", "business"))), Map.of(), readers)); + Map same = new HashMap<>(Map.of("input", "confirm", "operator", "equals", "valueFrom", Map.of("input", "password"))); + assertTrue(api.matchConditions(same, Map.of(), readers)); + value.put("confirm", "b"); + assertFalse(api.matchConditions(same, Map.of(), readers)); + // `value` is always a value, even an object naming a reader. + value.put("confirm", "a"); + assertFalse(api.matchConditions(leaf("confirm", "equals", Map.of("input", "password")), Map.of(), readers)); + // A pattern read from a value never runs, nor a source no reader answers. + assertFalse(api.matchConditions(Map.of("input", "confirm", "operator", "matches", "valueFrom", Map.of("input", "password")), Map.of(), readers)); + assertFalse(api.matchConditions(Map.of("input", "confirm", "operator", "equals", "valueFrom", Map.of("attribute", "country")), Map.of(), readers)); + // Without a reader for its kind, a leaf does not match. + assertFalse(api.matchConditions(leaf("accountType", "equals", "business"), Map.of())); + // Absent differs from null. + assertTrue(api.matchConditions(Map.of("input", "missing", "operator", "notExists"), Map.of(), readers)); + assertFalse(api.matchConditions(Map.of("input", "missing", "operator", "isNull"), Map.of(), readers)); + // Without a value to compare, JavaScript compares with undefined, which only an absent read equals. + value.put("nothing", null); + assertTrue(api.matchConditions(Map.of("input", "missing", "operator", "equals"), Map.of(), readers)); + assertFalse(api.matchConditions(Map.of("input", "nothing", "operator", "equals"), Map.of(), readers)); + assertTrue(api.matchConditions(Map.of("input", "nothing", "operator", "notEquals"), Map.of(), readers)); + assertFalse(api.matchConditions(Map.of("input", "nothing", "operator", "equals", "valueFrom", Map.of("input", "missing")), Map.of(), readers)); + } + + @Test + void featureLeavesReachModulesAsDependenciesOfThePackagesEntry() { + List seen = new ArrayList<>(); + FeaturevisorModule observer = new FeaturevisorModule("observer").afterEvaluation((evaluation, options) -> { + DependencyOf parent = options.getDependencyOf(); + seen.add(evaluation.getFeatureKey() + " for " + parent.getType() + " " + parent.getKey()); + return evaluation; + }); + FeaturevisorModuleApi api = setup(observer); + assertTrue(api.matchConditions(List.of(Map.of("feature", "paid")), Map.of(), + new MatchConditionsOptions().type("schema").key("signUp"))); + assertEquals(List.of("paid for schema signUp"), seen); + } + + @Test + void aConditionThatCannotBeAnsweredReportsEvaluationErrorAndDoesNotMatch() { + FeaturevisorModuleApi api = setup(); + MatchConditionsOptions readers = new MatchConditionsOptions().reader("input", path -> { + throw new IllegalStateException("broken reader"); + }); + assertFalse(api.matchConditions(leaf("x", "equals", 1), Map.of(), readers)); + assertEquals(List.of("evaluation_error"), diagnostics); + } +} diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/SectionsConformanceTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/SectionsConformanceTest.java new file mode 100644 index 0000000..9b8a63c --- /dev/null +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/SectionsConformanceTest.java @@ -0,0 +1,142 @@ +package com.featurevisor.sdk; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.jupiter.api.Test; + +/** Runs conformance/sdk-sections.json: sections change no evaluation, and modules read them by entry. */ +class SectionsConformanceTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private JsonNode fixture() throws Exception { + try (InputStream stream = getClass().getResourceAsStream("/conformance/sdk-sections.json")) { + JsonNode fixture = JSON.readTree(stream); + assertEquals("featurevisor.sdk-sections", fixture.get("kind").asText()); + assertEquals(1, fixture.get("schemaVersion").asInt()); + return fixture; + } + } + + private static String datafileText(JsonNode datafile) throws Exception { + return datafile.isTextual() ? datafile.asText() : JSON.writeValueAsString(datafile); + } + + @Test + void sectionsChangeNoEvaluation() throws Exception { + for (JsonNode testCase : fixture().get("evaluationCases")) { + Map context = JSON.convertValue(testCase.get("context"), Map.class); + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafileText(testCase.get("datafile"))) + .context(context) + .logLevel(FeaturevisorLogLevel.FATAL)); + for (int run = 0; run < 2; run++) { + for (JsonNode result : testCase.get("results")) { + String method = result.get("method").asText(); + JsonNode args = result.get("args"); + Object actual; + switch (method) { + case "isEnabled": actual = f.isEnabled(args.get(0).asText()); break; + case "getVariation": actual = f.getVariation(args.get(0).asText()); break; + case "getVariable": + actual = args.size() == 1 ? f.getVariable(args.get(0).asText()) + : f.getVariable(args.get(0).asText(), args.get(1).asText()); + break; + default: throw new IllegalStateException("Unknown method " + method); + } + assertEquals(JSON.convertValue(result.get("value"), Object.class), actual, + testCase.get("name").asText() + ": " + method + " " + args); + } + } + } + } + + @Test + void sectionsCarryThroughMergeAndReplace() throws Exception { + for (JsonNode testCase : fixture().get("carriageCases")) { + String name = testCase.get("name").asText(); + AtomicReference api = new AtomicReference<>(); + List events = new ArrayList<>(); + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafileText(testCase.get("initial").get("datafile"))) + .logLevel(FeaturevisorLogLevel.FATAL)); + f.addModule(new FeaturevisorModule("sections").setup(api::set)); + f.on(FeaturevisorEventName.DATAFILE_SET, details -> events.add(details)); + expect(name + " initially", api.get(), testCase.get("expectInitial"), null); + + int index = 0; + for (JsonNode operation : testCase.get("operations")) { + assertEquals("setDatafile", operation.get("action").asText()); + f.setDatafile(datafileText(operation.get("datafile")), operation.get("replace").asBoolean()); + expect(name + " after operation " + index++, api.get(), operation.get("expect"), + events.get(events.size() - 1)); + } + } + } + + @SuppressWarnings("unchecked") + private static void expect(String name, FeaturevisorModuleApi api, JsonNode expected, + FeaturevisorEventDetails details) { + if (expected.has("sections")) { + Map> sections = (Map>) details.get("sections"); + Map wanted = JSON.convertValue(expected.get("sections"), Map.class); + assertEquals(wanted.keySet(), sections.keySet(), name + ": sections"); + expected.get("sections").fields().forEachRemaining(entry -> + assertEquals(unordered(entry.getValue()), new HashSet<>(sections.get(entry.getKey())), + name + ": changed entries of " + entry.getKey())); + } + if (expected.has("entryKeys")) { + expected.get("entryKeys").fields().forEachRemaining(entry -> + assertEquals(unordered(entry.getValue()), new HashSet<>(api.getEntryKeys(entry.getKey())), + name + ": entry keys of " + entry.getKey())); + } + if (expected.has("entries")) { + for (JsonNode entry : expected.get("entries")) { + Object actual = api.getEntry(entry.get("section").asText(), entry.get("key").asText()); + if (entry.get("value").isNull()) assertNull(actual, name + ": entry is absent"); + else assertEquals(JSON.convertValue(entry.get("value"), Object.class), actual, name + ": entry"); + } + } + } + + private static HashSet unordered(JsonNode list) { + HashSet values = new HashSet<>(); + list.forEach(item -> values.add(item.asText())); + return values; + } + + @Test + void decodingAndSerializingKeepSections() throws Exception { + String text = "{\"schemaVersion\":\"4\",\"revision\":\"1\",\"segments\":{},\"features\":{}," + + "\"variables\":{},\"schemas\":{\"signUp\":{\"hash\":\"s1\",\"type\":\"object\"}},\"note\":\"kept\"}"; + DatafileContent datafile = DatafileContent.fromJson(text); + assertEquals(Collections.singleton("schemas"), datafile.getSections().keySet()); + assertEquals("s1", ((Map) datafile.getSection("schemas").get("signUp")).get("hash")); + assertNull(datafile.getSection("note")); + JsonNode written = JSON.readTree(datafile.toJson()); + assertEquals("kept", written.get("note").asText()); + assertTrue(written.get("schemas").has("signUp")); + assertTrue(!written.has("sections") && !written.has("others")); + + // A datafile built in code carries a section set on it. + AtomicReference api = new AtomicReference<>(); + DatafileContent built = new DatafileContent("4", "2"); + built.setSegments(new java.util.HashMap<>()); + built.setFeatures(new java.util.HashMap<>()); + built.setSection("schemas", Map.of("coupon", Map.of("hash", "c1"))); + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafile(built).logLevel(FeaturevisorLogLevel.FATAL)); + f.addModule(new FeaturevisorModule("sections").setup(api::set)); + assertEquals(List.of("coupon"), api.get().getEntryKeys("schemas")); + } +} diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java index fa8dea7..8c6b597 100644 --- a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java @@ -176,7 +176,10 @@ private Map event(String target, FeaturevisorEventName name, Map value = new LinkedHashMap<>(); value.put("target", target); value.put("name", name.getValue()); - value.put("details", new LinkedHashMap<>(details)); + Map portable = new LinkedHashMap<>(details); + // `sections` in datafile_set is not yet part of the portable fixtures, as in JavaScript. + if (name == FeaturevisorEventName.DATAFILE_SET) portable.remove("sections"); + value.put("details", portable); return value; } diff --git a/pom.xml b/pom.xml index e109755..b8ac80b 100644 --- a/pom.xml +++ b/pom.xml @@ -10,12 +10,13 @@ pom Featurevisor Java - Featurevisor Java SDK and OpenFeature provider + Featurevisor Java SDK, OpenFeature provider and schemas https://github.com/featurevisor/featurevisor-java featurevisor-sdk featurevisor-openfeature + featurevisor-schemas diff --git a/scripts/verify-artifacts.sh b/scripts/verify-artifacts.sh index bab3ce8..4b6e96e 100644 --- a/scripts/verify-artifacts.sh +++ b/scripts/verify-artifacts.sh @@ -5,9 +5,25 @@ set -euo pipefail version="$(sed -n 's/.*\([^<]*\)<\/revision>.*/\1/p' pom.xml)" sdk_jar="featurevisor-sdk/target/featurevisor-java-$version.jar" provider_jar="featurevisor-openfeature/target/featurevisor-openfeature-$version.jar" +schemas_jar="featurevisor-schemas/target/featurevisor-schemas-$version.jar" -if [[ -z "$version" || ! -f "$sdk_jar" || ! -f "$provider_jar" ]]; then - echo "Expected SDK and provider JARs were not found" >&2 +if [[ -z "$version" || ! -f "$sdk_jar" || ! -f "$provider_jar" || ! -f "$schemas_jar" ]]; then + echo "Expected SDK, provider and schemas JARs were not found" >&2 + exit 1 +fi + +if jar tf "$sdk_jar" | grep '^com/featurevisor/schemas/' >/dev/null; then + echo "The Featurevisor SDK JAR contains schemas classes" >&2 + exit 1 +fi + +if ! jar tf "$schemas_jar" | grep '^com/featurevisor/schemas/Schemas.class$' >/dev/null; then + echo "The schemas JAR does not contain its Schemas class" >&2 + exit 1 +fi + +if ! grep -A1 'featurevisor-java' featurevisor-schemas/.flattened-pom.xml | grep -Fq "$version"; then + echo "Schemas dependency does not match SDK revision $version" >&2 exit 1 fi @@ -36,7 +52,7 @@ if ! grep -q 'dev\.openfeature' featurevisor-openfeature/.fla exit 1 fi -for pom in .flattened-pom.xml featurevisor-sdk/.flattened-pom.xml featurevisor-openfeature/.flattened-pom.xml; do +for pom in .flattened-pom.xml featurevisor-sdk/.flattened-pom.xml featurevisor-openfeature/.flattened-pom.xml featurevisor-schemas/.flattened-pom.xml; do if ! grep -Fq "$version" "$pom"; then echo "Published POM does not match revision $version: $pom" >&2 exit 1 @@ -52,11 +68,13 @@ for artifact in \ "featurevisor-sdk/target/featurevisor-java-$version-sources.jar" \ "featurevisor-sdk/target/featurevisor-java-$version-javadoc.jar" \ "featurevisor-openfeature/target/featurevisor-openfeature-$version-sources.jar" \ - "featurevisor-openfeature/target/featurevisor-openfeature-$version-javadoc.jar"; do + "featurevisor-openfeature/target/featurevisor-openfeature-$version-javadoc.jar" \ + "featurevisor-schemas/target/featurevisor-schemas-$version-sources.jar" \ + "featurevisor-schemas/target/featurevisor-schemas-$version-javadoc.jar"; do if [[ ! -f "$artifact" ]]; then echo "Missing published artifact: $artifact" >&2 exit 1 fi done -echo "SDK and OpenFeature provider artifacts are isolated and complete." +echo "SDK, OpenFeature provider and schemas artifacts are isolated and complete." From 7cf55999f4a3ce5f1040a6db1b907d8dff75b5a7 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 22:17:09 +0100 Subject: [PATCH 02/21] fix: read $, \s and the dot in conditions as JavaScript does Without the m flag, $ now matches only at the end of a value, never before a final line break. \s and \S follow JavaScript's whitespace, with U+00A0 and U+FEFF and without U+0085, and without the s flag a dot refuses only JavaScript's line terminators. sdk-conditions.json pins each, and sdk-package-conditions.json now runs matchConditions with readers. --- conformance/sdk-conditions.json | 768 ++++++++++++++++++ conformance/sdk-package-conditions.json | 380 +++++++++ .../java/com/featurevisor/sdk/Conditions.java | 36 +- .../sdk/InstanceEvaluationDataProvider.java | 2 +- .../sdk/PackageConditionsConformanceTest.java | 74 ++ 5 files changed, 1257 insertions(+), 3 deletions(-) create mode 100644 conformance/sdk-package-conditions.json create mode 100644 featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java diff --git a/conformance/sdk-conditions.json b/conformance/sdk-conditions.json index 339a41b..f62fff4 100644 --- a/conformance/sdk-conditions.json +++ b/conformance/sdk-conditions.json @@ -10985,6 +10985,774 @@ "value": "matched" } } + }, + { + "name": "matches: $ matches at the end", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^[A-Z]{2}$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "DE" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: $ is the end only, never before a final line break", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^[A-Z]{2}$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "DE\n" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^[A-Z]{2}$" + } + } + }, + { + "name": "matches: ^ is the start only, never after a line break", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\d{5}$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "abc\n12345" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\d{5}$" + } + } + }, + { + "name": "matches: with the m flag ^ and $ match at every line", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\d{5}$", + "regexFlags": "m" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "abc\n12345" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: \\s matches a no-break space and the byte order mark", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^a\\sb\\sc$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "a\u00a0b\ufeffc" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: \\s does not match U+0085 or U+001C", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "\\s" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "a\u0085\u001cb" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "\\s" + } + } + }, + { + "name": "matches: \\S does not match a no-break space", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\S$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\u00a0" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^\\S$" + } + } + }, + { + "name": "matches: a dot matches U+0085 and a vertical tab", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^..$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\u0085\u000b" + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "matches: a dot does not match a line separator", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\u2028" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + { + "name": "matches: a dot does not match a carriage return", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "code": "\r" + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "code", + "operator": "matches", + "value": "^.$" + } + } + }, + { + "name": "equals: integers above 2^53 compare as doubles", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "id", + "operator": "equals", + "value": 9007199254740993 + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "id": 9007199254740992 + }, + "expected": { + "enabled": true, + "reason": "rule" + } + }, + { + "name": "greaterThan: integers above 2^53 compare as doubles", + "type": "flag", + "feature": "subject", + "datafile": { + "schemaVersion": "4", + "revision": "conditions-conformance", + "segments": { + "dutch": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + } + }, + "features": { + "gate": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "subject": { + "bucketBy": "userId", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ], + "conditions": { + "attribute": "id", + "operator": "greaterThan", + "value": 9007199254740992 + } + } + }, + "variables": { + "policy": { + "type": "object", + "defaultValue": { + "enabled": true + } + } + } + }, + "context": { + "userId": "conditions-user", + "id": 9007199254740993 + }, + "expected": { + "enabled": false, + "reason": "conditions_unmet", + "conditions": { + "attribute": "id", + "operator": "greaterThan", + "value": 9007199254740992 + } + } } ] } diff --git a/conformance/sdk-package-conditions.json b/conformance/sdk-package-conditions.json new file mode 100644 index 0000000..127a87a --- /dev/null +++ b/conformance/sdk-package-conditions.json @@ -0,0 +1,380 @@ +{ + "kind": "featurevisor.sdk-package-conditions", + "schemaVersion": 1, + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "dutch": { + "hash": "d1", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ] + }, + "payingDutch": { + "hash": "p1", + "conditions": { + "and": [ + "dutch", + { + "feature": "paid" + } + ] + } + } + }, + "features": { + "paid": { + "hash": "f1", + "bucketBy": "userId", + "traffic": [ + { + "key": "everyone", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": {} + }, + "context": { + "country": "nl" + }, + "cases": [ + { + "name": "a wildcard matches", + "conditions": "*", + "expected": true + }, + { + "name": "an attribute leaf reads the instance's context", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ], + "expected": true + }, + { + "name": "a call's context is merged over the instance's", + "conditions": "dutch", + "context": { + "country": "de" + }, + "expected": false + }, + { + "name": "a segment reads a feature through the instance", + "conditions": "payingDutch", + "expected": true + }, + { + "name": "a feature leaf is evaluated", + "conditions": { + "not": [ + { + "feature": "paid" + } + ] + }, + "expected": false + }, + { + "name": "conditions can be JSON text", + "conditions": "[\"dutch\"]", + "expected": true + }, + { + "name": "an input leaf reads through the reader beside a segment", + "conditions": { + "and": [ + "dutch", + { + "input": "accountType", + "operator": "equals", + "value": "business" + } + ] + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": true + }, + { + "name": "valueFrom compares two reads that agree", + "conditions": { + "input": "confirm", + "operator": "equals", + "valueFrom": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": true + }, + { + "name": "valueFrom compares two reads that differ", + "conditions": { + "input": "confirm", + "operator": "equals", + "valueFrom": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "b" + }, + "expected": false + }, + { + "name": "value is always a value, even an object naming a reader", + "conditions": { + "input": "confirm", + "operator": "equals", + "value": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": false + }, + { + "name": "a pattern read from a value never runs", + "conditions": { + "input": "confirm", + "operator": "matches", + "valueFrom": { + "input": "password" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": false + }, + { + "name": "a source no reader answers does not match", + "conditions": { + "input": "confirm", + "operator": "equals", + "valueFrom": { + "attribute": "country" + } + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": false + }, + { + "name": "without a reader for its kind, a leaf does not match", + "conditions": { + "input": "accountType", + "operator": "equals", + "value": "business" + }, + "expected": false + }, + { + "name": "an absent read does not exist", + "conditions": { + "input": "missing", + "operator": "notExists" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "an absent read is not null", + "conditions": { + "input": "missing", + "operator": "isNull" + }, + "input": { + "nothing": null + }, + "expected": false + }, + { + "name": "a null read is null", + "conditions": { + "input": "nothing", + "operator": "isNull" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "a null read exists", + "conditions": { + "input": "nothing", + "operator": "exists" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "without a value to compare, an absent read equals", + "conditions": { + "input": "missing", + "operator": "equals" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "without a value to compare, a null read does not equal", + "conditions": { + "input": "nothing", + "operator": "equals" + }, + "input": { + "nothing": null + }, + "expected": false + }, + { + "name": "without a value to compare, a null read is not equal", + "conditions": { + "input": "nothing", + "operator": "notEquals" + }, + "input": { + "nothing": null + }, + "expected": true + }, + { + "name": "an absent valueFrom does not equal a null read", + "conditions": { + "input": "nothing", + "operator": "equals", + "valueFrom": { + "input": "missing" + } + }, + "input": { + "nothing": null + }, + "expected": false + }, + { + "name": "valueFrom compares numbers", + "conditions": { + "input": "guests", + "operator": "greaterThan", + "valueFrom": { + "input": "rooms" + } + }, + "input": { + "guests": 3, + "rooms": 2 + }, + "expected": true + }, + { + "name": "valueFrom compares timestamps", + "conditions": { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + }, + "input": { + "checkIn": "2026-12-01T14:00:00Z", + "checkOut": "2026-12-02T10:00:00Z" + }, + "expected": true + }, + { + "name": "a text that is not a timestamp is never after one", + "conditions": { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + }, + "input": { + "checkIn": "2026-12-01T14:00:00Z", + "checkOut": "tomorrow" + }, + "expected": false + }, + { + "name": "reads above 2^53 compare as doubles", + "conditions": { + "input": "first", + "operator": "equals", + "valueFrom": { + "input": "second" + } + }, + "input": { + "first": 9007199254740993, + "second": 9007199254740992 + }, + "expected": true + }, + { + "name": "an input leaf in a group with an attribute leaf", + "conditions": { + "or": [ + { + "attribute": "country", + "operator": "equals", + "value": "de" + }, + { + "input": "accountType", + "operator": "in", + "value": [ + "business", + "charity" + ] + } + ] + }, + "input": { + "accountType": "business", + "password": "a", + "confirm": "a" + }, + "expected": true + } + ] +} diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java index c2716fc..776360e 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Conditions.java @@ -18,7 +18,26 @@ public class Conditions { private static final Instant MIN_PORTABLE_DATE = Instant.parse("0001-01-01T00:00:00Z"); private static final Instant MAX_PORTABLE_DATE_EXCLUSIVE = Instant.parse("+10000-01-01T00:00:00Z"); + /** JavaScript's whitespace and line terminators, for {@code \s}. */ + private static final String SPACES = "\\t\\n\\x0B\\f\\r \\x{A0}\\x{1680}\\x{2000}-\\x{200A}\\x{2028}\\x{2029}\\x{202F}\\x{205F}\\x{3000}\\x{FEFF}"; + /** Everything else, for {@code \S} inside a class. */ + private static final String NOT_SPACES = "\\x{0}-\\x{8}\\x{E}-\\x{1F}\\x{21}-\\x{9F}\\x{A1}-\\x{167F}\\x{1681}-\\x{1FFF}" + + "\\x{200B}-\\x{2027}\\x{202A}-\\x{202E}\\x{2030}-\\x{205E}\\x{2060}-\\x{2FFF}\\x{3001}-\\x{FEFE}\\x{FF00}-\\x{10FFFF}"; + static String normalizePortableRegex(String pattern) { + return normalizePortableRegex(pattern, ""); + } + + /** + * A portable pattern in Java's syntax, meaning what it means in JavaScript + * with the same flags: {@code \d} and {@code \w} are ASCII, {@code \s} is + * JavaScript's whitespace, {@code .} refuses only JavaScript's line + * terminators, and without {@code m} a {@code $} matches at the very end, + * never before a final line break as Java's does. + */ + static String normalizePortableRegex(String pattern, String flags) { + boolean multiline = flags.indexOf('m') != -1; + boolean dotAll = flags.indexOf('s') != -1; StringBuilder output = new StringBuilder(); boolean inClass = false; for (int index = 0; index < pattern.length(); index++) { @@ -31,14 +50,27 @@ static String normalizePortableRegex(String pattern) { case 'D': replacement = inClass ? "\\x{0}-\\x{2F}\\x{3A}-\\x{10FFFF}" : "[^0-9]"; break; case 'w': replacement = inClass ? "A-Za-z0-9_" : "(?-i:[A-Za-z0-9_])"; break; case 'W': replacement = inClass ? "\\x{0}-\\x{2F}\\x{3A}-\\x{40}\\x{5B}-\\x{5E}\\x{60}\\x{7B}-\\x{10FFFF}" : "(?-i:[^A-Za-z0-9_])"; break; + case 's': replacement = inClass ? SPACES : "[" + SPACES + "]"; break; + case 'S': replacement = inClass ? NOT_SPACES : "[^" + SPACES + "]"; break; default: break; } if (replacement == null) output.append('\\').append(code); else output.append(replacement); continue; } - if (current == '[' && !inClass) inClass = true; - else if (current == ']' && inClass) inClass = false; + if (inClass) { + if (current == ']') inClass = false; + output.append(current); + continue; + } + if (current == '[') inClass = true; + else if (current == '$' && !multiline) { + output.append("\\z"); + continue; + } else if (current == '.' && !dotAll) { + output.append("[^\\n\\r\\x{2028}\\x{2029}]"); + continue; + } output.append(current); } return output.toString(); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java index 4ffded4..c75d454 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/InstanceEvaluationDataProvider.java @@ -238,7 +238,7 @@ public Pattern getRegex(String regexString, String regexFlags) { } try { - Pattern regex = Pattern.compile(Conditions.normalizePortableRegex(regexString), getPatternFlags(flags)); + Pattern regex = Pattern.compile(Conditions.normalizePortableRegex(regexString, flags), getPatternFlags(flags)); regexCache.put(cacheKey, regex); return regex; } catch (IllegalArgumentException e) { diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java new file mode 100644 index 0000000..8b9fbba --- /dev/null +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java @@ -0,0 +1,74 @@ +package com.featurevisor.sdk; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Stream; +import org.junit.jupiter.api.DynamicTest; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestFactory; + +/** Runs conformance/sdk-package-conditions.json: matchConditions with readers, as packages call it. */ +class PackageConditionsConformanceTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private JsonNode fixture() throws Exception { + try (InputStream stream = getClass().getResourceAsStream("/conformance/sdk-package-conditions.json")) { + return JSON.readTree(stream); + } + } + + @Test + void isTheVersionThisRunnerKnows() throws Exception { + JsonNode fixture = fixture(); + assertEquals("featurevisor.sdk-package-conditions", fixture.get("kind").asText()); + assertEquals(1, fixture.get("schemaVersion").asInt()); + assertTrue(fixture.get("cases").size() > 0); + } + + @TestFactory + @SuppressWarnings("unchecked") + Stream cases() throws Exception { + JsonNode fixture = fixture(); + String datafile = JSON.writeValueAsString(fixture.get("datafile")); + Map instanceContext = JSON.convertValue(fixture.get("context"), Map.class); + List tests = new ArrayList<>(); + for (JsonNode testCase : fixture.get("cases")) { + tests.add(DynamicTest.dynamicTest(testCase.get("name").asText(), () -> { + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile) + .context(instanceContext) + .logLevel(FeaturevisorLogLevel.FATAL)); + AtomicReference api = new AtomicReference<>(); + f.addModule(new FeaturevisorModule("package").setup(api::set)); + Object conditions = JSON.convertValue(testCase.get("conditions"), Object.class); + Map context = testCase.has("context") + ? JSON.convertValue(testCase.get("context"), Map.class) + : Map.of(); + boolean expected = testCase.get("expected").asBoolean(); + // Twice, so a cached answer is the answer. + for (int attempt = 0; attempt < 2; attempt++) { + boolean matched; + if (testCase.has("input")) { + Map input = JSON.convertValue(testCase.get("input"), Map.class); + // An absent key reads as nothing, which differs from null. + MatchConditionsOptions readers = new MatchConditionsOptions() + .reader("input", path -> input.containsKey(path) ? input.get(path) : ConditionReader.ABSENT); + matched = api.get().matchConditions(conditions, context, readers); + } else { + matched = api.get().matchConditions(conditions, context); + } + assertEquals(expected, matched, testCase.get("name").asText()); + } + })); + } + return tests.stream(); + } +} From c438d3b55102f366139445010cc600d5d51256ba Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 22:17:09 +0100 Subject: [PATCH 03/21] feat(schemas): read patterns with the u flag and fail closed as JavaScript does Patterns now mean what JavaScript means with the u flag, so what u rejects, such as an escape without a meaning or a lone brace, fails every value. A mutation that cannot be applied fails the value with refineError and one schema_mutation_error diagnostic instead of throwing, and views keep such a node as it is. format holds issue entries back, and additionalProperties other than true or a schema takes no extra key. The conformance runner checks diagnostics, and the differential test reads the shared schemas-datafile.json. --- README.md | 4 + .../schemas-datafile.json | 191 ++ conformance/schemas-validation.json | 1552 +++++++++++++++++ .../java/com/featurevisor/schemas/Engine.java | 38 +- .../com/featurevisor/schemas/Patterns.java | 116 +- .../com/featurevisor/schemas/Resolver.java | 3 + .../java/com/featurevisor/schemas/Store.java | 13 + .../java/com/featurevisor/schemas/Views.java | 11 +- .../schemas/BuiltDatafileTest.java | 25 +- .../schemas/SchemasConformanceTest.java | 14 +- .../com/featurevisor/schemas/SchemasTest.java | 8 +- .../src/test/resources/built-datafile.json | 1 - 12 files changed, 1929 insertions(+), 47 deletions(-) rename featurevisor-schemas/src/test/resources/built-datafile-expected.json => conformance/schemas-datafile.json (69%) delete mode 100644 featurevisor-schemas/src/test/resources/built-datafile.json diff --git a/README.md b/README.md index f98ca59..dae13f9 100644 --- a/README.md +++ b/README.md @@ -1043,6 +1043,10 @@ SchemaHandle signUp = schemas.get("signUp", new HandleOptions() Handles are safe to share between threads. `close()` on the instance stops its subscriptions and removes its module from the Featurevisor instance. +### Patterns + +Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. + ## CLI usage Compile the CLI module from this SDK repository: diff --git a/featurevisor-schemas/src/test/resources/built-datafile-expected.json b/conformance/schemas-datafile.json similarity index 69% rename from featurevisor-schemas/src/test/resources/built-datafile-expected.json rename to conformance/schemas-datafile.json index 80f4847..1cd37f0 100644 --- a/featurevisor-schemas/src/test/resources/built-datafile-expected.json +++ b/conformance/schemas-datafile.json @@ -1,4 +1,195 @@ { + "kind": "featurevisor.schemas-datafile", + "schemaVersion": 1, + "datafile": { + "schemaVersion": "4", + "featurevisorVersion": "4.13.0", + "revision": "lKLik9RrAm", + "segments": { + "netherlands": { + "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" + }, + "paying": { + "conditions": "{\"attribute\":\"plan\",\"operator\":\"equals\",\"value\":\"paid\"}" + } + }, + "features": {}, + "variables": {}, + "schemas": { + "checkout": { + "hash": "gSboXrZWcM", + "type": "object", + "properties": { + "billingCountry": { + "type": "string" + }, + "shippingCountry": { + "type": "string" + }, + "customsDescription": { + "type": "string" + }, + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "billingCountry" + ], + "mutations": [ + { + "key": "shipsAbroad", + "conditions": "[{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}},\"paying\"]", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "customsDescription" + } + ] + } + ] + }, + "register": { + "hash": "XlDf9sip1o", + "type": "object", + "properties": { + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string", + "annotations": { + "title": "Confirmation" + } + }, + "shippingCountry": { + "type": "string" + }, + "billingCountry": { + "type": "string" + } + }, + "required": [ + "password" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": "{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}", + "path": "confirmPassword", + "message": "{title} does not match the password" + }, + { + "key": "dutchShippingCountry", + "conditions": "[\"netherlands\",{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}}]", + "path": "shippingCountry", + "message": "We ship Dutch orders to the billing country only" + } + ] + }, + "signUp": { + "hash": "wLXjboTQnZ", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ], + "annotations": { + "title": "Account type", + "options": { + "personal": { + "title": "Personal" + }, + "business": { + "title": "Business" + } + } + } + }, + "displayName": { + "type": "string", + "minLength": 2, + "maxLength": 40, + "annotations": { + "title": "Display name", + "examples": [ + "Ada", + "Grace Hopper" + ] + } + }, + "taxId": { + "type": "string", + "annotations": { + "title": "VAT number" + } + } + }, + "required": [ + "accountType", + "displayName" + ], + "messages": { + "displayName": { + "minLength": "Use at least {minLength} characters" + } + }, + "annotations": { + "title": "Create your account", + "order": [ + "accountType", + "displayName", + "taxId" + ] + }, + "mutations": [ + { + "key": "business", + "conditions": "{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + }, + { + "op": "set", + "path": [ + "properties", + "taxId", + "pattern" + ], + "value": "^[A-Z]{2}[0-9]{9}$" + }, + { + "op": "set", + "path": [ + "properties", + "taxId", + "messages" + ], + "value": { + "pattern": "Enter your VAT number, such as DE123456789" + } + } + ] + } + ] + } + } + }, "cases": [ { "schema": "signUp", diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index d1d6b64..e5f79a7 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -2593,6 +2593,1558 @@ } } ] + }, + { + "name": "a format issue holds every issue entry back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "checkIn": { + "type": "string", + "format": "date-time" + }, + "checkOut": { + "type": "string", + "format": "date-time" + } + }, + "issues": [ + { + "key": "checkOutAfterCheckIn", + "conditions": [ + { + "not": [ + { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + } + ] + } + ], + "path": "checkOut", + "message": "Check out after check in" + } + ] + } + }, + "schema": "subject", + "value": { + "checkIn": "2026-12-01T14:00:00Z", + "checkOut": "tomorrow" + }, + "issues": [ + { + "code": "format", + "path": [ + "checkOut" + ], + "params": { + "format": "date-time" + } + } + ] + }, + { + "name": "an issue entry compares valid timestamps", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "checkIn": { + "type": "string", + "format": "date-time" + }, + "checkOut": { + "type": "string", + "format": "date-time" + } + }, + "issues": [ + { + "key": "checkOutAfterCheckIn", + "conditions": [ + { + "not": [ + { + "input": "checkOut", + "operator": "after", + "valueFrom": { + "input": "checkIn" + } + } + ] + } + ], + "path": "checkOut", + "message": "Check out after check in" + } + ] + } + }, + "schema": "subject", + "value": { + "checkIn": "2026-12-02T10:00:00Z", + "checkOut": "2026-12-01T10:00:00Z" + }, + "issues": [ + { + "code": "refine", + "path": [ + "checkOut" + ], + "params": { + "refine": "checkOutAfterCheckIn" + } + } + ] + }, + { + "name": "-0 equals 0 in const", + "schemas": { + "subject": { + "hash": "subject-1", + "const": 0 + } + }, + "schema": "subject", + "value": -0, + "issues": [] + }, + { + "name": "0 equals -0 in enum", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + -0 + ] + } + }, + "schema": "subject", + "value": 0, + "issues": [] + }, + { + "name": "uniqueItems counts -0 and 0 as one value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "number" + }, + "uniqueItems": true + } + }, + "schema": "subject", + "value": [ + 0, + -0 + ], + "issues": [ + { + "code": "uniqueItems", + "path": [], + "params": { + "index": 1 + } + } + ] + }, + { + "name": "a boolean never equals a number in const", + "schemas": { + "subject": { + "hash": "subject-1", + "const": 0 + } + }, + "schema": "subject", + "value": false, + "issues": [ + { + "code": "const", + "path": [], + "params": { + "const": 0 + } + } + ] + }, + { + "name": "a boolean never equals a number in enum", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 1, + "a" + ] + } + }, + "schema": "subject", + "value": true, + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + 1, + "a" + ] + } + } + ] + }, + { + "name": "integers above 2^53 compare as doubles in const", + "schemas": { + "subject": { + "hash": "subject-1", + "const": 9007199254740993 + } + }, + "schema": "subject", + "value": 9007199254740992, + "issues": [] + }, + { + "name": "integers above 2^53 compare as doubles in enum", + "schemas": { + "subject": { + "hash": "subject-1", + "enum": [ + 9007199254740993 + ] + } + }, + "schema": "subject", + "value": 9007199254740992, + "issues": [] + }, + { + "name": "integers above 2^53 compare as doubles in maximum", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "integer", + "maximum": 9007199254740992 + } + }, + "schema": "subject", + "value": 9007199254740993, + "issues": [] + }, + { + "name": "a dot takes an emoji as one character", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.$" + } + }, + "schema": "subject", + "value": "😀", + "issues": [] + }, + { + "name": "a negated class takes an emoji as one character", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[^a]$" + } + }, + "schema": "subject", + "value": "😀", + "issues": [] + }, + { + "name": "a pattern counts an emoji as one character, as lengths do", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.{2}$" + } + }, + "schema": "subject", + "value": "😀", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^.{2}$" + } + } + ] + }, + { + "name": "$ matches at the end only, never before a final line break", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[A-Z]{2}$" + } + }, + "schema": "subject", + "value": "DE\n", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^[A-Z]{2}$" + } + } + ] + }, + { + "name": "^ matches at the start only, never after a line break", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^a" + } + }, + "schema": "subject", + "value": "b\na", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^a" + } + } + ] + }, + { + "name": "\\s matches a no-break space and the byte order mark", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\s\\s$" + } + }, + "schema": "subject", + "value": "\u00a0\ufeff", + "issues": [] + }, + { + "name": "\\s matches a vertical tab, a line separator and an ideographic space", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\s{3}$" + } + }, + "schema": "subject", + "value": "\u000b\u2028\u3000", + "issues": [] + }, + { + "name": "\\s does not match U+0085 or U+001C", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "\\s" + } + }, + "schema": "subject", + "value": "a\u0085\u001cb", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "\\s" + } + } + ] + }, + { + "name": "\\S does not match a no-break space", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\S$" + } + }, + "schema": "subject", + "value": "\u00a0", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\S$" + } + } + ] + }, + { + "name": "a dot matches U+0085 and a vertical tab", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^..$" + } + }, + "schema": "subject", + "value": "\u0085\u000b", + "issues": [] + }, + { + "name": "a dot does not match a line separator", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.$" + } + }, + "schema": "subject", + "value": "\u2028", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^.$" + } + } + ] + }, + { + "name": "a dot does not match a carriage return", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^.$" + } + }, + "schema": "subject", + "value": "\r", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^.$" + } + } + ] + }, + { + "name": "\\d is ASCII", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\d$" + } + }, + "schema": "subject", + "value": "\u0663", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\d$" + } + } + ] + }, + { + "name": "\\w is ASCII", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\w$" + } + }, + "schema": "subject", + "value": "é", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\w$" + } + } + ] + }, + { + "name": "an escaped slash is a slash", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\/$" + } + }, + "schema": "subject", + "value": "/", + "issues": [] + }, + { + "name": "an escaped hyphen inside a class is a hyphen", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^[a\\-]$" + } + }, + "schema": "subject", + "value": "-", + "issues": [] + }, + { + "name": "a pattern that does not compile fails every value", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "(" + } + }, + "schema": "subject", + "value": "(", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "(" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "a lone brace does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "a{" + } + }, + "schema": "subject", + "value": "a{", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "a{" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "a lone closing bracket does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "a]" + } + }, + "schema": "subject", + "value": "a]", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "a]" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "an escaped hyphen outside a class does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\-$" + } + }, + "schema": "subject", + "value": "-", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\-$" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "an escaped letter without a meaning does not compile with u", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "pattern": "^\\a$" + } + }, + "schema": "subject", + "value": "a", + "issues": [ + { + "code": "pattern", + "path": [], + "params": { + "pattern": "^\\a$" + } + } + ], + "diagnostics": [ + "schema_pattern_unsupported" + ] + }, + { + "name": "a mutation with an unknown operation fails the value closed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "mutations": [ + { + "key": "broken", + "conditions": "*", + "operations": [ + { + "op": "explode", + "path": [ + "properties", + "name", + "minLength" + ], + "value": 1 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "name": "Ada" + }, + "issues": [ + { + "code": "refineError", + "path": [], + "params": {} + } + ], + "diagnostics": [ + "schema_mutation_error" + ] + }, + { + "name": "a mutation through an unsafe key fails the value closed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string" + } + }, + "mutations": [ + { + "key": "broken", + "conditions": "*", + "operations": [ + { + "op": "set", + "path": [ + "properties", + "constructor", + "maxLength" + ], + "value": 1 + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "name": "Ada" + }, + "issues": [ + { + "code": "refineError", + "path": [], + "params": {} + } + ], + "diagnostics": [ + "schema_mutation_error" + ] + }, + { + "name": "additionalProperties false takes no key beyond properties", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "a": { + "type": "string" + } + }, + "additionalProperties": false + } + }, + "schema": "subject", + "value": { + "a": "x", + "b": 1 + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "additionalProperties false without properties takes no key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": false + } + }, + "schema": "subject", + "value": { + "b": "x" + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "additionalProperties other than true or a schema takes no extra key", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": null + } + }, + "schema": "subject", + "value": { + "b": "x" + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "b" + ], + "params": { + "key": "b" + } + } + ] + }, + { + "name": "a schema that references itself reads deeper into the value each time", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + } + }, + "schema": "subject", + "value": [ + "a", + [ + "b", + [ + "c" + ] + ] + ], + "issues": [] + }, + { + "name": "a schema that references itself reports the item that fails", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + } + }, + "schema": "subject", + "value": [ + "a", + [ + 1 + ] + ], + "issues": [ + { + "code": "oneOf", + "path": [ + 1, + 0 + ], + "params": { + "matches": 0 + } + } + ] + }, + { + "name": "a reference loop fails closed at 128 references", + "schemas": { + "subject": { + "hash": "subject-1", + "schema": "other" + }, + "other": { + "hash": "other-1", + "schema": "subject" + } + }, + "schema": "subject", + "value": "x", + "issues": [ + { + "code": "refineError", + "path": [], + "params": {} + } + ], + "diagnostics": [ + "schema_reference_depth" + ] + }, + { + "name": "a schema that references itself at the same value fails closed at 128 references", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + }, + "schema": "subject", + "value": 1, + "issues": [ + { + "code": "oneOf", + "path": [], + "params": { + "matches": 0 + } + } + ], + "diagnostics": [ + "schema_reference_depth" + ] + }, + { + "name": "references at the same value count to exactly 128", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "schema": "subject" + }, + { + "type": "string" + } + ] + } + }, + "schema": "subject", + "value": "a", + "issues": [], + "diagnostics": [ + "schema_reference_depth" + ] + }, + { + "name": "a mutation's conditions can be JSON text", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": "[{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}]", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "schema": "subject", + "value": { + "accountType": "business" + }, + "issues": [ + { + "code": "required", + "path": [ + "taxId" + ], + "params": { + "key": "taxId" + }, + "mutation": "business" + } + ] + }, + { + "name": "an issue entry's conditions can be JSON text", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "password": { + "type": "string" + }, + "confirmPassword": { + "type": "string" + } + }, + "issues": [ + { + "key": "passwordsDiffer", + "conditions": "[{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}]", + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "password": "lovelace", + "confirmPassword": "lovelaced" + }, + "issues": [ + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "JSON text conditions read segments and the context", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "accountType": { + "type": "string", + "enum": [ + "personal", + "business" + ] + }, + "taxId": { + "type": "string" + } + }, + "required": [ + "accountType" + ], + "mutations": [ + { + "key": "business", + "conditions": "{\"and\":[\"dutch\",{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}]}", + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "taxId" + } + ] + } + ] + } + }, + "segments": { + "dutch": { + "hash": "dutch-1", + "conditions": [ + { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + ] + } + }, + "context": { + "country": "nl" + }, + "schema": "subject", + "value": { + "accountType": "business" + }, + "issues": [ + { + "code": "required", + "path": [ + "taxId" + ], + "params": { + "key": "taxId" + }, + "mutation": "business" + } + ] + }, + { + "name": "a missing field's title is in its issue's params", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "annotations": { + "title": "Name" + } + } + }, + "required": [ + "name" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [ + { + "code": "required", + "path": [ + "name" + ], + "params": { + "key": "name", + "title": "Name" + } + } + ] + }, + { + "name": "a field's title is in its issue's params", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "name": { + "type": "string", + "annotations": { + "title": "Name" + }, + "minLength": 3 + } + }, + "required": [ + "name" + ] + } + }, + "schema": "subject", + "value": { + "name": "A" + }, + "issues": [ + { + "code": "minLength", + "path": [ + "name" + ], + "params": { + "minLength": 3, + "length": 1, + "title": "Name" + } + } + ] + }, + { + "name": "an enum gives its choices' titles when every choice has one", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "enum": [ + "a", + "b" + ], + "annotations": { + "options": { + "a": { + "title": "A" + }, + "b": { + "title": "B" + } + } + } + } + }, + "schema": "subject", + "value": "c", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "a", + "b" + ], + "titles": [ + "A", + "B" + ] + } + } + ] + }, + { + "name": "a oneOf of consts gives its branches' titles", + "schemas": { + "subject": { + "hash": "subject-1", + "oneOf": [ + { + "const": "a", + "annotations": { + "title": "A" + } + }, + { + "const": "b", + "annotations": { + "title": "B" + } + } + ] + } + }, + "schema": "subject", + "value": "c", + "issues": [ + { + "code": "enum", + "path": [], + "params": { + "options": [ + "a", + "b" + ], + "titles": [ + "A", + "B" + ] + } + } + ] + }, + { + "name": "a reference's own title wins over the referenced schema's", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "city": { + "schema": "city", + "annotations": { + "title": "Town" + } + } + } + }, + "city": { + "hash": "city-1", + "type": "string", + "minLength": 2, + "annotations": { + "title": "City" + } + } + }, + "schema": "subject", + "value": { + "city": "A" + }, + "issues": [ + { + "code": "minLength", + "path": [ + "city" + ], + "params": { + "minLength": 2, + "length": 1, + "title": "Town" + } + } + ] + }, + { + "name": "rules beside a reference are ignored", + "schemas": { + "subject": { + "hash": "subject-1", + "schema": "text", + "minLength": 100 + }, + "text": { + "hash": "text-1", + "type": "string" + } + }, + "schema": "subject", + "value": "x", + "issues": [] + }, + { + "name": "a type beside oneOf is ignored", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "number", + "oneOf": [ + { + "type": "string" + }, + { + "type": "boolean" + } + ] + } + }, + "schema": "subject", + "value": "x", + "issues": [] + }, + { + "name": "required without properties is ignored", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "required": [ + "a" + ] + } + }, + "schema": "subject", + "value": {}, + "issues": [] + }, + { + "name": "const skips the typed rules", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "const": "a", + "minLength": 5 + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "enum skips the typed rules", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "enum": [ + "a" + ], + "pattern": "^b" + } + }, + "schema": "subject", + "value": "a", + "issues": [] + }, + { + "name": "a node without a type skips the rules of other kinds", + "schemas": { + "subject": { + "hash": "subject-1", + "minLength": 3 + } + }, + "schema": "subject", + "value": 5, + "issues": [] + }, + { + "name": "a node without a type applies the rules of the value's kind", + "schemas": { + "subject": { + "hash": "subject-1", + "minLength": 3 + } + }, + "schema": "subject", + "value": "ab", + "issues": [ + { + "code": "minLength", + "path": [], + "params": { + "minLength": 3, + "length": 2 + } + } + ] + }, + { + "name": "a mutation under items reads each item", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string" + }, + "code": { + "type": "string" + } + }, + "required": [ + "kind" + ], + "mutations": [ + { + "key": "coded", + "conditions": [ + { + "input": "kind", + "operator": "equals", + "value": "coded" + } + ], + "operations": [ + { + "op": "appendUnique", + "path": [ + "required" + ], + "value": "code" + } + ] + } + ] + } + } + }, + "schema": "subject", + "value": [ + { + "kind": "plain" + }, + { + "kind": "coded" + } + ], + "issues": [ + { + "code": "required", + "path": [ + 1, + "code" + ], + "params": { + "key": "code" + }, + "mutation": "coded" + } + ] + }, + { + "name": "a mutation can change a node's type", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "string", + "mutations": [ + { + "key": "numeric", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "paid" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "type" + ], + "value": "number" + } + ] + } + ] + } + }, + "context": { + "plan": "paid" + }, + "schema": "subject", + "value": "x", + "issues": [ + { + "code": "type", + "path": [], + "params": { + "type": "number", + "received": "string" + }, + "mutation": "numeric" + } + ] } ] } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java index 66b1b71..79fd7de 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java @@ -20,7 +20,9 @@ private Engine() {} /** Issues after which an object's {@code issues} could not trust the values they compare. */ private static final Set SHAPE_CODES = new HashSet<>(Arrays.asList( - "type", "required", "enum", "const", "additionalProperties", "oneOf", "schemaNotFound")); + "type", "required", "enum", "const", "additionalProperties", "oneOf", "schemaNotFound", + // The operators that read timestamps and versions cannot compare a value that is neither. + "format")); static void report(Run run, Position at, String code, Map params) { report(run, at, code, params, at.path, at, null); @@ -351,7 +353,9 @@ private static Validator compileObject(Map node, Resolver resolv } boolean hasAdditional = node.containsKey("additionalProperties"); Object additional = node.get("additionalProperties"); - Validator compiledAdditional = hasAdditional && !Boolean.TRUE.equals(additional) ? compileNode(additional, resolve) : null; + Validator compiledAdditional = additional instanceof Map ? compileNode(additional, resolve) : null; + // Anything but `true` or a schema, `false` included, takes no key beyond `properties`. + boolean closed = hasAdditional && !Boolean.TRUE.equals(additional) && compiledAdditional == null; return (value, run, at) -> { Map object = (Map) value; @@ -378,7 +382,7 @@ private static Validator compileObject(Map node, Resolver resolv continue; } else if (compiledAdditional != null) { compiledAdditional.validate(child, run, new Position(append(at.path, key), append(at.mpath, "*"), at.scopes, null)); - } else if (properties != null) { + } else if (properties != null || closed) { // An extra key has no field of its own, so the object that rejects it words its issue, without a title. report(run, at, "additionalProperties", params("key", key), append(at.path, key), untitled(at), null); } else if (!Json.isPrimitive(child)) { @@ -612,11 +616,21 @@ private static final class Variant { final Validator validate; final Map rules; final List matched; + /** Why the mutations cannot be applied, when they cannot. */ + final RuntimeException failure; Variant(Validator validate, Map rules, List matched) { this.validate = validate; this.rules = rules; this.matched = matched; + this.failure = null; + } + + Variant(RuntimeException failure) { + this.validate = null; + this.rules = null; + this.matched = List.of(); + this.failure = failure; } } @@ -633,12 +647,22 @@ private static Validator compileMutations(Map node, Resolver res String id = matchingMutations(node, value, run.sources.info.getContext(), resolve, run.schema); Variant variant = variants.get(id); if (variant == null) { - Map rules = mutatedRules(node, id, resolve); - List matched = new ArrayList<>(); - for (String index : id.split(",")) if (!index.isEmpty()) matched.add(Integer.parseInt(index)); - variant = new Variant(compileNode(rules, resolve), rules, matched); + try { + Map rules = mutatedRules(node, id, resolve); + List matched = new ArrayList<>(); + for (String index : id.split(",")) if (!index.isEmpty()) matched.add(Integer.parseInt(index)); + variant = new Variant(compileNode(rules, resolve), rules, matched); + } catch (RuntimeException failure) { + variant = new Variant(failure); + } variants.put(id, variant); } + if (variant.validate == null) { + // Operations the SDK refuses fail closed: no value can be shown to meet rules nobody can read. + resolve.mutationFailed(run.schema, variant.failure); + report(run, at, "refineError", new LinkedHashMap<>()); + return; + } int start = run.issues.size(); variant.validate.validate(value, run, at); if (variant.matched.isEmpty()) return; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java index 120daa3..0b1297b 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java @@ -5,14 +5,14 @@ import java.util.regex.Pattern; /** - * Schema patterns, written for JavaScript's {@code RegExp} without flags, - * compiled to mean the same in {@code java.util.regex}. Without the rewrites, - * Java's {@code $} matches before a final line break, its {@code \s} misses - * Unicode spaces, its {@code .} refuses U+0085, its {@code [} nests classes and - * its {@code {} fails where JavaScript reads a literal brace. - * - *

One difference stays: JavaScript without flags reads a string in UTF-16 - * units, so {@code ^.$} refuses an emoji there and accepts it here. + * Schema patterns, written for JavaScript's {@code RegExp} with the {@code u} + * flag, compiled to mean the same in {@code java.util.regex}. Both read code + * points, so {@code ^.$} takes an emoji in each. Without the rewrites, Java's + * {@code $} matches before a final line break, its {@code \s} misses Unicode + * spaces, its {@code .} refuses U+0085 and its {@code [} nests classes. What + * the {@code u} flag rejects, such as an escaped letter without a meaning or a + * lone brace, does not compile here either, so it fails every value as it + * does in JavaScript. */ final class Patterns { private Patterns() {} @@ -42,15 +42,48 @@ static Pattern compile(String source) { return cached == FAILED ? null : (Pattern) cached; } + /** Characters the {@code u} flag lets an escape name as themselves, besides {@code -} in a class. */ + private static final String SYNTAX = "^$\\.*+?()[]{}|/"; + + private static final int NO_ATOM = 0; + private static final int CHARACTER = 1; + private static final int CLASS_ESCAPE = 2; + + private static IllegalArgumentException unsupported(String what) { + return new IllegalArgumentException("Not a pattern with the u flag: " + what); + } + + private static boolean isHex(String source, int from, int count) { + if (from + count > source.length()) return false; + for (int index = from; index < from + count; index++) { + if (Character.digit(source.charAt(index), 16) == -1) return false; + } + return true; + } + /** JavaScript's pattern in Java's syntax. */ static String translate(String source) { StringBuilder out = new StringBuilder(); boolean inClass = false; + // The class's last item, which a dash can make the low end of a range, and whether one waits for its high end. + int lastAtom = NO_ATOM; + boolean rangePending = false; int length = source.length(); for (int index = 0; index < length; index++) { char current = source.charAt(index); - if (current == '\\' && index + 1 < length) { + if (current == '\\') { + if (index + 1 >= length) throw unsupported("a trailing backslash"); char code = source.charAt(++index); + boolean classEscape = "dDwWsS".indexOf(code) != -1; + if (inClass) { + int atom = classEscape ? CLASS_ESCAPE : CHARACTER; + if (rangePending) { + // `u` lets no class, such as `\d`, bound a range. + if (atom == CLASS_ESCAPE || lastAtom == CLASS_ESCAPE) throw unsupported("a range from a class"); + lastAtom = NO_ATOM; + rangePending = false; + } else lastAtom = atom; + } switch (code) { case 'd': out.append(inClass ? "0-9" : "[0-9]"); break; case 'D': out.append(inClass ? NOT_DIGITS : "[^0-9]"); break; @@ -60,28 +93,58 @@ static String translate(String source) { case 'S': out.append(inClass ? NOT_SPACES : "[^" + SPACES + "]"); break; case 'v': out.append("\\x0B"); break; case 'b': out.append(inClass ? "\\x08" : "\\b"); break; - case 'B': out.append(inClass ? "B" : "\\B"); break; + case 'B': + if (inClass) throw unsupported("\\B in a class"); + out.append("\\B"); + break; case 'n': case 'r': case 't': case 'f': out.append('\\').append(code); break; - case 'c': case 'x': case 'u': out.append('\\').append(code); break; + case 'c': + if (index + 1 >= length || !isAsciiLetter(source.charAt(index + 1))) throw unsupported("\\c"); + out.append("\\c").append(source.charAt(++index)); + break; + case 'x': + if (!isHex(source, index + 1, 2)) throw unsupported("\\x"); + out.append("\\x").append(source, index + 1, index + 3); + index += 2; + break; + case 'u': + if (isHex(source, index + 1, 4)) { + out.append("\\u").append(source, index + 1, index + 5); + index += 4; + } else if (index + 1 < length && source.charAt(index + 1) == '{') { + int end = source.indexOf('}', index + 2); + if (end == -1 || end == index + 2 || !isHex(source, index + 2, end - index - 2)) throw unsupported("\\u{}"); + out.append("\\x{").append(source, index + 2, end).append('}'); + index = end; + } else throw unsupported("\\u"); + break; case '0': - if (index + 1 < length && Character.isDigit(source.charAt(index + 1))) out.append("\\0"); - else out.append("\\x00"); + if (index + 1 < length && Character.isDigit(source.charAt(index + 1))) throw unsupported("\\0 before a digit"); + out.append("\\x00"); break; default: - if (Character.isDigit(code)) { + if (code >= '1' && code <= '9') { // A back reference, which lint refuses in delivered schemas. out.append('\\').append(code); - } else if (Character.isLetter(code)) { - // Without flags JavaScript reads an unknown escape, such as `\p`, as the letter. - out.append(code); - } else { + } else if (SYNTAX.indexOf(code) != -1 || (inClass && code == '-')) { out.append('\\').append(code); + } else { + // `u` rejects an escape without a meaning, such as `\a` or `\-` outside a class. + throw unsupported("\\" + code); } } continue; } if (inClass) { if (current == ']') inClass = false; + else if (current == '-' && lastAtom != NO_ATOM && !rangePending + && index + 1 < length && source.charAt(index + 1) != ']') { + rangePending = true; + } else if (rangePending) { + if (lastAtom == CLASS_ESCAPE) throw unsupported("a range from a class"); + lastAtom = NO_ATOM; + rangePending = false; + } else lastAtom = CHARACTER; // Java nests classes on `[` and intersects them on `&&`, where JavaScript reads the characters. if (current == '[' || current == '&') out.append('\\'); out.append(current); @@ -99,6 +162,8 @@ static String translate(String source) { index += 1; } else { inClass = true; + lastAtom = NO_ATOM; + rangePending = false; out.append('['); if (index + 1 < length && source.charAt(index + 1) == '^') { out.append('^'); @@ -110,20 +175,23 @@ static String translate(String source) { case '$': out.append("\\z"); break; case '{': { int end = quantifierEnd(source, index); - if (end == -1) out.append("\\{"); - else { - out.append(source, index, end + 1); - index = end; - } + if (end == -1) throw unsupported("a lone {"); + out.append(source, index, end + 1); + index = end; break; } - case '}': out.append("\\}"); break; + case '}': throw unsupported("a lone }"); + case ']': throw unsupported("a lone ]"); default: out.append(current); } } return out.toString(); } + private static boolean isAsciiLetter(char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); + } + /** Where a `{` that starts `{n}`, `{n,}` or `{n,m}` ends, which JavaScript reads as a quantifier, or -1. */ private static int quantifierEnd(String source, int start) { int index = start + 1; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java index 591e1a9..2e7d908 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java @@ -23,6 +23,9 @@ interface Resolver { /** Reports, once, a pattern Java cannot compile, which fails every value. */ void unsupportedPattern(String pattern); + /** Reports, once per schema, mutations whose operations cannot be applied, which fail the value. */ + void mutationFailed(String schema, RuntimeException error); + final class Resolved { final Map node; final Validator validate; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java index bad6db8..a257747 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java @@ -59,6 +59,7 @@ private static final class Identity { private final Set reported = ConcurrentHashMap.newKeySet(); private final Set reportedPatterns = ConcurrentHashMap.newKeySet(); private final Set reportedDepths = ConcurrentHashMap.newKeySet(); + private final Set reportedMutations = ConcurrentHashMap.newKeySet(); /** SDK instances whose schemas module holds the package's name, which only one module on an instance can. */ private static final Map NAMED = Collections.synchronizedMap(new WeakHashMap<>()); @@ -201,6 +202,18 @@ public void unsupportedPattern(String pattern) { .details(Map.of("pattern", pattern))); } + @Override + public void mutationFailed(String schema, RuntimeException error) { + if (!reportedMutations.add(schema)) return; + api.reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.ERROR) + .code("schema_mutation_error") + .message("A mutation of schema " + Json.stringify(schema) + " cannot be applied, so the rules it changes" + + " fail every value.") + .details(Map.of("schemaKey", schema)) + .originalError(error)); + } + @Override public void referenceTooDeep(String schema) { if (!reportedDepths.add(schema)) return; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java index dbf4f02..7dab7bb 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java @@ -14,12 +14,19 @@ final class Views { private Views() {} - /** Applies a node's mutations whose conditions match the value at it and the context. */ + /** + * Applies a node's mutations whose conditions match the value at it and the context. A node whose + * mutations cannot be applied stays as it is, since a view describes a form and validating reports the failure. + */ static BiFunction adjuster(Resolver resolve, Map context, String schema) { return (node, value) -> { Map map = Json.map(node); if (map == null || !Engine.hasMutations(map)) return node; - return Engine.mutatedRules(map, Engine.matchingMutations(map, value, context, resolve, schema), resolve); + try { + return Engine.mutatedRules(map, Engine.matchingMutations(map, value, context, resolve, schema), resolve); + } catch (RuntimeException failure) { + return node; + } }; } diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java index a840bc6..d66e3a5 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java @@ -15,30 +15,37 @@ import org.junit.jupiter.api.Test; /** - * A datafile the CLI built, with conditions as JSON text, against what the - * JavaScript package answers for it, messages included. Regenerate - * built-datafile-expected.json with the JavaScript package when the datafile changes. + * conformance/schemas-datafile.json: a datafile the CLI built, with conditions + * as JSON text, against what the JavaScript package answers for it, messages + * and handle members included. */ class BuiltDatafileTest { private static final ObjectMapper JSON = new ObjectMapper(); - private static String resource(String name) throws Exception { - try (InputStream stream = BuiltDatafileTest.class.getResourceAsStream("/" + name)) { - return new String(stream.readAllBytes(), StandardCharsets.UTF_8); + private static JsonNode fixture() throws Exception { + try (InputStream stream = BuiltDatafileTest.class.getResourceAsStream("/conformance/schemas-datafile.json")) { + return JSON.readTree(new String(stream.readAllBytes(), StandardCharsets.UTF_8)); } } private static Featurevisor instance(Map context) throws Exception { return Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() - .datafileString(resource("built-datafile.json")) + .datafileString(JSON.writeValueAsString(fixture().get("datafile"))) .context(context) .logLevel(FeaturevisorLogLevel.FATAL)); } + @Test + void isTheVersionThisRunnerKnows() throws Exception { + JsonNode fixture = fixture(); + assertEquals("featurevisor.schemas-datafile", fixture.get("kind").asText()); + assertEquals(1, fixture.get("schemaVersion").asInt()); + } + @Test @SuppressWarnings("unchecked") void validatesAsJavaScriptDoes() throws Exception { - JsonNode expected = JSON.readTree(resource("built-datafile-expected.json")); + JsonNode expected = fixture(); for (JsonNode testCase : expected.get("cases")) { Map context = JSON.convertValue(testCase.get("context"), Map.class); Schemas schemas = Schemas.create(instance(context)); @@ -61,7 +68,7 @@ void validatesAsJavaScriptDoes() throws Exception { @Test void describesFieldsAsJavaScriptDoes() throws Exception { - JsonNode expected = JSON.readTree(resource("built-datafile-expected.json")).get("members"); + JsonNode expected = fixture().get("members"); Schemas schemas = Schemas.create(instance(Map.of())); SchemaHandle signUp = schemas.get("signUp"); SchemaHandle business = signUp.withInput(Map.of("accountType", "business")); diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java index 04a0302..681c348 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasConformanceTest.java @@ -57,10 +57,13 @@ private static void run(JsonNode testCase) throws Exception { datafile.set("variables", JSON.createObjectNode()); datafile.set("schemas", testCase.get("schemas")); Map context = testCase.has("context") ? JSON.convertValue(testCase.get("context"), Map.class) : Map.of(); + List diagnostics = Collections.synchronizedList(new ArrayList<>()); Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() .datafileString(JSON.writeValueAsString(datafile)) .context(context) - .logLevel(FeaturevisorLogLevel.FATAL)); + // Errors reach onDiagnostic only at their own level or below. + .logLevel(FeaturevisorLogLevel.ERROR) + .onDiagnostic(diagnostic -> diagnostics.add(diagnostic.getCode()))); Schemas schemas = Schemas.create(f); Object value = JSON.convertValue(testCase.get("value"), Object.class); @@ -83,6 +86,15 @@ private static void run(JsonNode testCase) throws Exception { Collections.sort(actual); assertEquals(expected, actual, testCase.get("name").asText()); } + // The error diagnostics the case reports, each once, when it gives them. + if (testCase.has("diagnostics")) { + List expectedDiagnostics = new ArrayList<>(); + for (JsonNode code : testCase.get("diagnostics")) expectedDiagnostics.add(code.asText()); + Collections.sort(expectedDiagnostics); + List actualDiagnostics = new ArrayList<>(diagnostics); + Collections.sort(actualDiagnostics); + assertEquals(expectedDiagnostics, actualDiagnostics, testCase.get("name").asText()); + } } /** An issue's portable fields as canonical JSON text: keys sorted, numbers as JavaScript writes them. */ diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java index c765ae4..bde7875 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -193,15 +193,17 @@ void patternsMeanWhatTheyMeanInJavaScript() { // A whitespace class takes JavaScript's whitespace, such as a no break space. assertTrue(schemas.isValid("spaced", "a b")); assertTrue(schemas.isValid("spaced", "ab")); - // A brace that starts no quantifier is a brace. - assertTrue(schemas.isValid("braces", "a{")); + // A brace that starts no quantifier does not compile with the u flag, so it fails every value, as in JavaScript. + assertFalse(schemas.isValid("braces", "a{")); + // The u flag reads code points, so a dot takes an emoji whole. + assertTrue(schemas.isValid("dots", "a\uD83D\uDE00b")); // A dot takes U+0085, as JavaScript's does, and no line break. assertTrue(schemas.isValid("dots", "a\u0085b")); assertFalse(schemas.isValid("dots", "a\nb")); // A pattern Java cannot compile fails every value, and says so once. assertEquals(List.of("pattern"), codes(schemas.validate("broken", "x"))); schemas.validate("broken", "y"); - assertEquals(1, Collections.frequency(diagnostics, "schema_pattern_unsupported")); + assertEquals(2, Collections.frequency(diagnostics, "schema_pattern_unsupported")); } @Test diff --git a/featurevisor-schemas/src/test/resources/built-datafile.json b/featurevisor-schemas/src/test/resources/built-datafile.json deleted file mode 100644 index 5bb7417..0000000 --- a/featurevisor-schemas/src/test/resources/built-datafile.json +++ /dev/null @@ -1 +0,0 @@ -{"schemaVersion":"4","featurevisorVersion":"4.13.0","revision":"2","segments":{"netherlands":{"conditions":"{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}"},"paying":{"conditions":"{\"attribute\":\"plan\",\"operator\":\"equals\",\"value\":\"paid\"}"}},"features":{},"variables":{},"schemas":{"checkout":{"hash":"gSboXrZWcM","type":"object","properties":{"billingCountry":{"type":"string"},"shippingCountry":{"type":"string"},"customsDescription":{"type":"string"},"password":{"type":"string"},"confirmPassword":{"type":"string"}},"required":["billingCountry"],"mutations":[{"key":"shipsAbroad","conditions":"[{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}},\"paying\"]","operations":[{"op":"appendUnique","path":["required"],"value":"customsDescription"}]}]},"register":{"hash":"XlDf9sip1o","type":"object","properties":{"password":{"type":"string","minLength":8},"confirmPassword":{"type":"string","annotations":{"title":"Confirmation"}},"shippingCountry":{"type":"string"},"billingCountry":{"type":"string"}},"required":["password"],"issues":[{"key":"passwordsDiffer","conditions":"{\"input\":\"confirmPassword\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"password\"}}","path":"confirmPassword","message":"{title} does not match the password"},{"key":"dutchShippingCountry","conditions":"[\"netherlands\",{\"input\":\"shippingCountry\",\"operator\":\"notEquals\",\"valueFrom\":{\"input\":\"billingCountry\"}}]","path":"shippingCountry","message":"We ship Dutch orders to the billing country only"}]},"signUp":{"hash":"wLXjboTQnZ","type":"object","properties":{"accountType":{"type":"string","enum":["personal","business"],"annotations":{"title":"Account type","options":{"personal":{"title":"Personal"},"business":{"title":"Business"}}}},"displayName":{"type":"string","minLength":2,"maxLength":40,"annotations":{"title":"Display name","examples":["Ada","Grace Hopper"]}},"taxId":{"type":"string","annotations":{"title":"VAT number"}}},"required":["accountType","displayName"],"messages":{"displayName":{"minLength":"Use at least {minLength} characters"}},"annotations":{"title":"Create your account","order":["accountType","displayName","taxId"]},"mutations":[{"key":"business","conditions":"{\"input\":\"accountType\",\"operator\":\"equals\",\"value\":\"business\"}","operations":[{"op":"appendUnique","path":["required"],"value":"taxId"},{"op":"set","path":["properties","taxId","pattern"],"value":"^[A-Z]{2}[0-9]{9}$"},{"op":"set","path":["properties","taxId","messages"],"value":{"pattern":"Enter your VAT number, such as DE123456789"}}]}]}}} \ No newline at end of file From 32dddad65fc06e6a31f17e008a884fffdb2f569a Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 23:46:48 +0100 Subject: [PATCH 04/21] fix(cli): read segment definitions that carry metadata Segments listed by the Node.js CLI carry authoring fields such as metadata, which the SDK's segments do not hold. Reading them failed every test run on a project whose segments have metadata, Example 1 among them. --- featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java | 5 ++++- .../main/java/com/featurevisor/cli/SegmentEvaluations.java | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java b/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java index 06c8a96..ac4284a 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java @@ -322,7 +322,10 @@ private Map getConfig(String featurevisorProjectPath) throws IOE private Map getSegments(String featurevisorProjectPath) throws IOException { progress("Getting segments..."); String segmentsOutput = executeCommandInDirectory(featurevisorProjectPath, "npx featurevisor list --segments --json", selectionArguments()); - List segments = objectMapper.readValue(segmentsOutput, new TypeReference>() {}); + // Definitions carry authoring fields, such as metadata, which the SDK's segments do not hold. + List segments = objectMapper.readerFor(new TypeReference>() {}) + .without(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) + .readValue(segmentsOutput); Map segmentsByKey = new HashMap<>(); for (Segment segment : segments) { segmentsByKey.put(segment.getKey(), segment); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/cli/SegmentEvaluations.java b/featurevisor-sdk/src/main/java/com/featurevisor/cli/SegmentEvaluations.java index 81e7223..c309165 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/cli/SegmentEvaluations.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/cli/SegmentEvaluations.java @@ -14,7 +14,9 @@ /** SDK gates and structural preflight for compiled execution protocol segments. */ final class SegmentEvaluations { - private static final ObjectMapper JSON = new ObjectMapper(); + // Definitions carry authoring fields, such as metadata, which the SDK's segments do not hold. + private static final ObjectMapper JSON = new ObjectMapper() + .configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); final DatafileContent datafile; final Map featureKeys = new LinkedHashMap<>(); From 9877dfe98db666ad0d4141e4a1f7c429c7c6fb30 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 23:46:55 +0100 Subject: [PATCH 05/21] feat: evaluate package entries with module phases, as getters do The module API's evaluate runs every module's beforeEvaluation for a package's own entry, with the entry's type and key, and answers the conditions its callback matches with the context the modules leave, in one dependency session. Schemas validate and describe views inside it, so context a module adds reaches mutations and issue entries as it reaches flags. Nested feature and variable reads never carry the package's key or readers. The shared fixtures gain package condition cases with a module that adds context, and drop the case that counted references at one value to exactly 128. --- README.md | 4 +- conformance/schemas-validation.json | 22 ----- conformance/sdk-package-conditions.json | 80 +++++++++++++++++++ .../java/com/featurevisor/schemas/Engine.java | 9 +-- .../com/featurevisor/schemas/Matcher.java | 8 ++ .../com/featurevisor/schemas/Resolver.java | 6 +- .../java/com/featurevisor/schemas/Run.java | 14 ++-- .../featurevisor/schemas/SchemaHandle.java | 62 +++++++++----- .../java/com/featurevisor/schemas/Store.java | 28 +++++-- .../java/com/featurevisor/schemas/Views.java | 9 ++- .../com/featurevisor/schemas/SchemasTest.java | 43 ++++++++++ .../java/com/featurevisor/sdk/Evaluate.java | 60 ++++++++------ .../com/featurevisor/sdk/EvaluateOptions.java | 6 ++ .../featurevisor/sdk/EvaluationSession.java | 6 ++ .../com/featurevisor/sdk/Featurevisor.java | 67 ++++++++++++++++ .../sdk/FeaturevisorModuleApi.java | 17 ++++ .../sdk/PackageEvaluationRequest.java | 25 ++++++ .../sdk/PackageEvaluationScope.java | 21 +++++ .../sdk/ModuleConditionsTest.java | 35 ++++++++ .../sdk/PackageConditionsConformanceTest.java | 33 +++++--- 20 files changed, 448 insertions(+), 107 deletions(-) create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/Matcher.java create mode 100644 featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationRequest.java create mode 100644 featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationScope.java diff --git a/README.md b/README.md index dae13f9..d736790 100644 --- a/README.md +++ b/README.md @@ -809,7 +809,7 @@ FeaturevisorModule myCustomModule = new FeaturevisorModule("my-custom-module") }); ``` -The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `getEntry(section, key)` returns an entry as stored, so treat it as read only, and `getEntryKeys(section)` lists a section's keys. `matchConditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `MatchConditionsOptions.reader` answers leaves only the package knows, such as `input`. This is how the [schemas](#schemas) artifact reads its schemas. +The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `getEntry(section, key)` returns an entry as stored, so treat it as read only, and `getEntryKeys(section)` lists a section's keys. `matchConditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `MatchConditionsOptions.reader` answers leaves only the package knows, such as `input`. `evaluate(new PackageEvaluationRequest(type, key).context(context), scope -> ...)` evaluates a package's own entry as a getter evaluates a feature: every module's `beforeEvaluation` runs first, with `getType()` and `getKey()` naming the entry, and the conditions the callback answers with `scope.matchConditions(conditions, readers)` read the context the modules leave, in one dependency session. This is how the [schemas](#schemas) artifact reads its schemas. ### Registering modules @@ -991,7 +991,7 @@ if (!result.isValid()) { A value can be maps, lists, strings, numbers, booleans and `null`, a Jackson `JsonNode`, or any object Jackson can convert, such as a request class with getters. `parse` returns the value when it passes and throws a `SchemaValidationException` with the issues when it does not. `flatten()` on a result or an exception groups the messages by field name, such as `displayName` or `items.0.name`, for an error response. -Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. +Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. Validation runs as the schema's evaluation, so a module's `beforeEvaluation` sees type `schema` and the schema's key, and context it adds reaches every condition, as it does for flags. ### Handles diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index e5f79a7..abf81ab 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -3536,28 +3536,6 @@ "schema_reference_depth" ] }, - { - "name": "references at the same value count to exactly 128", - "schemas": { - "subject": { - "hash": "subject-1", - "oneOf": [ - { - "schema": "subject" - }, - { - "type": "string" - } - ] - } - }, - "schema": "subject", - "value": "a", - "issues": [], - "diagnostics": [ - "schema_reference_depth" - ] - }, { "name": "a mutation's conditions can be JSON text", "schemas": { diff --git a/conformance/sdk-package-conditions.json b/conformance/sdk-package-conditions.json index 127a87a..30da8ee 100644 --- a/conformance/sdk-package-conditions.json +++ b/conformance/sdk-package-conditions.json @@ -38,6 +38,17 @@ "percentage": 100000 } ] + }, + "dutchOnly": { + "hash": "f2", + "bucketBy": "userId", + "traffic": [ + { + "key": "dutch", + "conditions": "dutch", + "percentage": 100000 + } + ] } }, "variables": {} @@ -350,6 +361,75 @@ }, "expected": true }, + { + "name": "without a module, an attribute the context lacks does not match", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "pro" + } + ], + "expected": false + }, + { + "name": "a module's context reaches attribute leaves", + "conditions": [ + { + "attribute": "plan", + "operator": "equals", + "value": "pro" + } + ], + "module": { + "context": { + "plan": "pro" + } + }, + "expected": true + }, + { + "name": "a module's context goes over the call's, as for flags", + "conditions": "dutch", + "context": { + "country": "de" + }, + "module": { + "context": { + "country": "nl" + } + }, + "expected": true + }, + { + "name": "without a module, a feature gated by the context is off", + "conditions": [ + { + "feature": "dutchOnly" + } + ], + "context": { + "country": "de" + }, + "expected": false + }, + { + "name": "a module's context reaches feature leaves", + "conditions": [ + { + "feature": "dutchOnly" + } + ], + "context": { + "country": "de" + }, + "module": { + "context": { + "country": "nl" + } + }, + "expected": true + }, { "name": "an input leaf in a group with an attribute leaf", "conditions": { diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java index 79fd7de..d805c08 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java @@ -585,13 +585,12 @@ static boolean hasMutations(Object node) { } /** Which of a node's mutations match the value at it, as an id such as {@code 0,2,}. */ - static String matchingMutations(Map node, Object value, Map context, Resolver resolve, - String schema) { + static String matchingMutations(Map node, Object value, Matcher match) { List> mutations = mutationsOf(node); ConditionReader input = inputReader(value); StringBuilder id = new StringBuilder(); for (int index = 0; index < mutations.size(); index++) { - if (resolve.match(mutations.get(index).get("conditions"), context, input, schema)) id.append(index).append(','); + if (match.match(mutations.get(index).get("conditions"), input)) id.append(index).append(','); } return id.toString(); } @@ -644,7 +643,7 @@ private static Validator compileMutations(Map node, Resolver res List> mutations = mutationsOf(node); Map variants = new ConcurrentHashMap<>(); return (value, run, at) -> { - String id = matchingMutations(node, value, run.sources.info.getContext(), resolve, run.schema); + String id = matchingMutations(node, value, run.match); Variant variant = variants.get(id); if (variant == null) { try { @@ -710,7 +709,7 @@ private static Validator compileIssues(Map node, Validator rules for (Object item : entries) { Map entry = Json.map(item); if (entry == null) continue; - if (!resolve.match(entry.get("conditions"), run.sources.info.getContext(), input, run.schema)) continue; + if (!run.match.match(entry.get("conditions"), input)) continue; String path = Json.string(entry.get("path")); List parts = path == null || path.isEmpty() ? List.of() : Arrays.asList(path.split("\\.", -1)); List scopes = new ArrayList<>(at.scopes); diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Matcher.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Matcher.java new file mode 100644 index 0000000..69dec4f --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Matcher.java @@ -0,0 +1,8 @@ +package com.featurevisor.schemas; + +import com.featurevisor.sdk.ConditionReader; + +/** Answers a schema's conditions in its package evaluation, with {@code input} leaves reading the value at the node. */ +interface Matcher { + boolean match(Object conditions, ConditionReader input); +} diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java index 2e7d908..945f1c7 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java @@ -1,9 +1,8 @@ package com.featurevisor.schemas; -import com.featurevisor.sdk.ConditionReader; import java.util.Map; -/** Schemas of the current datafile by key, compiled, with the matcher conditions use and the caches of mutated rules. */ +/** Schemas of the current datafile by key, compiled, with the caches of mutated rules. */ interface Resolver { /** A compiled schema and its node, or null when the datafile has none. */ Resolved resolve(String key); @@ -14,9 +13,6 @@ interface Resolver { /** Reports, once, a schema that follows references deeper than any value can need, which fails the value. */ void referenceTooDeep(String schema); - /** Answers conditions with the SDK's engine, for the schema being validated. */ - boolean match(Object conditions, Map context, ConditionReader input, String schema); - /** A node's rules with a combination of its mutations applied, the same object for the same combination. */ Map mutated(Map node, String id, java.util.function.Supplier> make); diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java index f8b2995..84f1d71 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java @@ -16,22 +16,26 @@ final class Run { int shape; /** How many references the walk follows at this point, which only a value nested as deep can need. */ int depth; + /** Answers conditions in the schema's package evaluation, with the context its modules leave. */ + final Matcher match; - Run(String schema, Messages.Sources sources, IssueTranslator translate) { - this(schema, new ArrayList<>(), sources, translate, false); + Run(String schema, Messages.Sources sources, IssueTranslator translate, Matcher match) { + this(schema, new ArrayList<>(), sources, translate, false, match); } - private Run(String schema, List issues, Messages.Sources sources, IssueTranslator translate, boolean trial) { + private Run(String schema, List issues, Messages.Sources sources, IssueTranslator translate, boolean trial, + Matcher match) { this.schema = schema; this.issues = issues; this.sources = sources; this.translate = translate; this.trial = trial; + this.match = match; } /** A run for one {@code oneOf} branch, which only notes whether it fails. */ Run trial() { - Run trial = new Run(schema, new ArrayList<>(), sources, translate, true); + Run trial = new Run(schema, new ArrayList<>(), sources, translate, true, match); trial.shape = shape; trial.depth = depth; return trial; @@ -39,6 +43,6 @@ Run trial() { /** The same run without the translator, for knowing which fields have issues. */ Run untranslated() { - return new Run(schema, new ArrayList<>(), sources, null, false); + return new Run(schema, new ArrayList<>(), sources, null, false, match); } } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 981bbdb..4887fd4 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -13,6 +13,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.function.BiFunction; +import java.util.function.Function; import java.util.function.Supplier; /** @@ -178,8 +179,10 @@ public CompletableFuture validateAsync(Object value) { */ public CompletableFuture validateAsync(Object value, Map context) { Object input = Json.plain(value); - Run run = run(context); - Located located = applyRules(input, run); + // The rules run in the schema's evaluation, and checks in code after it. + Object[] ran = evaluated(context, run -> new Object[] {run, applyRules(input, run)}); + Run run = (Run) ran[0]; + Located located = (Located) ran[1]; List checks = located == null ? List.of() : checks(); if (checks.isEmpty()) return CompletableFuture.completedFuture(new ValidationResult(value, run.issues)); return runChecks(value, input, context, run, located, checks); @@ -210,9 +213,10 @@ public ValidationResult validateRules(Object value) { } public ValidationResult validateRules(Object value, Map context) { - Run run = run(context); - applyRules(Json.plain(value), run); - return new ValidationResult(value, run.issues); + return evaluated(context, run -> { + applyRules(Json.plain(value), run); + return new ValidationResult(value, run.issues); + }); } /** Whether the handle has checks in code, which can make validation wait for an answer. */ @@ -220,17 +224,24 @@ public boolean hasChecks() { return !checks().isEmpty(); } - private Run run(Map given) { - // A view's context, with one given to the call merged over it. + /** + * Runs the body with a run in the schema's package evaluation, so modules see it + * and its conditions read the context they leave. A view's context comes first, + * with one given to the call merged over it. + */ + private T evaluated(Map given, Function body) { Map merged = given; if (view != null && view.context != null) { merged = new LinkedHashMap<>(view.context); if (given != null) merged.putAll(given); } - Map finalContext = merged; - MessageInfo info = new MessageInfo(() -> context.store.f.getContext(finalContext)); + return context.store.evaluate(key, merged, scope -> body.apply(run(scope))); + } + + private Run run(Store.Scope scope) { + MessageInfo info = new MessageInfo(() -> scope.context); return new Run(key, new Messages.Sources(options == null ? null : options.getMessages(), - context.options.getMessages(), info), context.options.getTranslator()); + context.options.getMessages(), info), context.options.getTranslator(), scope.match); } /** @@ -244,7 +255,7 @@ private Located locate(Object value, Run run) { if (root == null) return null; Store.Walk walk = view == null ? null : new Store.Walk( Views.place(view.values, steps.subList(view.from, steps.size()), value), view.from, - Views.adjuster(store, run.sources.info.getContext(), key)); + Views.adjuster(store, run.match)); Store.Location field = Store.locate(store, root.node, steps, List.of(), List.of(), walk); if (field == null) return null; return new Located(store.compile(field.node), field.node, new Messages.Lookup(field.mpath, field.scopes, null, null)); @@ -438,9 +449,11 @@ private static String failure(CheckKind kind) { private List rootRuleIssues(Object input, Map given) { Resolver.Resolved root = context.store.resolve(key); if (root == null) return List.of(); - Run run = run(given).untranslated(); - root.validate.validate(input, run, new Position(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null)); - return run.issues; + return evaluated(given, base -> { + Run run = base.untranslated(); + root.validate.validate(input, run, new Position(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null)); + return run.issues; + }); } private void reportCheck(Run run, Located located, List slot, String code, Check check, List at) { @@ -517,13 +530,18 @@ private Described describe(View view) { Store store = context.store; Resolver.Resolved root = store.resolve(key); if (root == null) return null; - BiFunction adjust = view == null ? null - : Views.adjuster(store, store.f.getContext(view.context), key); - Store.Location field = Store.locate(store, root.node, steps, List.of(), List.of(), - adjust == null ? null : new Store.Walk(view.values, view.from, adjust)); - if (field == null) return null; - if (adjust == null) return new Described(field.node, field.required); - return new Described(Views.resolveTree(field.node, field.value, adjust, store, List.of()), field.required); + if (view == null) { + Store.Location field = Store.locate(store, root.node, steps, List.of(), List.of(), null); + return field == null ? null : new Described(field.node, field.required); + } + // A view's mutations match in the schema's evaluation, with the view's context. + return store.evaluate(key, view.context, scope -> { + BiFunction adjust = Views.adjuster(store, scope.match); + Store.Location field = Store.locate(store, root.node, steps, List.of(), List.of(), + new Store.Walk(view.values, view.from, adjust)); + if (field == null) return null; + return new Described(Views.resolveTree(field.node, field.value, adjust, store, List.of()), field.required); + }); } /** What a member derives from the node, kept until the datafile changes, since a field's can come from a referenced schema. */ @@ -705,7 +723,7 @@ public CompletableFuture lookup(Object value, Map } private CheckInfo sourceInfo(Map given) { - return new CheckInfo(view == null ? null : view.values, run(given).sources.info.getContext()); + return new CheckInfo(view == null ? null : view.values, evaluated(given, run -> run.sources.info.getContext())); } // Changes diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java index a257747..869d44b 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java @@ -8,7 +8,7 @@ import com.featurevisor.sdk.FeaturevisorModule; import com.featurevisor.sdk.FeaturevisorModuleApi; import com.featurevisor.sdk.FeaturevisorUnsubscribe; -import com.featurevisor.sdk.MatchConditionsOptions; +import com.featurevisor.sdk.PackageEvaluationRequest; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -18,6 +18,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; +import java.util.function.Function; import java.util.function.Supplier; /** @@ -167,11 +168,26 @@ Validator compile(Object node) { return validate; } - @Override - public boolean match(Object conditions, Map context, ConditionReader input, String schema) { - // Conditions read through the SDK, so a segment means in a schema what it means in a flag. - return api.matchConditions(conditions, context, - new MatchConditionsOptions().type("schema").key(schema).reader("input", input)); + /** What a schema's package evaluation gives: its context and a matcher for its conditions. */ + static final class Scope { + final Map context; + final Matcher match; + + Scope(Map context, Matcher match) { + this.context = context; + this.match = match; + } + } + + /** + * Runs the callback in the schema's package evaluation, so modules see it as they see a + * getter, and its conditions read the context they leave. Conditions read through the + * SDK, so a segment means in a schema what it means in a flag. + */ + T evaluate(String key, Map context, Function callback) { + return api.evaluate(new PackageEvaluationRequest("schema", key).context(context), scope -> + callback.apply(new Scope(scope.getContext(), + (conditions, input) -> scope.matchConditions(conditions, Map.of("input", input))))); } @Override diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java index 7dab7bb..3fd26aa 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java @@ -15,15 +15,16 @@ final class Views { private Views() {} /** - * Applies a node's mutations whose conditions match the value at it and the context. A node whose - * mutations cannot be applied stays as it is, since a view describes a form and validating reports the failure. + * Applies a node's mutations whose conditions match the value at it, in the schema's package evaluation. + * A node whose mutations cannot be applied stays as it is, since a view describes a form and validating + * reports the failure. */ - static BiFunction adjuster(Resolver resolve, Map context, String schema) { + static BiFunction adjuster(Resolver resolve, Matcher match) { return (node, value) -> { Map map = Json.map(node); if (map == null || !Engine.hasMutations(map)) return node; try { - return Engine.mutatedRules(map, Engine.matchingMutations(map, value, context, resolve, schema), resolve); + return Engine.mutatedRules(map, Engine.matchingMutations(map, value, match), resolve); } catch (RuntimeException failure) { return node; } diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java index bde7875..68bac47 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -310,4 +310,47 @@ private static List messages(ValidationResult result) { for (SchemaIssue issue : result.getIssues()) messages.add(issue.getMessage()); return messages; } + + @Test + void contextAModuleAddsReachesMutationsIssueEntriesAndViewsAsItReachesFlags() { + String schemas = "{\"signUp\":{\"hash\":\"s1\",\"type\":\"object\"," + + "\"properties\":{\"taxId\":{\"type\":\"string\"},\"name\":{\"type\":\"string\"}}," + + "\"mutations\":[{\"key\":\"dutch\"," + + " \"conditions\":[{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}]," + + " \"operations\":[{\"op\":\"appendUnique\",\"path\":[\"required\"],\"value\":\"taxId\"}]}]," + + "\"issues\":[{\"key\":\"noAda\"," + + " \"conditions\":[\"dutch\",{\"input\":\"name\",\"operator\":\"equals\",\"value\":\"Ada\"}]," + + " \"path\":\"name\",\"message\":\"Pick another name\"}]}}"; + String datafile = "{\"schemaVersion\":\"4\",\"revision\":\"1\",\"features\":{},\"variables\":{}," + + "\"segments\":{\"dutch\":{\"conditions\":[{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}]}}," + + "\"schemas\":" + schemas + "}"; + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile) + .logLevel(FeaturevisorLogLevel.FATAL)); + List seen = Collections.synchronizedList(new ArrayList<>()); + f.addModule(new com.featurevisor.sdk.FeaturevisorModule("geo").beforeEvaluation(options -> { + seen.add(options.getType() + " " + options.getKey()); + Map context = new java.util.HashMap<>(options.getContext()); + context.put("country", "nl"); + return options.copy().context(context); + })); + Schemas s = Schemas.create(f); + + assertEquals(List.of("required taxId"), codesAt(s.validate("signUp", Map.of("name", "Ada")))); + assertEquals(List.of("refine name"), codesAt(s.validate("signUp", Map.of("name", "Ada", "taxId", "x")))); + assertTrue(s.get("signUp").withInput(Map.of()).at("taxId").getConstraints().isRequired()); + // One evaluation per validation and per view, each the schema's own. + assertFalse(seen.isEmpty()); + for (String evaluation : seen) assertEquals("schema signUp", evaluation); + } + + private static List codesAt(ValidationResult result) { + List codes = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) { + StringBuilder path = new StringBuilder(); + for (Object part : issue.getPath()) path.append(path.length() == 0 ? "" : ".").append(part); + codes.add(issue.getCode() + " " + path); + } + return codes; + } } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java index fb0e16c..63d1c14 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Evaluate.java @@ -18,6 +18,38 @@ final class Evaluate { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper() .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + /** + * Runs every module's {@code beforeEvaluation} in registration order, as a + * getter and a package evaluation do, keeping the session, the requester and + * the sticky source each module's options would otherwise lose. + */ + static EvaluateOptions beforeModules(EvaluateOptions opts) { + EvaluationSession session = opts.getSession(); + ModulesManager modulesManager = opts.getModulesManager(); + EvaluateOptions options = opts; + if (modulesManager != null) { + for (FeaturevisorModule module : modulesManager.phaseModules()) { + if (module.getBeforeEvaluation() != null) { + Map previousFeatures = options.getStickyFeatures(); + Map previousVariables = options.getStickyVariables(); + EvaluateOptions.StickySource source = options.getStickySource(); + boolean inheritedFeatures = options.inheritsStickyFeatures(); + boolean inheritedVariables = options.inheritsStickyVariables(); + options = module.getBeforeEvaluation().apply(options); + session.retainCallbackOptions(options); + options.setSession(session); + options.setDependencyOf(opts.getDependencyOf()); + options.setDependencyPurpose(opts.getDependencyPurpose()); + if (options.getStickySource() == null) options.setStickySource(source, inheritedFeatures, inheritedVariables); + if (options.getStickyFeatures() != previousFeatures) options.setInheritedStickyFeatures(false); + if (options.getStickyVariables() != previousVariables) options.setInheritedStickyVariables(false); + } + } + } + options.refreshSticky(); + return options; + } + /** * Evaluate with modules * @param opts The evaluation options @@ -30,28 +62,7 @@ public static Evaluation evaluateWithModules(EvaluateOptions opts) { try { ModulesManager modulesManager = opts.getModulesManager(); - // run before modules - EvaluateOptions options = opts; - if (modulesManager != null) { - for (FeaturevisorModule module : modulesManager.phaseModules()) { - if (module.getBeforeEvaluation() != null) { - Map previousFeatures = options.getStickyFeatures(); - Map previousVariables = options.getStickyVariables(); - EvaluateOptions.StickySource source = options.getStickySource(); - boolean inheritedFeatures = options.inheritsStickyFeatures(); - boolean inheritedVariables = options.inheritsStickyVariables(); - options = module.getBeforeEvaluation().apply(options); - session.retainCallbackOptions(options); - options.setSession(session); - options.setDependencyOf(opts.getDependencyOf()); - options.setDependencyPurpose(opts.getDependencyPurpose()); - if (options.getStickySource() == null) options.setStickySource(source, inheritedFeatures, inheritedVariables); - if (options.getStickyFeatures() != previousFeatures) options.setInheritedStickyFeatures(false); - if (options.getStickyVariables() != previousVariables) options.setInheritedStickyVariables(false); - } - } - } - options.refreshSticky(); + EvaluateOptions options = beforeModules(opts); session.updateCurrent(DependencyOf.from(options)); // evaluate @@ -287,7 +298,7 @@ private static boolean condition(Object expression, EvaluateOptions options) { if (!(value.get("feature") instanceof String)) return false; EvaluateOptions clean = options.copy().featureKey((String) value.get("feature")) .globalVariable(false).variableKey(null).defaultVariationValue(null) - .defaultVariableValue(null, false).readers(null); + .defaultVariableValue(null, false).readers(null).key(null); boolean enabled = !value.containsKey("enabled") || Boolean.TRUE.equals(value.get("enabled")); if (Boolean.TRUE.equals(readDependency(clean.type(Evaluation.TYPE_FLAG))) != enabled) return false; return !value.containsKey("variation") @@ -367,7 +378,8 @@ private static boolean variableCondition(Object required, EvaluateOptions option .defaultVariationValue(null) .type(Evaluation.TYPE_VARIABLE) .variableKey(variableKey) - .readers(null); + .readers(null) + .key(null); if (featureValue instanceof String) { value = readDependency(clean.featureKey((String) featureValue).globalVariable(false)); } else { diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java index 2bff758..71dde50 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluateOptions.java @@ -12,6 +12,8 @@ public class EvaluateOptions { private String type; private String featureKey; private String variableKey; + /** A package entry's key, such as a schema's, when the evaluation is a package's own. */ + private String key; private boolean globalVariable; // Dependencies @@ -65,6 +67,8 @@ public EvaluateOptions(String type, String featureKey, String variableKey) { public String getType() { return type; } public String getFeatureKey() { return featureKey; } public String getVariableKey() { return variableKey; } + /** A package entry's key, such as {@code signUp} when {@link #getType()} is {@code schema}. */ + public String getKey() { return key; } public boolean isGlobalVariable() { return globalVariable; } public Map getContext() { return context; } DiagnosticReporter getDiagnostics() { return diagnostics; } @@ -108,6 +112,7 @@ public void setDefaultVariableValue(Object defaultVariableValue) { } void setSession(EvaluationSession session) { this.session = session; } Map getReaders() { return readers; } + EvaluateOptions key(String value) { this.key = value; return this; } EvaluateOptions readers(Map value) { this.readers = value; return this; } public void setDependencyOf(DependencyOf dependencyOf) { this.dependencyOf = dependencyOf; } void setStickySource(StickySource source, boolean features, boolean variables) { @@ -192,6 +197,7 @@ public EvaluateOptions copy() { copy.type = this.type; copy.featureKey = this.featureKey; copy.variableKey = this.variableKey; + copy.key = this.key; copy.context = this.context; copy.diagnostics = this.diagnostics; copy.modulesManager = this.modulesManager; diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluationSession.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluationSession.java index 65c58ba..648c66b 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluationSession.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/EvaluationSession.java @@ -135,6 +135,12 @@ void throwIfFatal() { if (requirementFailure != null) throw requirementFailure; } + /** Lets a package evaluation's next condition answer after one that failed, as each call fails alone. */ + void clearFatal() { + cycleDetected = false; + requirementFailure = null; + } + T segment(String key, Supplier evaluate) { prepareFrames(); if (segments == null) segments = new java.util.HashSet<>(); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java index a23049a..fb65772 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java @@ -10,6 +10,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.util.Map; import java.util.HashMap; +import java.util.Collections; import java.util.List; import java.util.ArrayList; import java.util.UUID; @@ -328,9 +329,75 @@ public List getEntryKeys(String section) { public boolean matchConditions(Object conditions, Map context, MatchConditionsOptions options) { return Featurevisor.this.matchConditions(conditions, context, options, module); } + + @Override + public T evaluate(PackageEvaluationRequest request, java.util.function.Function callback) { + return Featurevisor.this.evaluatePackage(request, callback, module); + } }; } + /** A package's own entry, evaluated with the module phases a getter runs before evaluating. */ + private T evaluatePackage(PackageEvaluationRequest request, + java.util.function.Function callback, FeaturevisorModule module) { + String type = request.getType(); + String key = request.getKey(); + EvaluateOptions options = getEvaluationDependencies(request.getContext(), null).type(type).key(key); + EvaluationSession session = options.getSession(); + // One session for every condition the package answers in this evaluation. + boolean ownsRoot = session.beginRoot(DependencyOf.ofEntry(type, key)); + session.retainCallbackOptions(options); + try { + EvaluateOptions evaluated = options; + try { + evaluated = Evaluate.beforeModules(options); + } catch (RuntimeException error) { + reportPackageError("beforeEvaluation failed", type, key, error, null); + } + final EvaluateOptions scoped = evaluated; + final Map context = Collections.unmodifiableMap( + scoped.getContext() != null ? scoped.getContext() : new HashMap<>()); + return callback.apply(new PackageEvaluationScope() { + @Override + public Map getContext() { return context; } + + @Override + public boolean matchConditions(Object conditions, Map readers) { + // A copy with this call's readers, in the same session. + EvaluateOptions dependencies = scoped.copy() + .readers(readers == null || readers.isEmpty() ? null : readers); + try { + Object parsed = conditions instanceof String && Normalize.stringified((String) conditions) + ? dependencies.getInstanceEvaluationDataProvider().parseConditionsIfStringified(conditions) + : conditions; + boolean matched = Evaluate.conditionsAreMatched(parsed, dependencies); + session.throwIfFatal(); + return matched; + } catch (RuntimeException | StackOverflowError error) { + session.clearFatal(); + reportPackageError("matchConditions failed", type, key, error, module); + return false; + } + } + }); + } finally { + if (ownsRoot) session.endRoot(); + } + } + + private void reportPackageError(String message, String type, String key, Throwable error, FeaturevisorModule module) { + Map details = new HashMap<>(); + details.put("type", type); + details.put("key", key); + reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.ERROR) + .code("evaluation_error") + .message(message) + .details(details) + .originalError(error), + module); + } + /** A package's conditions, answered in one dependency session of their own. */ private boolean matchConditions(Object conditions, Map context, MatchConditionsOptions options, FeaturevisorModule module) { diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java index ab2eab8..a82e0ba 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/FeaturevisorModuleApi.java @@ -2,6 +2,7 @@ import java.util.List; import java.util.Map; +import java.util.function.Function; public interface FeaturevisorModuleApi { String getRevision(); @@ -45,4 +46,20 @@ default boolean matchConditions(Object conditions, Map context, default boolean matchConditions(Object conditions, Map context) { return matchConditions(conditions, context, null); } + + /** + * Evaluates a package's own entry as a getter evaluates a feature: the + * request's context is merged over the instance's, and every module's + * {@code beforeEvaluation} runs in registration order with options whose + * {@link EvaluateOptions#getType()} is the request's type and whose + * {@link EvaluateOptions#getKey()} is its key. The callback reads with the + * context that results, and every condition it matches answers in this one + * dependency session, with the entry as the requester of feature and variable + * leaves. A module that throws reports {@code evaluation_error}, and the + * evaluation goes on with the options before the modules. The callback's + * result is returned as it is. + */ + default T evaluate(PackageEvaluationRequest request, Function callback) { + throw new UnsupportedOperationException("This module API cannot evaluate a package entry"); + } } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationRequest.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationRequest.java new file mode 100644 index 0000000..9a0a526 --- /dev/null +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationRequest.java @@ -0,0 +1,25 @@ +package com.featurevisor.sdk; + +import java.util.Map; + +/** + * What {@link FeaturevisorModuleApi#evaluate} evaluates: a package's own type, + * such as {@code schema}, which modules see as the evaluation's type, the + * entry's key, and a context merged over the instance's. + */ +public final class PackageEvaluationRequest { + private final String type; + private final String key; + private Map context; + + public PackageEvaluationRequest(String type, String key) { + this.type = type; + this.key = key; + } + + public PackageEvaluationRequest context(Map context) { this.context = context; return this; } + + public String getType() { return type; } + public String getKey() { return key; } + public Map getContext() { return context; } +} diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationScope.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationScope.java new file mode 100644 index 0000000..d444a19 --- /dev/null +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/PackageEvaluationScope.java @@ -0,0 +1,21 @@ +package com.featurevisor.sdk; + +import java.util.Collections; +import java.util.Map; + +/** What a package evaluation's callback reads with. */ +public interface PackageEvaluationScope { + /** The context after every module's {@code beforeEvaluation}, as a getter's conditions see it. */ + Map getContext(); + + /** + * Answers conditions with that context, in the evaluation's one dependency + * session, as {@link FeaturevisorModuleApi#matchConditions} does otherwise. + * Readers answer leaves only the package knows, such as {@code input}. + */ + boolean matchConditions(Object conditions, Map readers); + + default boolean matchConditions(Object conditions) { + return matchConditions(conditions, Collections.emptyMap()); + } +} diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java index 6ecb416..2d67bab 100644 --- a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/ModuleConditionsTest.java @@ -101,6 +101,41 @@ void featureLeavesReachModulesAsDependenciesOfThePackagesEntry() { assertEquals(List.of("paid for schema signUp"), seen); } + @Test + void evaluateRunsTheModulesForTheEntryAsAGetterDoesAndAnswersInOneSession() { + List before = new ArrayList<>(); + List after = new ArrayList<>(); + FeaturevisorModule geo = new FeaturevisorModule("geo") + .beforeEvaluation(options -> { + if (options.getKey() != null) { + before.add(options.getType() + " " + options.getKey() + " " + options.getContext().get("country")); + } + // A module that adds context, as one reading a request's country would. + Map context = new HashMap<>(options.getContext()); + context.put("country", "nl"); + return options.copy().context(context); + }) + .afterEvaluation((evaluation, options) -> { + DependencyOf parent = options.getDependencyOf(); + after.add(evaluation.getFeatureKey() + " for " + parent.getType() + " " + parent.getKey()); + return evaluation; + }); + FeaturevisorModuleApi api = setup(geo); + + Map result = api.evaluate( + new PackageEvaluationRequest("schema", "signUp").context(Map.of("country", "de")), + scope -> Map.of( + "country", scope.getContext().get("country"), + "dutch", scope.matchConditions("dutch"), + "paid", scope.matchConditions(List.of(Map.of("feature", "paid"))), + "payingDutch", scope.matchConditions("payingDutch"))); + + assertEquals(Map.of("country", "nl", "dutch", true, "paid", true, "payingDutch", true), result); + assertEquals(List.of("schema signUp de"), before); + // The feature is read once in the evaluation's session, for the entry. + assertEquals(List.of("paid for schema signUp"), after); + } + @Test void aConditionThatCannotBeAnsweredReportsEvaluationErrorAndDoesNotMatch() { FeaturevisorModuleApi api = setup(); diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java index 8b9fbba..33264c3 100644 --- a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/PackageConditionsConformanceTest.java @@ -7,6 +7,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import java.io.InputStream; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -15,7 +16,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; -/** Runs conformance/sdk-package-conditions.json: matchConditions with readers, as packages call it. */ +/** Runs conformance/sdk-package-conditions.json: conditions in a package evaluation, as packages answer them. */ class PackageConditionsConformanceTest { private static final ObjectMapper JSON = new ObjectMapper(); @@ -46,6 +47,15 @@ Stream cases() throws Exception { .datafileString(datafile) .context(instanceContext) .logLevel(FeaturevisorLogLevel.FATAL)); + if (testCase.has("module")) { + // A module whose beforeEvaluation merges this context over every evaluation's. + Map added = JSON.convertValue(testCase.get("module").get("context"), Map.class); + f.addModule(new FeaturevisorModule("context").beforeEvaluation(options -> { + Map merged = new HashMap<>(options.getContext()); + merged.putAll(added); + return options.copy().context(merged); + })); + } AtomicReference api = new AtomicReference<>(); f.addModule(new FeaturevisorModule("package").setup(api::set)); Object conditions = JSON.convertValue(testCase.get("conditions"), Object.class); @@ -53,18 +63,17 @@ Stream cases() throws Exception { ? JSON.convertValue(testCase.get("context"), Map.class) : Map.of(); boolean expected = testCase.get("expected").asBoolean(); - // Twice, so a cached answer is the answer. + Map readers = new HashMap<>(); + if (testCase.has("input")) { + Map input = JSON.convertValue(testCase.get("input"), Map.class); + // An absent key reads as nothing, which differs from null. + readers.put("input", path -> input.containsKey(path) ? input.get(path) : ConditionReader.ABSENT); + } + // Twice, so a cached answer is the answer, each in a package evaluation as a package makes one. for (int attempt = 0; attempt < 2; attempt++) { - boolean matched; - if (testCase.has("input")) { - Map input = JSON.convertValue(testCase.get("input"), Map.class); - // An absent key reads as nothing, which differs from null. - MatchConditionsOptions readers = new MatchConditionsOptions() - .reader("input", path -> input.containsKey(path) ? input.get(path) : ConditionReader.ABSENT); - matched = api.get().matchConditions(conditions, context, readers); - } else { - matched = api.get().matchConditions(conditions, context); - } + boolean matched = api.get().evaluate( + new PackageEvaluationRequest("schema", "subject").context(context), + scope -> scope.matchConditions(conditions, readers)); assertEquals(expected, matched, testCase.get("name").asText()); } })); From 90db33a8855aa55879be7c715f3eabf6f043eb67 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Fri, 27 Nov 2026 23:47:02 +0100 Subject: [PATCH 06/21] feat(cli): run schema specs with featurevisor-schemas The test runner asks for schema specs and validates each assertion's value as the JavaScript CLI does, against the datafile of its environment and Target, under its context. featurevisor-schemas provides the validator as a service, so the SDK does not depend on it. Run the CLI from the featurevisor-schemas module to have it, while from featurevisor-sdk alone each schema case fails saying so. A Node.js CLI from before schema specs rejects the option, so the runner asks again without it. --- README.md | 7 +- featurevisor-schemas/pom.xml | 19 ++ .../schemas/CliSchemaSpecValidator.java | 32 ++++ .../com.featurevisor.cli.SchemaSpecValidator | 1 + .../main/java/com/featurevisor/cli/CLI.java | 178 ++++++++++++++++-- .../featurevisor/cli/SchemaSpecValidator.java | 19 ++ .../featurevisor/cli/RuntimeCommandTest.java | 22 +++ 7 files changed, 261 insertions(+), 17 deletions(-) create mode 100644 featurevisor-schemas/src/main/java/com/featurevisor/schemas/CliSchemaSpecValidator.java create mode 100644 featurevisor-schemas/src/main/resources/META-INF/services/com.featurevisor.cli.SchemaSpecValidator create mode 100644 featurevisor-sdk/src/main/java/com/featurevisor/cli/SchemaSpecValidator.java diff --git a/README.md b/README.md index d736790..2a8112e 100644 --- a/README.md +++ b/README.md @@ -1072,10 +1072,13 @@ Options use kebab case, such as `--project-directory-path`. The camelCase forms ### Test ```bash -mvn -q -pl featurevisor-sdk exec:java -Dexec.mainClass=com.featurevisor.cli.CLI \ +mvn -q install -DskipTests +mvn -q -pl featurevisor-schemas exec:java -Dexec.mainClass=com.featurevisor.cli.CLI \ -Dexec.args="test --project-directory-path=/path/to/featurevisor-project --only-failures" ``` +Running from `featurevisor-schemas` puts the [schemas](#schemas) artifact beside the SDK, so schema specs validate their values as the JavaScript CLI does. From `featurevisor-sdk` alone the other specs run as before, and each schema spec case fails asking for `featurevisor-schemas`. + See [Testing](https://featurevisor.com/docs/testing/) for authoring specs and [Checks](https://featurevisor.com/docs/testing/#checks) for check syntax and operators. Segment specs and checks evaluate ordinary SDK gates with the selected datafile, context, fixed bucket and isolated sticky state. Compiled execution definitions restore missing segments. Existing Target segment specializations remain authoritative. Attribute only segment chains can omit the environment, while segments depending on features or variables require the selected datafile. All transitive root and child check references are preflighted before getters. Synthetic segment gates do not count towards coverage. @@ -1083,7 +1086,7 @@ Segment specs and checks evaluate ordinary SDK gates with the selected datafile, Useful test options: - `--key-pattern=` and `--assertion-pattern=` filter tests. -- `--entity-type=scenario` selects scenarios. `--set=` selects one project set. Omitting `--set` runs all sets. +- `--entity-type=scenario` selects scenarios, and `--entity-type=schema` schema specs. `--set=` selects one project set. Omitting `--set` runs all sets. - `--case=` reruns one expanded case. Copy the opaque ID or rerun command from a failure report. - `--json --pretty` produces an indented JSON report. - `--coverage` reports observed rule and override selections. `--uncovered` lists features and global variables without associated specs. diff --git a/featurevisor-schemas/pom.xml b/featurevisor-schemas/pom.xml index 921c713..a261ad8 100644 --- a/featurevisor-schemas/pom.xml +++ b/featurevisor-schemas/pom.xml @@ -40,6 +40,17 @@ junit-jupiter test + + + info.picocli + picocli + test + + + org.apache.commons + commons-exec + test + @@ -73,6 +84,14 @@ org.codehaus.mojo flatten-maven-plugin + + + org.codehaus.mojo + exec-maven-plugin + + test + + diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/CliSchemaSpecValidator.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/CliSchemaSpecValidator.java new file mode 100644 index 0000000..64b3601 --- /dev/null +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/CliSchemaSpecValidator.java @@ -0,0 +1,32 @@ +package com.featurevisor.schemas; + +import com.featurevisor.cli.SchemaSpecValidator; +import com.featurevisor.sdk.Featurevisor; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** Lets the SDK's CLI run schema specs, found through {@link java.util.ServiceLoader}. */ +public final class CliSchemaSpecValidator implements SchemaSpecValidator { + @Override + public List> validate(Featurevisor f, String schema, Object value) { + Schemas schemas = Schemas.create(f); + try { + List> issues = new ArrayList<>(); + for (SchemaIssue issue : schemas.validate(schema, value).getIssues()) { + // An issue as a test result shows it, without the schema key every issue repeats. + Map described = new LinkedHashMap<>(); + described.put("path", issue.getPath()); + described.put("code", issue.getCode()); + if (issue.getMutation() != null) described.put("mutation", issue.getMutation()); + described.put("message", issue.getMessage()); + described.put("params", issue.getParams()); + issues.add(described); + } + return issues; + } finally { + schemas.close(); + } + } +} diff --git a/featurevisor-schemas/src/main/resources/META-INF/services/com.featurevisor.cli.SchemaSpecValidator b/featurevisor-schemas/src/main/resources/META-INF/services/com.featurevisor.cli.SchemaSpecValidator new file mode 100644 index 0000000..6ac6e9b --- /dev/null +++ b/featurevisor-schemas/src/main/resources/META-INF/services/com.featurevisor.cli.SchemaSpecValidator @@ -0,0 +1 @@ +com.featurevisor.schemas.CliSchemaSpecValidator diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java b/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java index ac4284a..95f7dbf 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java @@ -116,7 +116,7 @@ interface NodeCommand { @Option(names = {"--target"}, arity = "1", description = "Target datafile; repeat for multiple targets") private List targets = new ArrayList<>(); - @Option(names = {"--entity-type", "--entityType"}, description = "Test entity type: feature, segment, variable or scenario") + @Option(names = {"--entity-type", "--entityType"}, description = "Test entity type: feature, segment, variable, scenario or schema") private String entityType; @Option(names = {"--set"}, description = "Project set") @@ -169,8 +169,8 @@ public Integer call() { System.err.println("--n must be a positive integer"); return 1; } - if (entityType != null && !Arrays.asList("feature", "segment", "variable", "scenario").contains(entityType)) { - System.err.println("--entity-type must be feature, segment, variable or scenario"); + if (entityType != null && !Arrays.asList("feature", "segment", "variable", "scenario", "schema").contains(entityType)) { + System.err.println("--entity-type must be feature, segment, variable, scenario or schema"); return 1; } for (String value : Arrays.asList(projectDirectoryPath, environment, feature, variable, set, caseId)) { @@ -490,10 +490,22 @@ private List> getTests(String featurevisorProjectPath, boole if (entityType != null) { rawArguments.add("--entityType=" + entityType); } - String command = "npx featurevisor list --tests --execution-protocol --apply-matrix --execution-metadata --json"; + // Schema specs come too, validated with featurevisor-schemas when it is on the classpath. + String command = "npx featurevisor list --tests --execution-protocol" + + (listsSchemaSpecs ? " --with-schemas" : "") + " --apply-matrix --execution-metadata --json"; rawArguments.addAll(selectionArguments()); if (includeCase && caseId != null) rawArguments.add("--case=" + caseId); - String testsOutput = executeCommandInDirectory(featurevisorProjectPath, command, rawArguments); + String testsOutput; + try { + testsOutput = executeCommandInDirectory(featurevisorProjectPath, command, rawArguments); + } catch (IOException failed) { + // A CLI from before schema specs rejects the option, and has none to list. + String message = String.valueOf(failed.getMessage()); + if (!listsSchemaSpecs || !message.contains("Unknown argument") || !message.contains("with-schemas")) throw failed; + listsSchemaSpecs = false; + testsOutput = executeCommandInDirectory(featurevisorProjectPath, + command.replace(" --with-schemas", ""), rawArguments); + } JsonNode document = objectMapper.readTree(testsOutput); if (!document.isObject()) throw new IOException("Test execution protocol output must be an object"); if (!document.has("kind") || !document.get("kind").isTextual() @@ -1380,8 +1392,7 @@ private String findCaseSet(List reportSets) throws IOException { for (String reportSet : reportSets) { set = reportSet; for (Map test : getTests(rootDirectoryPath, false)) { - String type = test.containsKey("scenario") ? "scenario" : test.containsKey("feature") - ? "feature" : test.containsKey("segment") ? "segment" : "variable"; + String type = testType(test); @SuppressWarnings("unchecked") List> assertions = test.get("assertions") instanceof List ? (List>) test.get("assertions") : Collections.emptyList(); for (Map assertion : assertions) { @@ -1417,8 +1428,7 @@ private void runReportSet(Map report, Map config FeaturevisorLogLevel level = getDiagnosticsLevel(); for (Map test : tests) { - String type = test.containsKey("scenario") ? "scenario" : test.containsKey("feature") - ? "feature" : test.containsKey("segment") ? "segment" : "variable"; + String type = testType(test); if (entityType != null && !entityType.equals(type)) continue; String key = String.valueOf(test.get(type)); @SuppressWarnings("unchecked") Map metadata = test.get("_test") instanceof Map @@ -1454,14 +1464,23 @@ private void runReportSet(Map report, Map config } } + /** The owner a spec names: a feature, segment, variable, scenario or schema. */ + private static String testType(Map test) { + if (test.containsKey("scenario")) return "scenario"; + if (test.containsKey("schema")) return "schema"; + if (test.containsKey("feature")) return "feature"; + if (test.containsKey("segment")) return "segment"; + return "variable"; + } + private void validateNormalizedTests(List> tests) throws IOException { for (Map test : tests) { int discriminators = 0; - for (String candidate : Arrays.asList("feature", "segment", "variable", "scenario")) { + for (String candidate : Arrays.asList("feature", "segment", "variable", "scenario", "schema")) { if (test.containsKey(candidate)) discriminators++; } if (discriminators != 1) { - throw new IOException("Test specification requires exactly one of feature, segment, variable, or scenario"); + throw new IOException("Test specification requires exactly one of feature, segment, variable, scenario, or schema"); } if (!(test.get("assertions") instanceof List) || ((List) test.get("assertions")).isEmpty()) { throw new IOException("Test specification requires assertions"); @@ -1471,8 +1490,7 @@ private void validateNormalizedTests(List> tests) throws IOE private boolean hasExecutableAssertion(List> tests) { for (Map test : tests) { - String type = test.containsKey("scenario") ? "scenario" : test.containsKey("feature") - ? "feature" : test.containsKey("segment") ? "segment" : "variable"; + String type = testType(test); @SuppressWarnings("unchecked") List> assertions = test.get("assertions") instanceof List ? (List>) test.get("assertions") : Collections.emptyList(); for (Map assertion : assertions) { @@ -1498,6 +1516,7 @@ private TestResult executeReportCase(String type, String key, Map()); datafile.setSegments(new LinkedHashMap<>()); } + if (type.equals("schema")) return testSchema(key, assertion, datafile); if (type.equals("segment")) { String error = SegmentEvaluations.validate(key, datafile, definitions); if (error != null) return new TestResult(true, error, 0, List.of(new TestError( @@ -1547,6 +1566,134 @@ private TestResult executeReportCase(String type, String key, Map assertion, DatafileContent datafile) { + List errors = new ArrayList<>(); + StringBuilder messages = new StringBuilder(); + java.util.function.BiConsumer fail = (message, values) -> { + messages.append(" ✘ ").append(message).append("\n"); + errors.add(new TestError(message, "schema", Collections.emptyList(), values[0], values[1], null)); + }; + Map schemas = datafile.getSection("schemas"); + if (schemas == null || !schemas.containsKey(schema)) { + fail.accept("Target \"" + assertion.get("target") + "\" does not deliver schema \"" + schema + + "\". Tag the schema for it, or list it in its includeSchemas.", new Object[] {schema, null}); + return new TestResult(true, messages.toString(), 0, errors); + } + SchemaSpecValidator validator = schemaSpecValidator(); + if (validator == null) { + fail.accept("Schema specs need featurevisor-schemas on the classpath. Run the CLI from the " + + "featurevisor-schemas module, or add com.featurevisor:featurevisor-schemas beside this SDK.", + new Object[] {"featurevisor-schemas", null}); + return new TestResult(true, messages.toString(), 0, errors); + } + Map context = assertion.get("context") instanceof Map + ? (Map) assertion.get("context") : new HashMap<>(); + Featurevisor sdk = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafile(datafile) + .context(context) + .logLevel(FeaturevisorLogLevel.FATAL)); + List> issues; + try { + issues = validator.validate(sdk, schema, assertion.get("value")); + } finally { + sdk.close(); + } + + boolean valid = issues.isEmpty(); + if (assertion.containsKey("expectedToBeValid") && !Objects.equals(assertion.get("expectedToBeValid"), valid)) { + StringBuilder message = new StringBuilder(); + if (valid) { + message.append("Expected the value to be invalid, and it is valid."); + } else { + message.append("Expected the value to be valid, and it has ") + .append(issues.size() == 1 ? "an issue" : issues.size() + " issues").append(":"); + for (Map issue : issues) message.append("\n ").append(compactJson(issue)); + } + fail.accept(message.toString(), new Object[] {assertion.get("expectedToBeValid"), valid}); + } + + if (assertion.get("expectedIssues") instanceof List) { + // Each expected issue pairs with one issue found, and every issue found must be expected. + List> left = new ArrayList<>(issues); + List missing = new ArrayList<>(); + for (Object raw : (List) assertion.get("expectedIssues")) { + Map expected = raw instanceof Map ? (Map) raw : Collections.emptyMap(); + int index = -1; + for (int candidate = 0; candidate < left.size(); candidate++) { + if (matchesIssue(expected, left.get(candidate))) { + index = candidate; + break; + } + } + if (index == -1) missing.add(raw); + else left.remove(index); + } + if (!missing.isEmpty() || !left.isEmpty()) { + StringBuilder message = new StringBuilder("The issues differ from expectedIssues:"); + for (Object issue : missing) message.append("\n missing: ").append(compactJson(issue)); + for (Object issue : left) message.append("\n unexpected: ").append(compactJson(issue)); + fail.accept(message.toString(), new Object[] {assertion.get("expectedIssues"), issues}); + } + } + return new TestResult(!errors.isEmpty(), messages.toString(), 0, errors); + } + + /** Whether an issue has every field an expected issue gives, params by JSON equality. */ + private boolean matchesIssue(Map expected, Map actual) { + if (expected.containsKey("path") && !jsonEquals(expected.get("path"), actual.get("path"))) return false; + for (String field : Arrays.asList("code", "mutation", "message")) { + if (expected.containsKey(field) && !Objects.equals(expected.get(field), actual.get(field))) return false; + } + if (expected.get("params") instanceof Map) { + Map params = actual.get("params") instanceof Map ? (Map) actual.get("params") : Collections.emptyMap(); + for (Map.Entry entry : ((Map) expected.get("params")).entrySet()) { + if (!params.containsKey(entry.getKey()) || !jsonEquals(entry.getValue(), params.get(entry.getKey()))) return false; + } + } + return true; + } + + /** JSON equality, with numbers equal by value, as JavaScript compares them. */ + private boolean jsonEquals(Object left, Object right) { + JsonNode a = objectMapper.valueToTree(left); + JsonNode b = objectMapper.valueToTree(right); + return a.equals((x, y) -> x.isNumber() && y.isNumber() + ? Double.compare(x.doubleValue(), y.doubleValue()) : x.equals(y) ? 0 : 1, b); + } + + private String compactJson(Object value) { + try { + return objectMapper.writeValueAsString(value); + } catch (Exception failed) { + return String.valueOf(value); + } + } + private List preflightExpandedAssertion( Map assertion, String ownerVariable, DatafileContent datafile, Map segmentDefinitions) { @@ -1606,7 +1753,8 @@ private Map reportCase(String type, Map assertio "passed", !result.hasError, "errors", structuredErrors(result.reportErrors, type, authoredAssertionIndex), "rerun", linkedMap( - "command", "mvn -q -pl featurevisor-sdk exec:java -Dexec.mainClass=com.featurevisor.cli.CLI", + "command", "mvn -q -pl " + (schemaSpecValidator() != null ? "featurevisor-schemas" : "featurevisor-sdk") + + " exec:java -Dexec.mainClass=com.featurevisor.cli.CLI", "args", args, "argumentEncoding", "maven-exec" ) @@ -1629,7 +1777,7 @@ private List> structuredErrors(List failures, Str if (failure.type != null) error.put("type", failure.type); List prefix = type.equals("scenario") ? Collections.emptyList() : Arrays.asList("assertions", authoredAssertionIndex); - if (failure.path != null && !failure.path.isEmpty()) { + if (failure.path != null && (!failure.path.isEmpty() || "schema".equals(failure.type))) { error.put("path", appendPath(prefix, failure.path.toArray())); } if (failure.hasExpected) error.put("expected", reportValue(failure.expected)); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/cli/SchemaSpecValidator.java b/featurevisor-sdk/src/main/java/com/featurevisor/cli/SchemaSpecValidator.java new file mode 100644 index 0000000..ed32069 --- /dev/null +++ b/featurevisor-sdk/src/main/java/com/featurevisor/cli/SchemaSpecValidator.java @@ -0,0 +1,19 @@ +package com.featurevisor.cli; + +import com.featurevisor.sdk.Featurevisor; +import java.util.List; +import java.util.Map; + +/** + * Validates a value with a schema of an instance's datafile, for the CLI's schema + * specs. featurevisor-schemas provides it as a service, so the CLI runs schema + * specs when that package is on the classpath, without this SDK depending on it. + */ +public interface SchemaSpecValidator { + /** + * The issues found, each a map of {@code path}, {@code code}, {@code mutation} + * when a mutation set the rule, {@code message} and {@code params}, in the + * order validation found them. Empty when the value is valid. + */ + List> validate(Featurevisor f, String schema, Object value); +} diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/cli/RuntimeCommandTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/cli/RuntimeCommandTest.java index 20e2685..40b2fa2 100644 --- a/featurevisor-sdk/src/test/java/com/featurevisor/cli/RuntimeCommandTest.java +++ b/featurevisor-sdk/src/test/java/com/featurevisor/cli/RuntimeCommandTest.java @@ -184,4 +184,26 @@ void allSetsAndExplicitSetsWithNestedTargets(@TempDir Path project) throws Excep assertEquals(List.of("npx featurevisor config --json"), calls); } } + + @Test + void asksForTestsAgainWithoutSchemaSpecsWhenTheNodeCliPredatesThem() { + List listings = new ArrayList<>(); + CLI.NodeCommand node = (directory, arguments) -> { + if (arguments.contains("config --json")) return "{}"; + if (arguments.contains("list --tests")) { + listings.add(arguments); + if (arguments.contains("--with-schemas")) { + throw new IOException("Command execution failed: {\"error\":{\"code\":\"invalid_cli_arguments\"," + + "\"message\":\"Unknown arguments: with-schemas, withSchemas\",\"details\":{}}}"); + } + return "{\"kind\":\"featurevisor.test-execution\",\"schemaVersion\":1,\"tests\":[]}"; + } + if (arguments.contains("list --segments") || arguments.contains("list --targets")) return "[]"; + return DATAFILE; + }; + assertEquals(0, new CommandLine(new CLI(node)).execute("test", "--json")); + assertEquals(2, listings.size()); + assertTrue(listings.get(0).contains(" --with-schemas")); + assertFalse(listings.get(1).contains("--with-schemas")); + } } From b430f1586bab1ec79bb68eb18902992cc96310bb Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 04:12:47 +0100 Subject: [PATCH 07/21] docs: follow the JavaScript SDK page in the README The README now has the JavaScript SDK page's sections in its order: install, create an instance with an options table, context, flags, variations and variables with typed methods and composition, default values, evaluating everything at once, sticky values, datafile updates with merging and an interval refresh, child instances, events, diagnostics, evaluation details with the reasons table, modules, and schemas from creating an instance to patterns. Examples use the docs' running example, checkout, pricing, buyButton and supportEmail for user-4 in the Netherlands, and the signUp schema, so each page reads like the others in its own language. The README test reads the example under its new heading. --- README.md | 1126 +++++++++++++++++++++++++++-------------------------- 1 file changed, 583 insertions(+), 543 deletions(-) diff --git a/README.md b/README.md index 2a8112e..a8e6a3a 100644 --- a/README.md +++ b/README.md @@ -1,55 +1,64 @@ # Featurevisor Java SDK -Use the Featurevisor Java SDK to evaluate flags, variations and variables in Java applications. +The Featurevisor Java SDK evaluates flags, variations and variables in Java and Kotlin applications, from a datafile it holds in memory. ## Table of contents -- [Installation](#installation) +- [Install](#install) - [Repository](#repository) - [Dependency](#dependency) - [Authentication](#authentication) -- [Initialization](#initialization) - - [Public API](#public-api) - - [Evaluation types](#evaluation-types) +- [Create an instance](#create-an-instance) + - [Concurrency](#concurrency) - [Context](#context) - - [Setting initial context](#setting-initial-context) - - [Setting after initialization](#setting-after-initialization) - - [Replacing existing context](#replacing-existing-context) - - [Manually passing context](#manually-passing-context) -- [Check if enabled](#check-if-enabled) -- [Getting variation](#getting-variation) -- [Getting variables](#getting-variables) - - [Getting feature variables](#getting-feature-variables) - - [Type specific methods](#type-specific-methods) - - [Getting global variables](#getting-global-variables) -- [Getting evaluations](#getting-evaluations) -- [Sticky](#sticky) -- [Setting datafile](#setting-datafile) - - [Merging by default](#merging-by-default) - - [Replacing](#replacing) - - [Loading datafiles on demand](#loading-datafiles-on-demand) - - [Updating datafile](#updating-datafile) - - [Interval-based update](#interval-based-update) -- [Diagnostics](#diagnostics) - - [Levels](#levels) - - [Handler](#handler) +- [Check a flag](#check-a-flag) +- [Get a variation](#get-a-variation) +- [Get a variable](#get-a-variable) + - [Typed methods](#typed-methods) + - [Composed variables](#composed-variables) +- [Default values](#default-values) +- [Evaluate everything at once](#evaluate-everything-at-once) + - [Hand results from server to client](#hand-results-from-server-to-client) +- [Sticky values](#sticky-values) +- [Update the datafile](#update-the-datafile) + - [Merge or replace](#merge-or-replace) + - [Refresh on an interval](#refresh-on-an-interval) +- [Child instances](#child-instances) - [Events](#events) - - [`datafile_set`](#datafile_set) + - [`datafile_set`](#datafile-set) - [`context_set`](#context_set) - [`sticky_features_set`](#sticky_features_set) - [`sticky_variables_set`](#sticky_variables_set) - [`error`](#error) +- [Diagnostics](#diagnostics) + - [Evaluation errors](#evaluation-errors) - [Evaluation details](#evaluation-details) + - [Evaluation reasons](#evaluation-reasons) - [Modules](#modules) - - [Defining a module](#defining-a-module) - - [Registering modules](#registering-modules) -- [Child instance](#child-instance) + - [Dependency evaluations](#dependency-evaluations) + - [Register a module](#register-a-module) + - [Read the datafile from a module](#read-the-datafile-from-a-module) +- [Schemas](#schemas) + - [Create a schemas instance](#create-a-schemas-instance) + - [Validate a value](#validate-a-value) + - [Read the issues](#read-the-issues) + - [Get a handle](#get-a-handle) + - [Read constraints and choices](#read-constraints-and-choices) + - [Read annotations](#read-annotations) + - [Choose the messages](#choose-the-messages) + - [Check in code](#check-in-code) + - [Options from your application](#options-from-your-application) + - [Follow the values typed so far](#follow-the-values-typed-so-far) + - [Validate on the server](#validate-on-the-server) + - [Listen for changes](#listen-for-changes) + - [Patterns](#patterns) - [Close](#close) - [OpenFeature](#openfeature) - [Schemas](#schemas) - [Handles](#handles) - [Messages](#messages) - [Checks in code](#checks-in-code) + - [Patterns](#patterns) - [CLI usage](#cli-usage) - [Test](#test) - [Benchmark](#benchmark) @@ -63,16 +72,12 @@ Use the Featurevisor Java SDK to evaluate flags, variations and variables in Jav -## Installation - -Upgrading an existing application? Follow the [Java migration guide](https://featurevisor.com/docs/migrations/v4/java/). +## Install -In your Java application, update `pom.xml` to add the following: +The SDK is published to GitHub Packages. Add the repository and the dependency to your `pom.xml`: ### Repository -For finding GitHub Package (public package): - ```xml @@ -85,8 +90,6 @@ For finding GitHub Package (public package): ### Dependency -Add the Featurevisor Java SDK as a dependency with your desired version: - ```xml @@ -97,11 +100,11 @@ Add the Featurevisor Java SDK as a dependency with your desired version: ``` -Browse [Java SDK packages](https://github.com/featurevisor/featurevisor-java/packages) +Browse the [Java SDK packages](https://github.com/featurevisor/featurevisor-java/packages) for every version. The SDK supports Java 11 and later. Upgrading an existing application? Follow the [Java migration guide](https://featurevisor.com/docs/migrations/v4/java/). ### Authentication -To authenticate with GitHub Packages, in your `~/.m2/settings.xml` file, add the following: +GitHub Packages needs a token, even for public packages. Generate one with the `read:packages` scope in your [GitHub token settings](https://github.com/settings/tokens), and add it to `~/.m2/settings.xml`: ```xml @@ -121,16 +124,11 @@ To authenticate with GitHub Packages, in your `~/.m2/settings.xml` file, add the ``` -Generate a token with `read:packages` scope in [GitHub token settings](https://github.com/settings/tokens) - -Example applications: - -- [Java application](https://github.com/featurevisor/featurevisor-example-java) -- [Kotlin Android application](https://github.com/featurevisor/featurevisor-example-android) +See the [Java application](https://github.com/featurevisor/featurevisor-example-java) and the [Kotlin Android application](https://github.com/featurevisor/featurevisor-example-android) for complete examples. -## Initialization +## Create an instance -Read a built [datafile](https://featurevisor.com/docs/building-datafiles/) from a local file and pass its content to the SDK. Save this Java 11 example as `Main.java` and place `featurevisor-all.json` in your working directory: +Read a [datafile](https://featurevisor.com/docs/building-datafiles/) and create an instance with it. Save this example as `Main.java`, with `featurevisor-all.json` in your working directory: ```java import com.featurevisor.sdk.Featurevisor; @@ -147,7 +145,7 @@ public class Main { new Featurevisor.FeaturevisorOptions().datafile(datafileContent) ); try { - System.out.println(f.isEnabled("checkout", Map.of("userId", "123"))); + System.out.println(f.isEnabled("checkout", Map.of("userId", "user-4"))); } finally { f.close(); } @@ -155,753 +153,791 @@ public class Main { } ``` -File read and JSON parsing failures propagate to the caller. You can also load the content with Java's HTTP client. Check for a successful HTTP status before passing the response body to the SDK. The following sections cover the available options. - -### Public API - -The main runtime API is `Featurevisor.createFeaturevisor()`: - -```java -import com.featurevisor.sdk.FeaturevisorLogLevel; - -Featurevisor f = Featurevisor.createFeaturevisor( - new Featurevisor.FeaturevisorOptions().datafile(datafileContent) -); -``` +This example closes the instance at once. In a long running application, keep it for every evaluation and close it at shutdown. To fetch a datafile over HTTP instead, check for a successful status before passing the body to `DatafileContent.fromJson`. Every option is optional, so an instance can start without a datafile and [receive one later](#update-the-datafile): -Most applications only need `Featurevisor.createFeaturevisor`, the `Featurevisor` instance type, and `Featurevisor.FeaturevisorOptions`. Public extension and observability types include `FeaturevisorModule`, `FeaturevisorDiagnostic`, and the datafile model types. +| Option | Sets | +| ----------------------------------- | -------------------------------- | +| `datafile`, `datafileString` | The datafile to evaluate | +| `context` | The [instance context](#context) | +| `stickyFeatures`, `stickyVariables` | [Sticky values](#sticky-values) | +| `logLevel`, `onDiagnostic` | [Diagnostics](#diagnostics) | +| `modules` | [Modules](#modules) | -Concurrent evaluations are safe after an instance is configured. Do not call state changing methods such as `setDatafile`, `setContext`, `setStickyFeatures`, `setStickyVariables`, `addModule`, `removeModule`, or `close` concurrently with evaluations or with each other. Apply those changes from a serialized update path. Module, event, and diagnostic callbacks must synchronize mutable state that they capture. +Create one instance and reuse it. On a server that handles many users, give each request a [child instance](#child-instances). -### Evaluation types +### Concurrency -Featurevisor evaluates four kinds of values: - -- [**Flag**](#check-if-enabled) (`boolean`): whether the feature is enabled or not -- [**Variation**](#getting-variation) (`String`): the variation of the feature (if any) -- [**Feature variable**](#getting-feature-variables): a configuration value owned by a feature -- [**Global variable**](#getting-global-variables): a configuration value evaluated independently of a feature - -These evaluations are run against the provided context. +Evaluations are safe from many threads once an instance is set up. Apply changes, such as `setDatafile`, `setContext`, `setStickyFeatures`, `setStickyVariables`, `addModule`, `removeModule` and `close`, from one thread at a time, never during evaluations. Module, event and diagnostic callbacks synchronize any state of their own. ## Context -Contexts are [attribute](https://featurevisor.com/docs/attributes) values you pass to the SDK for evaluating [features](https://featurevisor.com/docs/features) against. - -Conditions compare these attributes using the [operators](https://featurevisor.com/docs/operators/), including `empty` and `notEmpty`. - -Date comparisons with `before` and `after` accept portable timestamp strings, `Instant`, `java.util.Date` (including `java.sql.Timestamp`), `OffsetDateTime` and `ZonedDateTime`. Native values are compared by their instant and truncated to milliseconds without rounding. Both the native written year, where present, and the UTC year must be within 1 to 9999. Explicit native offsets must have a magnitude of at most 14 hours, including any seconds. Offsets within that limit retain their full precision. `Instant` and `java.util.Date` have only an instant, so no offset check applies. `LocalDate` and `LocalDateTime` are not accepted because they do not identify an instant. Invalid values make both operators return `false`. +Context is a plain map of [attribute](https://featurevisor.com/docs/attributes/) values. The instance keeps a context of its own, and each evaluation can add to it. -They are plain maps: +Set it when creating the instance: ```java -Map context = new HashMap<>(); -context.put("userId", "123"); -context.put("country", "nl"); -// ...other attributes +Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafile(datafileContent) + .context(Map.of("country", "nl"))); ``` -### Setting initial context - -Set context when you create the instance: +Add to it later with `setContext`, or replace it by passing `true` as the second argument: ```java -Map initialContext = new HashMap<>(); -initialContext.put("deviceId", "123"); -initialContext.put("country", "nl"); +f.setContext(Map.of("userId", "user-4")); -Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() - .datafile(datafileContent) - .context(initialContext)); +f.setContext(Map.of( + "userId", "user-2", + "country", "nl" +), true); ``` -This is useful for values that don't change too frequently and available at the time of application startup. - -### Setting after initialization - -Add context later: +Context passed to an evaluation is merged over the instance context for that call only: ```java -Map additionalContext = new HashMap<>(); -additionalContext.put("userId", "123"); -additionalContext.put("country", "nl"); +Map context = Map.of( + "userId", "user-4", + "country", "nl" +); -f.setContext(additionalContext); +f.isEnabled("checkout", context); ``` -This will merge the new context with the existing one (if already set). +`getContext()` returns the instance context, and `getContext(Map.of("country", "de"))` shows it merged with extra values without storing them. -### Replacing existing context +Dates compare as portable timestamp strings, `Instant`, `java.util.Date`, `OffsetDateTime` or `ZonedDateTime`, by their instant, truncated to milliseconds. Offsets stay within 14 hours and years within 1 and 9999. `LocalDate` and `LocalDateTime` name no instant, so they are not accepted. -Replace the context by passing `true` as the second argument: +## Check a flag + +`isEnabled` reads a [flag](https://featurevisor.com/docs/flags/). Dutch users have the new `checkout`: ```java -Map newContext = new HashMap<>(); -newContext.put("deviceId", "123"); -newContext.put("userId", "234"); -newContext.put("country", "nl"); -newContext.put("browser", "chrome"); +Map context = Map.of( + "userId", "user-4", + "country", "nl" +); -f.setContext(newContext, true); // replace existing context +if (f.isEnabled("checkout", context)) { + // show the new checkout +} ``` -### Manually passing context +## Get a variation -Pass context to one evaluation without changing the instance context: +`getVariation` returns the [variation](https://featurevisor.com/docs/variations/) of a feature, or `null` if the feature is disabled or has none: ```java -Map context = new HashMap<>(); -context.put("userId", "123"); -context.put("country", "nl"); +String variation = f.getVariation("pricing", context); -boolean isEnabled = f.isEnabled("checkout", context); -String variation = f.getVariation("checkout", context); -String variableValue = f.getVariableString("checkout", "bgColor", context); +if ("treatment".equals(variation)) { + // show the new pricing +} ``` -When manually passing context, it will merge with existing context set to the SDK instance before evaluating the specific value. +For `user-4` it returns `"control"`, and for `user-2` it returns `"treatment"`. -## Check if enabled +## Get a variable -Check whether a feature is enabled: +`getVariable` reads a [feature variable](https://featurevisor.com/docs/variables/#feature-variables) with a feature key and a variable key. For `user-4`, the `netherlands` rule sets the buy button's label to `"Nu kopen"`: ```java -String featureKey = "checkout"; - -boolean isEnabled = f.isEnabled(featureKey); - -if (isEnabled) { - // do something -} +Object label = f.getVariable("buyButton", "label", context); ``` -Pass additional context to one evaluation: +With a context as its second argument, it reads a [global variable](https://featurevisor.com/docs/variables/#global-variables) instead. `supportEmail` returns `"support-nl@example.com"` for `user-4`: ```java -Map additionalContext = new HashMap<>(); -// ...additional context - -boolean isEnabled = f.isEnabled(featureKey, additionalContext); +Object email = f.getVariable("supportEmail", context); ``` -## Getting variation +Two keys mean a feature variable, and one key a global variable. The typed methods below follow the same rule. -Evaluate a feature's [variations](https://featurevisor.com/docs/features/#variations): +Treat returned maps and lists as read only. The SDK can share them with its datafile rather than copy them on every evaluation, so copy a value before changing it, and never change a datafile after passing it to the instance. -```java -String featureKey = "checkout"; +### Typed methods -String variation = f.getVariation(featureKey); +Each typed method returns `null` when the value has a different type, and never converts it. `getVariableInteger` returns `null` for the string `"1"`, and `getVariableBoolean` returns `null` for `"true"`. -if ("treatment".equals(variation)) { - // do something for treatment variation -} else { - // handle default/control variation -} -``` - -Pass additional context to one evaluation: +| Method | Returns | +| ---------------------- | ----------------------------- | +| `getVariableBoolean` | `Boolean` | +| `getVariableString` | `String` | +| `getVariableInteger` | `Integer` | +| `getVariableDouble` | `Double`, whole or fractional | +| `getVariableArray` | `List` | +| `getVariableObject` | `T`, or `Map` | +| `getVariableJSON` | `T`, decoded JSON | +| `getVariableJSONNode` | A Jackson `JsonNode` | ```java -String variation = f.getVariation(featureKey, additionalContext); +Map settings = f.getVariableObject("checkoutSettings", context, null); +// {currency=EUR, paymentMethods=[card]} ``` -## Getting variables - -### Getting feature variables - -Evaluate a feature's [variables](https://featurevisor.com/docs/features/#variables): +For a feature variable, pass a `Class` or a Jackson `TypeReference` to decode it into your own type, and get `null` when it does not decode: ```java -String variableKey = "bgColor"; +ButtonStyle style = f.getVariableObject( + "buyButton", + "style", + context, + ButtonStyle.class +); -String bgColorValue = f.getVariableString(featureKey, variableKey); +List methods = f.getVariableArray( + "checkout", + "paymentMethods", + context, + new TypeReference>() {} +); ``` -Pass additional context to one evaluation: +`getVariableJSONNode` suits a value of unknown shape. A `json` variable whose text does not parse returns `null` from `getVariable`, `getVariableJSON` and `getVariableJSONNode`. -```java -String bgColorValue = f.getVariableString(featureKey, variableKey, additionalContext); -``` +### Composed variables -### Type specific methods +Read a [composed global variable](https://featurevisor.com/docs/variables/#compose-values) like any other global variable. For a string `compose` alias, choose the getter for the source's type, such as `getVariableString` for an alias of `supportEmail`. It returns what the source's own getter returns, including decoded JSON and `null`, with no wrapper or copy. -Next to generic `getVariable()` methods, there are also type specific methods available for convenience: +A composition is evaluated in this order: -```java -f.getVariableBoolean(featureKey, variableKey, context); -f.getVariableString(featureKey, variableKey, context); -f.getVariableInteger(featureKey, variableKey, context); -f.getVariableDouble(featureKey, variableKey, context); -f.getVariableArray(featureKey, variableKey, context); +1. A sticky value for the whole variable, which skips everything after it. +2. Root `conditions`. When they miss, no source is read and no override runs. The result is `disabledValue` when supplied, otherwise `null`, with reason `conditions_unmet`. +3. The sources, with their own sticky values, the context and modules taking part as usual. +4. The [overrides](https://featurevisor.com/docs/variables/#override-composed-values), which run as they do for any global variable. -f.>getVariableObject(featureKey, variableKey, context); -f.getVariableObject(featureKey, variableKey, context); +Compositions have no `defaultValue` or `useDefaultWhenDisabled`. With no override match, the reason is `variable_composed`, and a match reports `variable_override_rule`, with `getVariableOverridePaths()` listing every override that changed the value. Only the outer map of a composition is fresh, so treat what it holds as read only. -f.>getVariableJSON(featureKey, variableKey, context); -f.getVariableJSON(featureKey, variableKey, context); -f.getVariableJSONNode(featureKey, variableKey, context); -``` +Cycles, and chains of more than 256 dependencies, fail the whole evaluation. A thread stack too small for a chain fails it the same way, so getters never throw `StackOverflowError`. -Type specific methods do not coerce values. `getVariableInteger()` returns `null` for the string `"1"`, and boolean getters return `null` for non-boolean values. +## Default values -For strongly typed decoding, additional overloads are available: +Pass `defaultVariationValue` or `defaultVariableValue` in `OverrideOptions` for when an evaluation produces no value, such as a feature missing from the datafile: ```java -import com.fasterxml.jackson.core.type.TypeReference; - -// Array decoding using Class -List items = f.getVariableArray(featureKey, variableKey, context, MyItem.class); - -// Array decoding using TypeReference -List> rows = f.getVariableArray( - featureKey, - variableKey, +Object label = f.getVariable( + "buyButton", + "label", context, - new TypeReference>>() {} + new Featurevisor.OverrideOptions().defaultVariableValue("Buy") ); +``` + +A default counts as given whenever it is set, so `""`, `0`, `false` and `null` are all valid defaults. -// Object decoding using Class -MyConfig config = f.getVariableObject(featureKey, variableKey, context, MyConfig.class); +## Evaluate everything at once -// Object decoding using TypeReference -Map> nested = f.getVariableObject( - featureKey, - variableKey, +`getFeatureEvaluations` evaluates every loaded feature, or only the keys you pass: + +```java +EvaluatedFeatures evaluations = f.getFeatureEvaluations( context, - new TypeReference>>() {} + List.of("checkout", "pricing", "buyButton"), + null ); +// checkout: enabled +// pricing: enabled, variation control +// buyButton: enabled, variation treatment, variables {label: Nu kopen} ``` -If decoding fails for the requested target type, these methods return `null`. - -For dynamic JSON values with unknown shape, use `getVariableJSONNode`: +`getVariableEvaluations` does the same for global variables: ```java -import com.fasterxml.jackson.databind.JsonNode; +Map variables = f.getVariableEvaluations( + context, + List.of("supportEmail", "checkoutSettings"), + null +); +``` -JsonNode node = f.getVariableJSONNode(featureKey, variableKey, context); +Pass `null` as the keys to evaluate them all. To see what is loaded without evaluating anything: -if (node != null && node.isObject()) { - String nested = node.path("key").path("nested").asText(null); -} -``` +- `getFeatureKeys()` lists every feature in the datafile, enabled or not. +- `getVariableKeys()` lists global variables, and `getVariableKeys("buyButton")` lists that feature's variables. +- `hasVariations("pricing")` is `true` when a feature has variations, and `false` for an unknown feature. -If a variable schema type is `json` and the resolved value is a malformed stringified JSON, JSON parsing fails safely and these methods return `null`: +### Hand results from server to client -- `getVariable(...)` -- `getVariableJSONNode(...)` -- `getVariableJSON(...)` +Both results have the shape [sticky values](#sticky-values) take. A server can evaluate once per request and pass the results to its client, so the first render matches what the server saw. The JavaScript SDK's [sticky values](https://featurevisor.com/docs/sdks/javascript/#hand-results-from-server-to-client) read them in a browser. -### Getting global variables +## Sticky values -Global variables use the same overloaded methods as variables inside features. A call with one key evaluates a global variable, while a call with a feature key and variable key evaluates a variable owned by that feature: +Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests: ```java -String message = f.getVariableString("welcomeMessage", context, null); -Object value = f.getVariable("checkoutSettings", context); -Evaluation evaluation = f.evaluateVariable("checkoutSettings", context); +Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .stickyFeatures(Map.of( + "checkout", Map.of("enabled", true), + "pricing", Map.of("enabled", true, "variation", "treatment") + )) + .stickyVariables(Map.of( + "supportEmail", "support@example.com" + ))); ``` -The type specific methods are `getVariableBoolean`, `getVariableString`, `getVariableInteger`, `getVariableDouble`, `getVariableArray`, `getVariableObject`, and `getVariableJSON`. +A sticky feature can also set `variables`. Change sticky values later with `setStickyFeatures` and `setStickyVariables`. Both merge by default, and replace the whole map when the second argument is `true`: -Root conditions and overrides are applied for you. See [Variables](https://featurevisor.com/docs/variables/#global-variables) and [Conditions](https://featurevisor.com/docs/conditions/) for authoring. - -### Conditions and composed variables +```java +f.setStickyFeatures(Map.of( + "checkout", Map.of("enabled", false) +), true); +``` -Conditions combine attribute comparisons, literal segment keys, feature getters and variable comparisons. Arrays imply AND. Logical groups use `and`, `or` and `not`, with NOT negating the AND of its children. Empty expressions are false. Variable paths in generated datafiles are compiled arrays, not authored dotted paths. +Treat sticky maps as read only once given to an instance, and change them only through these methods. -Feature evaluation checks sticky values, force rules, root conditions and traffic rules in that order. Global variables check sticky values and root conditions before sources and overrides. An unmet root returns `conditions_unmet` and exposes `Evaluation.getConditions()`. Disabled variations and feature variables retain their existing disabled reasons. +## Update the datafile -Composed global variables use the ordinary getters: +`setDatafile` gives the instance a newer datafile, parsed or as a JSON string: ```java -Object screen = f.getVariable("checkoutScreen", context); -Object policy = f.getVariable("policyAlias", context); -Evaluation evaluation = f.evaluateVariable("checkoutScreen", context); +boolean accepted = f.setDatafile(datafileContent); ``` -A map composition assembles a fresh outer object with literal properties from feature flags, variations, feature variables and global variables. A string composition aliases one literal global variable key and returns its value directly. Sources use effective context, child sticky state and modules. False, zero, empty strings, arrays and explicit null remain values. JSON sources decode exactly once, even through alias chains. An outer caller default is never forwarded to sources. +It returns `true` when the datafile is accepted, even if nothing changed, and `false` when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through [diagnostics](#diagnostics). -Compositions have no defaultValue or useDefaultWhenDisabled. Root conditions can return disabledValue or null without reading sources or overrides. Whole variable sticky state bypasses composition. Sources are read before runtime overrides, whose mutation operations copy changed paths without modifying sources, siblings or sticky values. Successful composition reports `variable_composed`, or `variable_override_rule` when an override matches. +### Merge or replace -Treat supplied datafiles and returned objects as read only. Copy values before changing them. Composed members and string aliases retain ordinary getter ownership. Only the map's outer object is freshly assembled. +By default, the new datafile is merged into the current one: -Conditions, segments and composition share cycle detection and a combined dependency depth bound of 256. A cycle or exhausted depth fails the complete evaluation through its ordinary error result. A thread stack too small for the chain fails the same way, and getters never throw `StackOverflowError`. A subsequent public call starts a fresh session. +- Its features, segments and global variables replace those with the same keys. +- Definitions it does not contain are kept. +- Its `revision` and `schemaVersion` are taken. -To see which overrides changed a value, read `variableOverridePaths` from `evaluateVariable`. The singular override fields describe the final match. - -## Getting evaluations - -Evaluate all features available in the instance: +Pass `true` to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger: ```java -import com.featurevisor.sdk.EvaluatedFeatures; -import com.featurevisor.sdk.EvaluatedFeature; - -EvaluatedFeatures allEvaluations = f.getFeatureEvaluations(context); - -// Access the evaluations map -Map evaluations = allEvaluations.getValue(); - -System.out.println(evaluations); -// { -// "checkout": { -// "enabled": true, -// "variation": "control", -// "variables": { -// "myVariableKey": "myVariableValue" -// } -// }, -// -// "anotherFeature": { -// "enabled": true, -// "variation": "treatment" -// } -// } +f.setDatafile(datafileContent, true); ``` -This is handy especially when you want to pass all evaluations from a backend application to the frontend. +Merging is what lets one instance hold datafiles for several [targets](https://featurevisor.com/docs/targets/), loaded as each part of the application needs them. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/). + +### Refresh on an interval -Global variables can be evaluated together as well: +Fetch the datafile again every few minutes: ```java -Map variables = f.getVariableEvaluations(context, null, null); +HttpClient client = HttpClient.newHttpClient(); +HttpRequest request = HttpRequest.newBuilder(URI.create(datafileUrl)) + .timeout(Duration.ofSeconds(30)) + .build(); + +ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); +scheduler.scheduleAtFixedRate(() -> { + try { + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + if (response.statusCode() == 200) { + f.setDatafile(response.body(), true); + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } catch (Exception e) { + System.err.println("Could not refresh datafile: " + e.getMessage()); + } +}, 5, 5, TimeUnit.MINUTES); ``` -## Sticky +A failed fetch keeps the previous datafile. `setDatafile` does not throw for an invalid datafile, it reports it through diagnostics. Call `scheduler.shutdownNow()` when you stop, since `close()` does not stop your scheduler. Each accepted update emits [`datafile_set`](#datafile-set). -Set sticky values to take precedence over feature evaluation against the [datafile](https://featurevisor.com/docs/building-datafiles/): +## Child instances -Sticky values belong to an SDK or child instance. Feature sticky values and global variable sticky values are independent. +A server handles many users at once, so give each request a child with its own context: ```java -Map stickyFeatures = new HashMap<>(); - -Map checkoutSticky = new HashMap<>(); -checkoutSticky.put("enabled", true); -checkoutSticky.put("variation", "treatment"); +ChildInstance child = f.spawn(Map.of( + "userId", "user-4", + "country", "nl" +)); -Map checkoutVariables = new HashMap<>(); -checkoutVariables.put("myVariableKey", "myVariableValue"); -checkoutSticky.put("variables", checkoutVariables); +child.isEnabled("checkout"); +``` -stickyFeatures.put("checkout", checkoutSticky); +- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it. +- Sticky values are not inherited. Pass `Featurevisor.SpawnOptions` as the second argument when the child needs some. +- A child has the parent's evaluation methods, plus `getContext`, `setContext`, `setStickyFeatures`, `setStickyVariables`, `on` and `close`. +- `close()` removes the child's listeners, including the ones it registered on its parent. -Map anotherFeatureSticky = new HashMap<>(); -anotherFeatureSticky.put("enabled", false); -stickyFeatures.put("anotherFeatureKey", anotherFeatureSticky); +## Events -Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() - .datafile(datafile) - .stickyFeatures(stickyFeatures) - .stickyVariables(Map.of("welcomeMessage", "Hello"))); -``` +`on` subscribes to an event and returns a `FeaturevisorUnsubscribe`, whose `unsubscribe()` stops it. -Once initialized with sticky features, the SDK will look for values there first before evaluating the targeting conditions and going through the bucketing process. +### `datafile_set` -Set sticky features after initialization: +Emitted for every accepted datafile: ```java -Map stickyFeatures = new HashMap<>(); -// ... build sticky features map +FeaturevisorUnsubscribe subscription = f.on(FeaturevisorEventName.DATAFILE_SET, event -> { + String revision = (String) event.get("revision"); + String previousRevision = (String) event.get("previousRevision"); + Boolean replaced = (Boolean) event.get("replaced"); + List features = (List) event.get("features"); + List variables = (List) event.get("variables"); -f.setStickyFeatures(stickyFeatures, true); // replace existing sticky features -f.setStickyVariables(Map.of("welcomeMessage", "Welcome back"), true); // replace -``` + // evaluate the listed features and variables again +}); -## Setting datafile +subscription.unsubscribe(); +``` -You may also initialize the SDK without passing `datafile`, and set it later on: +`replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`. -```java -f.setDatafile(datafileContent); -``` +### `context_set` -`setDatafile` accepts either a parsed `DatafileContent` or a raw JSON string. All overloads return `true` when the datafile is accepted, including unchanged content, and `false` when the input is rejected or the instance is closed. Rejected input leaves the last accepted datafile in place and reports the existing diagnostic and error event, without a `datafile_set` event. Calls after closing do nothing. Accepted calls still emit `datafile_set`, even when nothing changed. The return value reports acceptance, not whether any features changed. +Emitted by `setContext`, with the new `context` and `replaced`: ```java -boolean accepted = f.setDatafile(datafileContent); +f.on(FeaturevisorEventName.CONTEXT_SET, event -> { + Map context = (Map) event.get("context"); +}); ``` -### Merging by default +### `sticky_features_set` -By default, `setDatafile(datafile)` merges the incoming datafile with the SDK's stored datafile. Incoming top level metadata is used, and incoming segments, features, and global variables override existing entities with the same keys. +Emitted by `setStickyFeatures`, with `features`, every feature that had a sticky value before the call or has one after it, and `replaced`: -Call `setDatafile` with different datafiles to merge their features, segments, and global variables. Use this to [load datafiles on demand](#loading-datafiles-on-demand). +```java +f.on(FeaturevisorEventName.STICKY_FEATURES_SET, event -> { + List features = (List) event.get("features"); +}); +``` -### Replacing +### `sticky_variables_set` -To replace the stored datafile entirely, pass `true`: +Emitted by `setStickyVariables`, with `variables` and `replaced`: ```java -f.setDatafile(datafileContent, true); // replace +f.on(FeaturevisorEventName.STICKY_VARIABLES_SET, event -> { + List variables = (List) event.get("variables"); +}); ``` -### Loading datafiles on demand +### `error` -Merge datafiles for different [targets](https://featurevisor.com/docs/targets/) into the same instance. Here, the two datafile values have already been loaded and validated by your application from the same published release: +Emitted for every diagnostic at `ERROR`: ```java -f.setDatafile(productsDatafile); -f.setDatafile(checkoutDatafile); +f.on(FeaturevisorEventName.ERROR, event -> { + FeaturevisorDiagnostic diagnostic = (FeaturevisorDiagnostic) event.get("diagnostic"); +}); ``` -Use immutable release URLs, check HTTP responses and keep shared dependencies consistent. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/) for the complete loading and refresh flow. - -### Updating datafile +## Diagnostics -Each accepted datafile update emits a [`datafile_set`](#datafile-set) event. Subscribe to react to updates. +The SDK reports what happens during evaluation as diagnostics, at one of five levels: `FATAL`, `ERROR`, `WARN`, `INFO` and `DEBUG`. By default, those at `INFO` and above go to the console with a `[Featurevisor]` prefix. -The triggers for setting the datafile again can be: +`DEBUG` shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later: -- periodic updates based on an interval (like every 5 minutes), or -- reacting to: - - a specific event in your application (like a user action), or - - an event served via websocket or server-sent events (SSE) +```java +Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .logLevel(FeaturevisorLogLevel.DEBUG)); -### Interval-based update +f.setLogLevel(FeaturevisorLogLevel.WARN); +``` -Replace the complete datafile on each refresh so definitions removed upstream are removed from the SDK too. Use merging only when loading partial datafiles intentionally. +To send diagnostics somewhere other than the console, pass a handler: ```java -import java.net.URI; -import java.net.http.HttpClient; -import java.net.http.HttpRequest; -import java.net.http.HttpResponse; -import java.time.Duration; -import java.util.concurrent.Executors; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.TimeUnit; -import com.featurevisor.sdk.DatafileContent; - -// f is the existing Featurevisor instance -HttpClient client = HttpClient.newHttpClient(); -HttpRequest request = HttpRequest.newBuilder(URI.create(datafileUrl)) - .timeout(Duration.ofSeconds(30)) - .build(); -ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); -scheduler.scheduleAtFixedRate(() -> { - try { - HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); - if (response.statusCode() == 200) { - DatafileContent newDatafile = DatafileContent.fromJson(response.body()); - f.setDatafile(newDatafile, true); // replace - } - } catch (InterruptedException e) { - Thread.currentThread().interrupt(); - } catch (Exception e) { - System.err.println("Failed to update datafile: " + e.getMessage()); - } -}, 0, 5, TimeUnit.MINUTES); +Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .onDiagnostic(diagnostic -> { + // send diagnostic.getLevel(), getCode(), getMessage() and getDetails() to your observability system + })); ``` -Call `scheduler.shutdownNow()` when your application shuts down. +Every diagnostic has a level, a code, a message and a details map. Values about an evaluation, such as `featureKey`, `variableKey`, `reason` and `evaluation`, are in the details. The module, module name and original error say where an error came from, when known. A handler that throws stops neither other handlers nor evaluations. -## Diagnostics +### Evaluation errors -By default, Featurevisor reports diagnostics to the console for `info` level and above with a `[Featurevisor]` prefix. +`conditions_parse_error` is an `ERROR` diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during `setDatafile` for v3 datafiles. Its details contain `conditions` with the raw string, `entityType` and `entityKey`. -### Levels +The whole malformed selector evaluates to `false`, even under `not`, while other entities keep working and `setDatafile` returns `true` for an otherwise valid datafile. A malformed root gate is unmet and reports `conditions_unmet`. -Available diagnostic levels are `FATAL`, `ERROR`, `WARN`, `INFO`, and `DEBUG`. +Dependency cycles fail the whole evaluation with reason `error`. SDK evaluation errors return the ordinary false or `null` result, and other entities keep working. -Set the level during initialization or update it afterwards: +## Evaluation details -```java -Featurevisor f = Featurevisor.createFeaturevisor( - new Featurevisor.FeaturevisorOptions().logLevel(FeaturevisorLogLevel.DEBUG) -); +The `evaluate` methods return how a value was reached, not only the value: -f.setLogLevel(FeaturevisorLogLevel.INFO); +```java +f.evaluateFlag("checkout", context); +f.evaluateVariation("pricing", context); +f.evaluateVariable("buyButton", "label", context); +f.evaluateVariable("supportEmail", context); ``` -### Handler +For `user-4`, `evaluateFlag` returns an `Evaluation` with these getters answering: + +| Getter | Value | +| ------------------ | ------------------- | +| `getType()` | `"flag"` | +| `getFeatureKey()` | `"checkout"` | +| `getReason()` | `"rule"` | +| `getBucketKey()` | `"user-4.checkout"` | +| `getBucketValue()` | `89312` | +| `getRuleKey()` | `"netherlands"` | +| `getEnabled()` | `true` | + +Every evaluation has a type and a reason. The others are `null` unless they apply: + +- `getFeatureKey()`, `null` for global variables +- `getBucketKey()` and `getBucketValue()`, from 0 to 100,000, and the `getRuleKey()` that matched +- `getEnabled()`, `getVariation()` and `getVariationValue()` +- `getVariableKey()`, `getVariableValue()`, `getVariableSchema()` and `getVariable()`, the global variable's definition +- `getVariableOverrideKey()` and `getVariableOverrideIndex()` when a keyed override matched, and `getVariableOverridePath()` for a nested one +- `getVariableOverridePaths()`, every override path matched in order, for [accumulating overrides](https://featurevisor.com/docs/mutations/#accumulate-overrides). The singular getters describe the last match +- `getConditions()` when a [root gate](https://featurevisor.com/docs/conditions/) stopped the evaluation +- `getError()` when evaluation failed + +### Evaluation reasons + +[Test specs](https://featurevisor.com/docs/testing/) can assert them. + +| Reason | Meaning | +| ----------------------------- | -------------------------------------------------------------------------------- | +| `feature_not_found` | The feature is not in the datafile | +| `disabled` | The feature is disabled | +| `no_variations` | A variation was requested from a feature without variations | +| `variation_disabled` | A disabled feature returned its `disabledVariationValue` | +| `variable_not_found` | The feature variable or global variable is not in the datafile | +| `variable_default` | The variable returned its default value | +| `variable_composed` | A global variable read its composition sources with no override match | +| `variable_disabled` | A disabled feature returned the variable's disabled value | +| `variable_override_variation` | A feature variable override matched inside a variation | +| `variable_override_rule` | A feature variable override or global variable override matched | +| `conditions_unmet` | Root conditions did not match. See `getConditions()` | +| `no_match` | No rule, allocation or variation matched, or the bucket fell outside the rollout | +| `forced` | A `force` entry supplied the result | +| `sticky` | A sticky value supplied the result | +| `rule` | A matching rule supplied the result | +| `allocated` | Bucketing allocated the result | +| `error` | Evaluation failed. See `getError()` | + +## Modules -Use `onDiagnostic` to send structured diagnostics to your observability system: +A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional: ```java -Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() - .logLevel(FeaturevisorLogLevel.INFO) - .onDiagnostic(diagnostic -> { - System.out.println(diagnostic.getLevel() + ": " + diagnostic.getCode()); - })); +FeaturevisorModule auditModule = new FeaturevisorModule("audit") + .setup(api -> { + api.onDiagnostic(diagnostic -> { + // diagnostics at this module's own level + }); + + api.reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.INFO) + .code("module_ready") + .message("Ready for revision " + api.getRevision())); + }) + .beforeEvaluation(options -> { + // type, feature key, variable key and context + Map context = new HashMap<>(options.getContext()); + context.put("plan", "paid"); + return options.copy().context(context); + }) + .afterEvaluation((evaluation, options) -> { + // log evaluation.getError() when the reason is error + return evaluation; + }) + .bucketKey(options -> options.getBucketKey()) + // between 0 and 100,000 + .bucketValue(options -> options.getBucketValue()) + .close(() -> { + // clean up when the instance closes + }); ``` -Generated datafiles use schemaVersion `"4"`. Schema `"2"` selectors normalize eagerly when accepted, while schema `"4"` entities normalize on first read. Partial updates invalidate only incoming entities. Replacement clears all entity caches. Legacy compatibility conversion does not change caller objects or the informational version metadata. +`beforeEvaluation` and `afterEvaluation` run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a feature key is a global one. -Malformed stringified conditions fail only their complete selector, including through NOT or segment aliases, without rejecting the datafile. `conditions_parse_error` is reported at error level once per selector per incoming entity load. Its details are exactly `conditions`, `entityType` and `entityKey`. Eager diagnostics run after storage, and lazy diagnostics run after caching, so callbacks may safely reenter getters. +The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress. -Every diagnostic has `level`, `code`, `message`, and an object shaped `details` map. Optional `module`, `moduleName`, and `originalError` fields describe provenance. Evaluation metadata belongs in `details`. +If `setup` throws, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports `module_setup_error`, and calls its `close` if it has one. -Diagnostic handlers are isolated from SDK behaviour. An exception in a handler does not stop other handlers or evaluations. +### Dependency evaluations -## Events +[Conditions](https://featurevisor.com/docs/conditions/) and [composition members](https://featurevisor.com/docs/variables/#compose-values) are evaluated through modules too. Their options answer `getDependencyOf()`, naming the requesting evaluation by type, feature key and variable key. `getDependencyPurpose()` is `condition` for an eligibility check and `composition` for a consumed member value. Direct calls have neither. -Subscribe to SDK events to respond to context, sticky state and datafile changes. +When tracking consumed evaluations, skip eligibility checks, not every read with a requester, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context. -Subscribe to instance lifecycle events: +### Register a module -### `datafile_set` +Pass modules when creating the instance, or add them later: ```java -FeaturevisorUnsubscribe unsubscribe = f.on(FeaturevisorEventName.DATAFILE_SET, (event) -> { - String revision = (String) event.get("revision"); // new revision - String previousRevision = (String) event.get("previousRevision"); - Boolean revisionChanged = (Boolean) event.get("revisionChanged"); // true if revision has changed +Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .modules(List.of(auditModule))); - // list of feature keys that have new updates, - // and you should re-evaluate them - @SuppressWarnings("unchecked") - List features = (List) event.get("features"); +Runnable remove = f.addModule(trackingModule); - @SuppressWarnings("unchecked") - List variables = (List) event.get("variables"); +// later +remove.run(); +f.removeModule("audit"); +``` - // handle here -}); +### Read the datafile from a module -// stop listening to the event -unsubscribe.unsubscribe(); -``` +A package, such as [schemas](#schemas), reads the datafile through the API `setup` receives: + +- `getEntry(section, key)` returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such as `schemas`. Treat it as read only. `getEntryKeys(section)` lists a section's keys. +- `matchConditions(conditions, context, options)` answers the package's own conditions with the instance's engine, segments and feature leaves included. `MatchConditionsOptions` readers answer leaves only the package knows, such as `input`. +- `evaluate(new PackageEvaluationRequest(type, key).context(context), scope -> ...)` evaluates the package's own entry as a getter evaluates a flag. Every module's `beforeEvaluation` runs first, with `getType()` and `getKey()` naming the entry, and the conditions the callback answers with `scope.matchConditions(conditions, readers)` read the context the modules leave, in one dependency session. -The `features` and `variables` arrays contain directly changed entities and their transitive dependants through conditions, segments and composition, including removed dependencies. +Feature and variable leaves reach modules as dependencies, naming the package's entry as their requester. A module with no evaluation callbacks, such as a package's, costs evaluations nothing. -- added, or -- updated, or -- removed +## Schemas -compared to the previous datafile content that existed in the SDK instance. +Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. -### `context_set` +### Create a schemas instance -```java -FeaturevisorUnsubscribe unsubscribe = f.on(FeaturevisorEventName.CONTEXT_SET, (event) -> { - Boolean replaced = (Boolean) event.get("replaced"); // true if context was replaced - @SuppressWarnings("unchecked") - Map context = (Map) event.get("context"); // the new context +They are a separate artifact, released with the same version as the SDK: - System.out.println("Context set"); -}); +```xml + + com.featurevisor + featurevisor-schemas + 5.0.0 + ``` -### `sticky_features_set` +Create it from the SDK instance. Call it `s`, as the SDK instance is `f`: ```java -FeaturevisorUnsubscribe unsubscribe = f.on(FeaturevisorEventName.STICKY_FEATURES_SET, (event) -> { - Boolean replaced = (Boolean) event.get("replaced"); // true if sticky features got replaced - @SuppressWarnings("unchecked") - List features = (List) event.get("features"); // list of all affected feature keys +import com.featurevisor.schemas.Schemas; - System.out.println("Sticky features set"); -}); +Schemas s = Schemas.create(f); ``` -### `sticky_variables_set` +It holds no copy of the schemas. Every call reads the datafile `f` has now, so a [new datafile](#update-the-datafile) applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to share between threads. + +### Validate a value ```java -FeaturevisorUnsubscribe unsubscribe = f.on(FeaturevisorEventName.STICKY_VARIABLES_SET, (event) -> { - @SuppressWarnings("unchecked") - List variables = (List) event.get("variables"); -}); -``` +Map signUp = Map.of( + "email", "user-1@example.com", + "displayName", "A", + "country", "nl" +); -### `error` +ValidationResult result = s.validate("signUp", signUp); -```java -FeaturevisorUnsubscribe unsubscribe = f.on(FeaturevisorEventName.ERROR, (event) -> { - FeaturevisorDiagnostic diagnostic = (FeaturevisorDiagnostic) event.get("diagnostic"); - System.err.println(diagnostic.getMessage()); -}); +if (!result.isValid()) { + // show result.getIssues() beside the form's fields +} ``` -The `error` event is emitted for diagnostics whose level is `ERROR`. +- `s.validate(key, value)` returns a `ValidationResult` with the value itself and its issues. It never coerces, fills defaults or strips keys. +- `s.isValid(key, value)` returns a boolean. +- `s.parse(key, value)` returns the value, or throws a `SchemaValidationException`, for a server or a script that wants a value or a stop. +- All three take a context as a third argument, merged over the instance's, for the [conditions](https://featurevisor.com/docs/schemas/#read-the-context) a schema's rules read. +- A validation runs as the schema's own evaluation, so a [module](#modules)'s `beforeEvaluation` sees it, with type `schema` and the schema's key, and context the module adds reaches every condition, as it does for flags. +- `s.getKeys()` lists the schemas the datafile has, and `s.has(key)` says whether it has one. -## Evaluation details +A value can be maps, lists, strings, numbers, booleans and `null`, a Jackson `JsonNode`, or any object Jackson can convert, such as a request class with getters. -Inspect how variations and variables are evaluated against a context: +A key the datafile does not have fails closed, with one `schemaNotFound` issue, and a `schema_not_found` [diagnostic](#diagnostics) at `WARN`, once per key. -```java -// flag -Evaluation evaluation = f.evaluateFlag(featureKey, context); +### Read the issues + +Every issue has a message, a path of object keys and list indices, the code of the rule that failed, its params, and the schema validated. `issue.getField()` gives its path as a form names a field, such as `items.0.name`. + +Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a [title](https://featurevisor.com/docs/schemas/#title-the-fields) carries it in its `title` param, and one whose rule a [mutation](https://featurevisor.com/docs/schemas/#mutations) set names it in `getMutation()`. + +| Code | Raised when | +| ---------------------------------- | --------------------------------------------------------------------- | +| `type` | The value has another type | +| `const`, `enum` | The value is not one allowed | +| `minimum`, `maximum` | A number is out of range | +| `minLength`, `maxLength` | A string is too short or too long | +| `pattern`, `format` | A string has the wrong shape | +| `minItems`, `maxItems` | A list has too few or too many items | +| `uniqueItems` | A list repeats an item | +| `required`, `additionalProperties` | A key is missing, or there is one it does not allow | +| `oneOf` | No branch matches, or more than one does | +| `refine` | An `issues` entry matches, or a [check in code](#check-in-code) fails | +| `refineError` | A check in code throws, or the schema itself cannot be applied | +| `schemaNotFound` | The datafile has no such schema or field | + +`result.flatten()` groups the messages by field, in the shape of Zod's `flattenError`, and so does `flatten()` on a `SchemaValidationException`, for an error response. -// variation -Evaluation evaluation = f.evaluateVariation(featureKey, context); +### Get a handle -// variable -Evaluation evaluation = f.evaluateVariable(featureKey, variableKey, context); +`s.get(key)` gives the schema's handle: -// global variable -Evaluation evaluation = f.evaluateVariable(variableKey, context); +```java +SchemaHandle signUp = s.get("signUp"); ``` -The returned `Evaluation` exposes the following properties: +A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. -- `featureKey`: the feature key -- `reason`: the reason how the value was evaluated +| Member | What it is | +| ---------------------------------------------------- | ------------------------------------------------------------------------- | +| `validate`, `isValid`, `parse` | As on `s`, without the key | +| `validateAsync` | Validation as a `CompletableFuture`, for [checks in code](#check-in-code) | +| `at(path)` | The handle of one field, such as `at("displayName")` | +| `getFields()`, `getFieldKeys()` | An object's fields' handles and names, in [order](#read-annotations) | +| `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, [below](#read-constraints-and-choices) | +| `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, and one of them by value | +| `getKind()` | What its rules make the field, such as `FieldKind.SELECT` | +| `getAnnotations()` | Its [annotations](#read-annotations) | +| `withInput(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | +| `getReads()` | The fields its rules' conditions read | +| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | +| `getKey()`, `getPath()`, `getName()` | The schema's key, and the field's path and own name | -And optionally these properties depending on whether you are evaluating a feature variation or a variable: +`at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. -- `bucketValue`: the bucket value between 0 and 100,000 -- `ruleKey`: the rule key -- `error`: the error object -- `enabled`: if feature itself is enabled or not -- `variation`: the variation object -- `variationValue`: the variation value -- `variableKey`: the variable key -- `variableValue`: the variable value -- `variableSchema`: the feature variable schema -- `variable`: the global variable definition -- `conditions`: the unmet root expression -- `variableOverrideIndex`, `variableOverrideKey`, `variableOverridePath`, `variableOverridePaths`: matched override provenance +### Read constraints and choices -## Modules +`getConstraints()` are named after HTML attributes: -The before evaluation and after evaluation phases each use the module membership at the start of that phase. Where an evaluation uses bucketing, the bucket key and bucket value phases each use their own starting membership. Adding or removing a module during a phase does not change the iteration already in progress. The next phase uses the membership then installed. A module added before the after phase can receive after callbacks for evaluations already in progress, even if it did not receive their before callbacks. A module removed before the after phase receives no after callback. +```java +FieldConstraints constraints = signUp.at("displayName").getConstraints(); +constraints.isRequired(); // true +constraints.getMinLength(); // 2 +constraints.getMaxLength(); // 40 -Modules allow you to intercept the evaluation process and customize it further as per your needs. +constraints.toAttributes(); +// {required=true, minlength=2, maxlength=40}, for a template +``` -`beforeEvaluation` and `afterEvaluation` run in registration order for feature and global variable evaluations. Condition and composition reads use the same complete module pipeline, and transformed defaults are preserved. One pair surrounds a complete accumulating evaluation, not each mutation operation. +- `isRequired()`, when the key is required, so an input left empty fails +- `getMinLength()` and `getMaxLength()`, from the same rules on a string +- `getMin()` and `getMax()`, from `minimum` and `maximum` on a number +- `getStep()` of 1, for an `integer` +- `isMultiple()`, for a list, such as a multiple select -Module options expose `getDependencyOf()` for an internal getter read. It identifies the immediate requester by type and optional feature and variable keys. `getDependencyPurpose()` is `condition` for eligibility checks or `composition` for consumed values. Application calls, including an independent public getter invoked from a module, have neither marker. Repeated equivalent internal reads can be memoized within one public call, separately for each purpose and requester. +`getOptions()` lists a field's choices in the order of its rules, each with what its [annotations](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `option(value)` finds one, for showing a value saved earlier: -Treat sticky maps and their nested values as read only after passing them to an instance or module. Use sticky setters or return replacement maps from a module to change them. Mutating an existing map in place is not supported. +```java +SchemaHandle country = signUp.at("country"); -Modules should return the same result for the same input during one evaluation. Pass values that change through context. +country.getOptions(); // nl, de and be, each a SchemaOption +country.option("nl").getTitle(); // "Netherlands" +country.option("fr"); // null +``` -### Defining a module +A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `getKind()` answers the switch every generic form writes, from the field's rules alone: `TEXT`, `DATE_TIME`, `VERSION`, `NUMBER`, `BOOLEAN`, `SELECT`, `MULTISELECT`, `OBJECT` or `LIST`. Your own annotation, such as `input: select`, still wins over it. -A module is a `FeaturevisorModule` with a unique `name` and optional lifecycle functions: +### Read annotations -If `setup` throws, the module is not registered. Featurevisor removes subscriptions created during setup, reports `module_setup_error`, and calls `close` when present. +A handle's `getAnnotations()` are its node's own, and `getFields()` gives an object's fields in its `order`: ```java -FeaturevisorModule myCustomModule = new FeaturevisorModule("my-custom-module") - .setup(api -> { - System.out.println("Current revision: " + api.getRevision()); - }) +signUp.getAnnotations().get("title"); // "Create your account" - // before evaluation - .beforeEvaluation(options -> { - Map context = new HashMap<>(options.getContext()); - context.put("someAdditionalAttribute", "value"); - return options.copy().context(context); - }) +signUp.getFields().stream().map(SchemaHandle::getPath).toList(); +// [displayName, email, country] +``` - // configure bucket key - .bucketKey(options -> { - String bucketKey = options.getBucketKey(); - return bucketKey; - }) +Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. - // configure bucket value (between 0 and 100,000) - .bucketValue(options -> { - int bucketValue = options.getBucketValue(); - return bucketValue; - }) +### Choose the messages - // after evaluation - .afterEvaluation((evaluation, options) -> evaluation) +`SchemasOptions` words every schema's issues, per code, as a template or a `SchemaMessage`: - // called by f.close() - .close(() -> { - // clean up resources - }); +```java +Schemas s = Schemas.create(f, new SchemasOptions() + .message("required", "This field is required")); ``` -The API `setup` receives also reads a datafile's sections, the top level keys besides Featurevisor's own whose values are objects, such as `schemas`. `getEntry(section, key)` returns an entry as stored, so treat it as read only, and `getEntryKeys(section)` lists a section's keys. `matchConditions(conditions, context, options)` answers a package's own conditions with the instance's engine, segments and feature leaves included, and `MatchConditionsOptions.reader` answers leaves only the package knows, such as `input`. `evaluate(new PackageEvaluationRequest(type, key).context(context), scope -> ...)` evaluates a package's own entry as a getter evaluates a feature: every module's `beforeEvaluation` runs first, with `getType()` and `getKey()` naming the entry, and the conditions the callback answers with `scope.matchConditions(conditions, readers)` read the context the modules leave, in one dependency session. This is how the [schemas](#schemas) artifact reads its schemas. +`HandleOptions.message(field, code, template)` on `s.get` words one form. For each issue, the first of these that words it wins: + +1. A check in code's own message, then the form's. +2. The schema's own, and then the `message` of its [issues](https://featurevisor.com/docs/schemas/#issues) entry. +3. The application's, from `SchemasOptions`. +4. The default, in English. -### Registering modules +A `translator` on `SchemasOptions` gets each issue, with the message chosen, and returns what the issue says, or `null` to keep it. Keep the text in your translation system, and let schemas and messages hold keys, such as `errors.required`, which the translator turns into text. -Register modules when you create the instance: +### Check in code + +Some checks need your application, such as whether a display name is taken. Give them to a handle with `HandleOptions.refine`, each a `Refinement` with a key, a path, a check and a message: ```java -List modules = new ArrayList<>(); -modules.add(myCustomModule); +SchemaHandle signUp = s.get("signUp", new HandleOptions() + .refine(Refinement.of("nameAvailable", "displayName", + (displayName, info) -> names.isAvailable((String) displayName)) + .message("That display name is taken"))); -Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() - .datafile(datafile) - .modules(modules)); +ValidationResult result = signUp.validate(value); ``` -Or after initialization: +- A check gets the value at its path, and a `CheckInfo` with the whole input and the context, where `info.read("country")` reads another field. It returns `true` when the value passes. +- It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. +- Its issue has code `refine` and the `refine` param `"nameAvailable"`, with the field's title. A check that throws gives `refineError`, and validation fails closed. +- `Refinement.async` takes a check returning a `CompletionStage`. `validate` waits for it, and `validateAsync` returns a `CompletableFuture` instead. + +### Options from your application + +Some lists only your application can answer for, such as cities for a `city` field. Give a handle an `OptionSource` with `HandleOptions.optionSource`, with a key, a path, and a `search`, a `lookup` or both: ```java -Runnable removeModule = f.addModule(myCustomModule); +SchemaHandle signUp = s.get("signUp", new HandleOptions() + .optionSource(OptionSource.of("cities", "city") + .reads("country") + .search((query, info) -> cities.search((String) info.read("country"), query)) + .lookup((city, info) -> cities.find((String) info.read("country"), (String) city)) + .message("Choose a city from the list"))); -// removeModule.run(); -// or: -f.removeModule("my-custom-module"); +SchemaHandle city = signUp.withInput(Map.of("country", "nl")).at("city"); + +List suggestions = city.search("am").join(); +// Amsterdam and Amersfoort ``` -Modules receive an API during `setup` and can subscribe to diagnostics or report their own: +- `search` returns choices shaped like `getOptions()`, or values alone. A handle's `search` passes it the values given to `withInput`, so the cities follow the country. `canSearch()` says whether a field has one. +- `lookup` returns the choice for a value, `true` when it carries nothing more, or `null` when there is none. A handle's `lookup(value)` returns the schema's own choice first, then the source's. +- Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by its message. `searchAsync` and `lookupAsync` take sources that answer later. + +### Follow the values typed so far + +A handle's constraints and choices describe the schema's own rules, which no condition changes. `withInput(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen: ```java -FeaturevisorModule module = new FeaturevisorModule("diagnostic-module") - .setup(api -> { - Runnable unsubscribe = api.onDiagnostic(diagnostic -> { - // observe diagnostics from the SDK and other modules - }); +Map values = Map.of( + "accountType", "business", + "country", "nl" +); - api.reportDiagnostic(new FeaturevisorDiagnostic() - .level(FeaturevisorLogLevel.WARN) - .code("custom_module_warning") - .message("Something notable happened")); - }); +signUp.at("taxId").getConstraints().isRequired(); // false +signUp.withInput(values).at("taxId").getConstraints().isRequired(); // true ``` -## Child instance +Every member follows the input, at every depth. `getReads()` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. + +### Validate on the server -A child snapshots the parent keys that exist when it is spawned. Child values win for those keys. Parent keys introduced later are still inherited. Calling `close()` removes both child-owned listeners and subscriptions delegated to the parent. +`parse` answers a request with a value or a `SchemaValidationException`, whose `flatten()` gives the issues by field: -When dealing with purely client-side applications, it is understandable that there is only one user involved, like in browser or mobile applications. +```java +@PostMapping("/sign-up") +public ResponseEntity signUp(@RequestBody Map body) { + try { + Object value = s.parse("signUp", body); + return ResponseEntity.ok(accounts.create(value)); + } catch (SchemaValidationException error) { + return ResponseEntity.badRequest().body(error.flatten()); + } +} +``` -But when using Featurevisor SDK in server-side applications, where a single server instance can handle multiple user requests simultaneously, it is important to isolate the context for each request. +A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree. -That's where child instances come in handy: +### Listen for changes -```java -Map childContext = new HashMap<>(); -childContext.put("userId", "123"); +`subscribe` calls back when a new datafile changes the schema, through a schema it references too, and returns a `FeaturevisorUnsubscribe` that stops it: -ChildInstance childF = f.spawn(childContext); +```java +FeaturevisorUnsubscribe stop = s.get("signUp").at("country") + .subscribe(() -> renderChoices()); ``` -Pass the child instance to the request handler to evaluate features for that user: +A datafile whose schema is unchanged calls nothing. `s.close()` stops every listener the instance started and removes its module from the Featurevisor instance. -```java -boolean isEnabled = childF.isEnabled("checkout"); -String variation = childF.getVariation("checkout"); -String variableValue = childF.getVariableString("checkout", "bgColor"); -``` - -Similar to parent SDK, child instances also support several additional methods: - -- `setContext` -- `setStickyFeatures` -- `setStickyVariables` -- `evaluateFlag` -- `isEnabled` -- `evaluateVariation` -- `getVariation` -- `evaluateVariable` -- `getVariable` -- `getVariableBoolean` -- `getVariableString` -- `getVariableInteger` -- `getVariableDouble` -- `getVariableArray` -- `getVariableObject` -- `getVariableJSON` -- `getVariableJSONNode` -- `getFeatureEvaluations` -- `getVariableEvaluations` -- `on` -- `close` +### Patterns + +Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. ## Close -Both primary and child instances support a `.close()` method, that removes forgotten event listeners (via `on` method) and cleans up any potential memory leaks. +`close()` removes event listeners and closes modules, on the instance and on a child: ```java f.close(); @@ -937,10 +973,10 @@ var api = OpenFeatureAPI.getInstance(); api.setProviderAndWait(provider); var client = api.getClient(); -boolean enabled = client.getBooleanValue("checkout", false, new ImmutableContext("user-123")); +boolean enabled = client.getBooleanValue("checkout", false, new ImmutableContext("user-4")); ``` -Use `checkout` for a flag, `checkout:variation` for its variation, `checkout:title` for its `title` variable, and `variable:welcomeMessage` for a global variable. Boolean variables use the boolean resolver. Lists, structures, and JSON variables use the object resolver. +Use `checkout` for a flag, `checkout:variation` for its variation, `buyButton:label` for a feature variable, and `variable:supportEmail` for a global variable. Boolean variables use the boolean resolver. Lists, structures, and JSON variables use the object resolver. OpenFeature's targeting key maps to `userId` by default. `targetingKeyField`, `keySeparator`, `variationKey`, and `globalVariablePrefix` on `FeaturevisorOpenFeatureProvider.Options` can customize the mapping. The global variable prefix defaults to `variable` and cannot contain the configured separator. @@ -1124,11 +1160,15 @@ The Java CLI also accepts `--variation` or `--variable=` to assess a variat -The aggregate evaluation reference has moved to [Getting evaluations](#getting-evaluations). + + +The aggregate evaluation reference has moved to [Evaluate everything at once](#evaluate-everything-at-once). -The sticky state reference has moved to [Sticky](#sticky). + + +The sticky state reference has moved to [Sticky values](#sticky-values). ## Development of this package From c242bac999de5a58d095e4a0a4f6327547c972df Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 14:40:21 +0100 Subject: [PATCH 08/21] feat: changed keys in context_set and segments in datafile_set context_set details now carry keys, the top level keys whose values changed, compared by value: numbers by numeric value, so an Integer and a Double holding 30 are the same though a Boolean is never a number, maps key by key and lists and arrays item by item, with a map or list given again as the same object counted as changed. A merge compares only the keys it carries, a replace every key of either context, and a child its own context. The keys are worked out only when a listener or a debug diagnostic receiver reads them. datafile_set details now carry segments, the segments whose definitions were added, changed or, on replace, removed, which the SDK already worked out to find the features and variables they affect. conformance/sdk-events.json pins both, as in JavaScript, and the README documents them as the JavaScript page does. Its contents list links datafile_set by GitHub's anchor. --- README.md | 36 +- conformance/sdk-events.json | 1104 +++++++++++++++++ .../com/featurevisor/sdk/ChildInstance.java | 5 + .../com/featurevisor/sdk/ContextKeys.java | 118 ++ .../java/com/featurevisor/sdk/Emitter.java | 5 + .../java/com/featurevisor/sdk/Events.java | 3 + .../com/featurevisor/sdk/Featurevisor.java | 8 + .../sdk/EventsConformanceTest.java | 147 +++ .../sdk/StatefulConformanceTest.java | 8 +- 9 files changed, 1428 insertions(+), 6 deletions(-) create mode 100644 conformance/sdk-events.json create mode 100644 featurevisor-sdk/src/main/java/com/featurevisor/sdk/ContextKeys.java create mode 100644 featurevisor-sdk/src/test/java/com/featurevisor/sdk/EventsConformanceTest.java diff --git a/README.md b/README.md index a8e6a3a..5e42967 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ The Featurevisor Java SDK evaluates flags, variations and variables in Java and - [Refresh on an interval](#refresh-on-an-interval) - [Child instances](#child-instances) - [Events](#events) - - [`datafile_set`](#datafile-set) + - [`datafile_set`](#datafile_set) - [`context_set`](#context_set) - [`sticky_features_set`](#sticky_features_set) - [`sticky_variables_set`](#sticky_variables_set) @@ -467,9 +467,11 @@ Emitted for every accepted datafile: FeaturevisorUnsubscribe subscription = f.on(FeaturevisorEventName.DATAFILE_SET, event -> { String revision = (String) event.get("revision"); String previousRevision = (String) event.get("previousRevision"); + Boolean revisionChanged = (Boolean) event.get("revisionChanged"); Boolean replaced = (Boolean) event.get("replaced"); List features = (List) event.get("features"); List variables = (List) event.get("variables"); + List segments = (List) event.get("segments"); // evaluate the listed features and variables again }); @@ -477,18 +479,44 @@ FeaturevisorUnsubscribe subscription = f.on(FeaturevisorEventName.DATAFILE_SET, subscription.unsubscribe(); ``` -`replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`. +`replaced` says whether the datafile replaced the previous one or merged into it. `features` and `variables` list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed. + +`segments` lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the `netherlands` segment take Belgium too, `segments` is `["netherlands"]`, and `features` and `variables` include `checkout` and `supportEmail`, whose conditions read it. The first datafile lists every feature, global variable and segment. `sections` lists the changed entries of each [datafile section](#read-the-datafile-from-a-module), such as `schemas`. ### `context_set` -Emitted by `setContext`, with the new `context` and `replaced`: +Emitted by `setContext`: ```java f.on(FeaturevisorEventName.CONTEXT_SET, event -> { - Map context = (Map) event.get("context"); + Map context = (Map) event.get("context"); // the new instance context + List keys = (List) event.get("keys"); // the top level keys whose values changed }); ``` +`keys` compares values, so a key set again to the value it already holds is not listed. Starting from the instance context `{"userId": "user-4", "country": "nl"}`: + +```java +f.setContext(Map.of( + "country", "de" +)); +// keys: ["country"] + +f.setContext(Map.of( + "country", "de", + "plan", "paid" +)); +// keys: ["plan"] + +f.setContext(Map.of( + "userId", "user-4", + "country", "de" +), true); +// keys: ["plan"] +``` + +A replace also lists the keys it removed, as `plan` above. Maps and lists compare item by item, and numbers by value, so `30` and `30.0` are the same, but a map or list given again as the same object counts as changed, since it may have been changed in place. + ### `sticky_features_set` Emitted by `setStickyFeatures`, with `features`, every feature that had a sticky value before the call or has one after it, and `replaced`: diff --git a/conformance/sdk-events.json b/conformance/sdk-events.json new file mode 100644 index 0000000..406fb5c --- /dev/null +++ b/conformance/sdk-events.json @@ -0,0 +1,1104 @@ +{ + "kind": "featurevisor.sdk-events", + "schemaVersion": 1, + "contextCases": [ + { + "name": "a merge lists the keys whose values changed", + "context": { + "userId": "user-4", + "country": "nl" + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "country": "de" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de" + }, + "replaced": false, + "keys": [ + "country" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "country": "de", + "plan": "pro" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "plan": "pro" + }, + "replaced": false, + "keys": [ + "plan" + ] + } + }, + { + "target": "root", + "replace": false, + "context": {}, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "plan": "pro" + }, + "replaced": false, + "keys": [] + } + } + ] + }, + { + "name": "a replace lists the keys it changed, added or removed", + "context": { + "userId": "user-4", + "country": "nl", + "plan": "pro" + }, + "operations": [ + { + "target": "root", + "replace": true, + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "replaced": true, + "keys": [ + "browser", + "country", + "plan" + ] + } + }, + { + "target": "root", + "replace": true, + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "browser": "firefox" + }, + "replaced": true, + "keys": [] + } + }, + { + "target": "root", + "replace": true, + "context": {}, + "expect": { + "context": {}, + "replaced": true, + "keys": [ + "browser", + "country", + "userId" + ] + } + } + ] + }, + { + "name": "objects and arrays compare item by item", + "context": { + "userId": "user-4", + "account": { + "plan": "pro", + "seats": 5 + }, + "tags": [ + "beta", + "staff" + ] + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "account": { + "seats": 5, + "plan": "pro" + }, + "tags": [ + "beta", + "staff" + ] + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "seats": 5, + "plan": "pro" + }, + "tags": [ + "beta", + "staff" + ] + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "root", + "replace": false, + "context": { + "tags": [ + "staff", + "beta" + ] + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "seats": 5, + "plan": "pro" + }, + "tags": [ + "staff", + "beta" + ] + }, + "replaced": false, + "keys": [ + "tags" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "account": { + "plan": "pro", + "seats": 6 + } + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "plan": "pro", + "seats": 6 + }, + "tags": [ + "staff", + "beta" + ] + }, + "replaced": false, + "keys": [ + "account" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "account": { + "plan": "pro", + "seats": 6, + "trial": false + } + }, + "expect": { + "context": { + "userId": "user-4", + "account": { + "plan": "pro", + "seats": 6, + "trial": false + }, + "tags": [ + "staff", + "beta" + ] + }, + "replaced": false, + "keys": [ + "account" + ] + } + } + ] + }, + { + "name": "null is a value of its own", + "context": { + "userId": "user-4" + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "plan": null + }, + "expect": { + "context": { + "userId": "user-4", + "plan": null + }, + "replaced": false, + "keys": [ + "plan" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "plan": null + }, + "expect": { + "context": { + "userId": "user-4", + "plan": null + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "root", + "replace": true, + "context": { + "userId": "user-4" + }, + "expect": { + "context": { + "userId": "user-4" + }, + "replaced": true, + "keys": [ + "plan" + ] + } + } + ] + }, + { + "name": "numbers compare by value", + "context": { + "userId": "user-4", + "age": 30, + "score": 2.5 + }, + "operations": [ + { + "target": "root", + "replace": false, + "context": { + "age": 30.0, + "score": 2.5 + }, + "expect": { + "context": { + "userId": "user-4", + "age": 30.0, + "score": 2.5 + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "root", + "replace": false, + "context": { + "age": 31 + }, + "expect": { + "context": { + "userId": "user-4", + "age": 31, + "score": 2.5 + }, + "replaced": false, + "keys": [ + "age" + ] + } + }, + { + "target": "root", + "replace": false, + "context": { + "age": "31" + }, + "expect": { + "context": { + "userId": "user-4", + "age": "31", + "score": 2.5 + }, + "replaced": false, + "keys": [ + "age" + ] + } + } + ] + }, + { + "name": "a child starts from the parent's context and lists the keys of its own", + "context": { + "userId": "user-4", + "country": "nl" + }, + "childContext": { + "plan": "pro" + }, + "operations": [ + { + "target": "child", + "replace": false, + "context": { + "plan": "pro" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "nl", + "plan": "pro" + }, + "replaced": false, + "keys": [] + } + }, + { + "target": "child", + "replace": false, + "context": { + "country": "de" + }, + "expect": { + "context": { + "userId": "user-4", + "country": "de", + "plan": "pro" + }, + "replaced": false, + "keys": [ + "country" + ] + } + }, + { + "target": "child", + "replace": true, + "context": { + "country": "de" + }, + "expect": { + "context": { + "country": "de" + }, + "replaced": true, + "keys": [ + "plan", + "userId" + ] + } + } + ] + } + ], + "datafileCases": [ + { + "name": "the first datafile lists every feature, global variable and segment", + "operations": [ + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "1", + "previousRevision": "unknown", + "revisionChanged": true, + "features": [ + "buyButton", + "checkout", + "pricing" + ], + "variables": [ + "supportEmail" + ], + "segments": [ + "benelux", + "germany", + "netherlands" + ], + "sections": {}, + "replaced": false + } + } + ] + }, + { + "name": "a merge lists the segments whose definitions it changed", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + } + }, + "operations": [ + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + } + }, + "features": {}, + "variables": {} + }, + "expect": { + "revision": "2", + "previousRevision": "1", + "revisionChanged": true, + "features": [ + "buyButton", + "checkout" + ], + "variables": [ + "supportEmail" + ], + "segments": [ + "netherlands" + ], + "sections": {}, + "replaced": false + } + }, + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "3", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + } + }, + "features": {}, + "variables": {} + }, + "expect": { + "revision": "3", + "previousRevision": "2", + "revisionChanged": true, + "features": [], + "variables": [], + "segments": [], + "sections": {}, + "replaced": false + } + }, + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "4", + "segments": { + "belgium": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "be" + } + } + }, + "features": {}, + "variables": {} + }, + "expect": { + "revision": "4", + "previousRevision": "3", + "revisionChanged": true, + "features": [], + "variables": [], + "segments": [ + "belgium" + ], + "sections": {}, + "replaced": false + } + } + ] + }, + { + "name": "a replace lists the segments it changed or removed", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + } + }, + "operations": [ + { + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "2", + "previousRevision": "1", + "revisionChanged": true, + "features": [ + "buyButton", + "checkout", + "pricing" + ], + "variables": [ + "supportEmail" + ], + "segments": [ + "germany", + "netherlands" + ], + "sections": {}, + "replaced": true + } + }, + { + "replace": true, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "in", + "value": [ + "nl", + "be" + ] + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "2", + "previousRevision": "2", + "revisionChanged": false, + "features": [], + "variables": [], + "segments": [], + "sections": {}, + "replaced": true + } + } + ] + }, + { + "name": "a changed feature or variable lists no segments", + "initial": { + "datafile": { + "schemaVersion": "4", + "revision": "1", + "segments": { + "netherlands": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "nl" + } + }, + "germany": { + "conditions": { + "attribute": "country", + "operator": "equals", + "value": "de" + } + }, + "benelux": { + "conditions": [ + "netherlands" + ] + } + }, + "features": { + "checkout": { + "hash": "checkout-1", + "bucketBy": "userId", + "conditions": "netherlands", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "pricing": { + "hash": "pricing-1", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + }, + "buyButton": { + "hash": "buyButton-1", + "bucketBy": "userId", + "conditions": "benelux", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-1", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + } + }, + "operations": [ + { + "replace": false, + "datafile": { + "schemaVersion": "4", + "revision": "2", + "segments": {}, + "features": { + "pricing": { + "hash": "pricing-2", + "bucketBy": "userId", + "conditions": "germany", + "traffic": [ + { + "key": "all", + "conditions": "*", + "percentage": 100000 + } + ] + } + }, + "variables": { + "supportEmail": { + "hash": "supportEmail-2", + "type": "string", + "defaultValue": "help@example.com", + "overrides": [ + { + "key": "dutch", + "conditions": "netherlands", + "value": "help-nl@example.com" + } + ] + } + } + }, + "expect": { + "revision": "2", + "previousRevision": "1", + "revisionChanged": true, + "features": [ + "pricing" + ], + "variables": [ + "supportEmail" + ], + "segments": [], + "sections": {}, + "replaced": false + } + } + ] + } + ] +} diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ChildInstance.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ChildInstance.java index 7e27a35..8a5ebb2 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ChildInstance.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ChildInstance.java @@ -70,6 +70,7 @@ public void close() { * Set context */ public void setContext(Map context, boolean replace) { + Map previous = this.context; if (replace) { this.context = new HashMap<>(context); } else { @@ -81,6 +82,10 @@ public void setContext(Map context, boolean replace) { FeaturevisorEventDetails eventDetails = new FeaturevisorEventDetails(); eventDetails.put("context", this.context); eventDetails.put("replaced", replace); + // Only a listener reads the changed keys, so only then are they worked out. + if (this.emitter.hasListeners(FeaturevisorEventName.CONTEXT_SET)) { + eventDetails.put("keys", ContextKeys.changed(previous, this.context, replace ? null : context)); + } this.emitter.trigger(FeaturevisorEventName.CONTEXT_SET, eventDetails); } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ContextKeys.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ContextKeys.java new file mode 100644 index 0000000..814c38e --- /dev/null +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/ContextKeys.java @@ -0,0 +1,118 @@ +package com.featurevisor.sdk; + +import java.lang.reflect.Array; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +/** + * The keys a context_set event lists: the top level keys whose values changed. + */ +final class ContextKeys { + /** How deep two values are compared. A value nested deeper, such as one that contains itself, counts as changed. */ + private static final int MAX_DEPTH = 64; + + private ContextKeys() { + } + + /** + * The top level keys whose values differ between two contexts, compared by value. A merge + * can change only the keys it carries, given as {@code incoming}, and a replace any key of + * either context. Null is a value, so a key set to null where it was absent has changed. + */ + static List changed(Map previous, Map next, Map incoming) { + List keys = new ArrayList<>(); + if (incoming != null) { + for (String key : incoming.keySet()) { + if (!previous.containsKey(key) || !same(previous.get(key), next.get(key), 0)) keys.add(key); + } + return keys; + } + for (Map.Entry entry : previous.entrySet()) { + if (!next.containsKey(entry.getKey()) || !same(entry.getValue(), next.get(entry.getKey()), 0)) { + keys.add(entry.getKey()); + } + } + for (String key : next.keySet()) { + if (!previous.containsKey(key)) keys.add(key); + } + return keys; + } + + /** + * Whether an attribute keeps its value. Numbers compare by numeric value, so an Integer and + * a Double holding 30 are the same, maps key by key and lists and arrays item by item. A + * map, collection or array given again as the same object counts as changed, since it may + * have been changed in place. + */ + static boolean same(Object before, Object after, int depth) { + if (before == after) { + return before == null || !(before instanceof Map || before instanceof Collection || before.getClass().isArray()); + } + if (before == null || after == null || depth > MAX_DEPTH) return false; + if (before instanceof Boolean || after instanceof Boolean) return before.equals(after); + if (before instanceof Number && after instanceof Number) return sameNumber((Number) before, (Number) after); + if (before instanceof Map) { + if (!(after instanceof Map)) return false; + Map left = (Map) before, right = (Map) after; + if (left.size() != right.size()) return false; + for (Map.Entry entry : left.entrySet()) { + if (!right.containsKey(entry.getKey()) || !same(entry.getValue(), right.get(entry.getKey()), depth + 1)) { + return false; + } + } + return true; + } + if (isList(before)) { + if (!isList(after) || length(before) != length(after)) return false; + Iterator left = items(before), right = items(after); + while (left.hasNext()) { + if (!same(left.next(), right.next(), depth + 1)) return false; + } + return true; + } + return before.getClass() == after.getClass() && before.equals(after); + } + + private static boolean sameNumber(Number before, Number after) { + if (integral(before) && integral(after)) { + return toBigInteger(before).equals(toBigInteger(after)); + } + if (before instanceof BigDecimal || after instanceof BigDecimal) { + try { + return new BigDecimal(before.toString()).compareTo(new BigDecimal(after.toString())) == 0; + } catch (NumberFormatException error) { + return false; + } + } + return before.doubleValue() == after.doubleValue(); + } + + private static boolean integral(Number value) { + return value instanceof Integer || value instanceof Long || value instanceof Short + || value instanceof Byte || value instanceof BigInteger; + } + + private static BigInteger toBigInteger(Number value) { + return value instanceof BigInteger ? (BigInteger) value : BigInteger.valueOf(value.longValue()); + } + + private static boolean isList(Object value) { + return value instanceof List || value.getClass().isArray(); + } + + private static int length(Object value) { + return value instanceof Collection ? ((Collection) value).size() : Array.getLength(value); + } + + private static Iterator items(Object value) { + if (value instanceof Collection) return ((Collection) value).iterator(); + List items = new ArrayList<>(); + for (int index = 0; index < Array.getLength(value); index++) items.add(Array.get(value, index)); + return items.iterator(); + } +} diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Emitter.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Emitter.java index 838e1e2..145859f 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Emitter.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Emitter.java @@ -51,6 +51,11 @@ void clearAll() { listeners.clear(); } + boolean hasListeners(FeaturevisorEventName eventName) { + List eventListeners = listeners.get(eventName); + return eventListeners != null && !eventListeners.isEmpty(); + } + Map> getListeners() { return new HashMap<>(listeners); } diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java index c466cbd..a2cf0bb 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Events.java @@ -118,6 +118,7 @@ private static FeaturevisorEventDetails getParamsForDatafileSetEvent( details.put("revisionChanged", !Objects.equals(previousDatafileContent.getRevision(), newDatafileContent.getRevision())); details.put("features", newDatafileContent.getFeatures() == null ? new ArrayList<>() : new ArrayList<>(newDatafileContent.getFeatures().keySet())); details.put("variables", newDatafileContent.getVariables() == null ? new ArrayList<>() : new ArrayList<>(newDatafileContent.getVariables().keySet())); + details.put("segments", newDatafileContent.getSegments() == null ? new ArrayList<>() : new ArrayList<>(newDatafileContent.getSegments().keySet())); details.put("sections", getChangedSections(previousDatafileContent, newDatafileContent)); details.put("replaced", replace); return details; @@ -170,6 +171,8 @@ private static FeaturevisorEventDetails getParamsForDatafileSetEvent( currentProvider == null ? Dependencies.create(newDatafileContent) : currentProvider.deriveDependencyIndex(previousProvider)); details.put("features", new ArrayList<>(changedFeatures)); details.put("variables", new ArrayList<>(variableKeys)); + // The dependency changes add features and variables only, so these are the changed definitions. + details.put("segments", new ArrayList<>(changedSegments)); details.put("sections", getChangedSections(previousDatafileContent, newDatafileContent)); details.put("replaced", replace); diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java index fb65772..1433f98 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java @@ -795,13 +795,21 @@ public void setContext(Map context) { public void setContext(Map context, boolean replace) { FeaturevisorEventDetails eventDetails = new FeaturevisorEventDetails(); + // Only a listener or a debug diagnostic receiver reads the changed keys, so + // only then are they worked out. + boolean wantsKeys = emitter.hasListeners(FeaturevisorEventName.CONTEXT_SET) + || hasDiagnosticInterest(FeaturevisorLogLevel.DEBUG); synchronized (stateLock) { + Map previous = this.context; Map next = replace ? new HashMap<>() : new HashMap<>(this.context); next.putAll(context); this.context = next; stateGeneration.incrementAndGet(); eventDetails.put("context", next); eventDetails.put("replaced", replace); + if (wantsKeys) { + eventDetails.put("keys", ContextKeys.changed(previous, next, replace ? null : context)); + } } this.emitter.trigger(FeaturevisorEventName.CONTEXT_SET, eventDetails); diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/EventsConformanceTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/EventsConformanceTest.java new file mode 100644 index 0000000..f438a01 --- /dev/null +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/EventsConformanceTest.java @@ -0,0 +1,147 @@ +package com.featurevisor.sdk; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; + +/** Runs conformance/sdk-events.json: the keys of context_set and the segments of datafile_set. */ +class EventsConformanceTest { + private static final ObjectMapper JSON = new ObjectMapper(); + + private JsonNode fixture() throws Exception { + try (InputStream stream = getClass().getResourceAsStream("/conformance/sdk-events.json")) { + JsonNode fixture = JSON.readTree(stream); + assertEquals("featurevisor.sdk-events", fixture.get("kind").asText()); + assertEquals(1, fixture.get("schemaVersion").asInt()); + return fixture; + } + } + + @SuppressWarnings("unchecked") + private static Map map(JsonNode node) { + return node == null || node.isNull() ? new HashMap<>() : JSON.convertValue(node, Map.class); + } + + /** Event details read as JSON, with their lists sorted, since key order differs across platforms. */ + private static JsonNode unordered(Object details) { + ObjectNode copy = JSON.valueToTree(details); + for (String field : new String[] {"keys", "features", "variables", "segments"}) { + if (copy.get(field) instanceof ArrayNode) copy.set(field, sorted((ArrayNode) copy.get(field))); + } + if (copy.get("sections") instanceof ObjectNode) { + ObjectNode sections = (ObjectNode) copy.get("sections"); + sections.fieldNames().forEachRemaining(name -> sections.set(name, sorted((ArrayNode) sections.get(name)))); + } + return copy; + } + + private static ArrayNode sorted(ArrayNode items) { + List values = new ArrayList<>(); + items.forEach(item -> values.add(item.asText())); + values.sort(null); + ArrayNode result = JSON.createArrayNode(); + values.forEach(result::add); + return result; + } + + @Test + void contextSetListsTheKeysItChanged() throws Exception { + for (JsonNode testCase : fixture().get("contextCases")) { + Featurevisor root = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .context(map(testCase.get("context"))) + .logLevel(FeaturevisorLogLevel.FATAL)); + ChildInstance child = root.spawn(map(testCase.get("childContext"))); + List events = new ArrayList<>(); + root.on(FeaturevisorEventName.CONTEXT_SET, events::add); + child.on(FeaturevisorEventName.CONTEXT_SET, events::add); + + int index = 0; + for (JsonNode operation : testCase.get("operations")) { + events.clear(); + Map context = map(operation.get("context")); + boolean replace = operation.get("replace").asBoolean(); + if ("child".equals(operation.get("target").asText())) child.setContext(context, replace); + else root.setContext(context, replace); + assertEquals(1, events.size(), testCase.get("name").asText() + ": operation " + index); + assertEquals(unordered(operation.get("expect")), unordered(events.get(0)), + testCase.get("name").asText() + ": operation " + index); + index++; + } + } + } + + @Test + void datafileSetListsTheSegmentsItChanged() throws Exception { + for (JsonNode testCase : fixture().get("datafileCases")) { + Featurevisor.FeaturevisorOptions options = new Featurevisor.FeaturevisorOptions() + .logLevel(FeaturevisorLogLevel.FATAL); + if (testCase.has("initial")) { + options.datafileString(JSON.writeValueAsString(testCase.get("initial").get("datafile"))); + } + Featurevisor f = Featurevisor.createFeaturevisor(options); + List events = new ArrayList<>(); + f.on(FeaturevisorEventName.DATAFILE_SET, events::add); + + int index = 0; + for (JsonNode operation : testCase.get("operations")) { + events.clear(); + assertTrue(f.setDatafile(JSON.writeValueAsString(operation.get("datafile")), + operation.get("replace").asBoolean())); + assertEquals(1, events.size(), testCase.get("name").asText() + ": operation " + index); + assertEquals(unordered(operation.get("expect")), unordered(events.get(0)), + testCase.get("name").asText() + ": operation " + index); + index++; + } + } + } + + @Test + void contextSetComparesJavaValuesAsAnApplicationReadsThem() { + Map nested = new HashMap<>(); + nested.put("plan", "pro"); + Map initial = new HashMap<>(); + initial.put("age", 30); + initial.put("big", 9007199254740993L); + initial.put("beta", true); + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .context(initial) + .logLevel(FeaturevisorLogLevel.FATAL)); + List keys = new ArrayList<>(); + f.on(FeaturevisorEventName.CONTEXT_SET, details -> keys.add(details.get("keys"))); + + // An Integer and a Double holding 30 are the same number, and so are a Long and a BigInteger. + f.setContext(Map.of("age", 30.0, "big", java.math.BigInteger.valueOf(9007199254740993L))); + // A boolean is never a number. + f.setContext(Map.of("beta", 1)); + // The same map given again may have been changed in place. + f.setContext(Map.of("account", nested)); + nested.put("plan", "basic"); + f.setContext(Map.of("account", nested)); + + assertEquals(List.of(), keys.get(0)); + assertEquals(List.of("beta"), keys.get(1)); + assertEquals(List.of("account"), keys.get(3)); + } + + @Test + void contextSetWorksTheKeysOutOnlyForSomeoneWhoReadsThem() { + List diagnostics = new ArrayList<>(); + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .logLevel(FeaturevisorLogLevel.DEBUG) + .onDiagnostic(diagnostics::add)); + f.setContext(Map.of("country", "nl")); + FeaturevisorDiagnostic contextSet = diagnostics.stream() + .filter(diagnostic -> "context_set".equals(diagnostic.getCode())).findFirst().orElseThrow(); + assertEquals(List.of("country"), contextSet.getDetails().get("keys")); + } +} diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java index 8c6b597..9a74926 100644 --- a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/StatefulConformanceTest.java @@ -177,8 +177,12 @@ private Map event(String target, FeaturevisorEventName name, value.put("target", target); value.put("name", name.getValue()); Map portable = new LinkedHashMap<>(details); - // `sections` in datafile_set is not yet part of the portable fixtures, as in JavaScript. - if (name == FeaturevisorEventName.DATAFILE_SET) portable.remove("sections"); + // The historical stateful cases predate `segments` and `sections` in datafile_set, + // which sdk-events.json and sdk-sections.json pin instead. + if (name == FeaturevisorEventName.DATAFILE_SET) { + portable.remove("sections"); + portable.remove("segments"); + } value.put("details", portable); return value; } From c2d1b08c9ef1ce198313440234acbbaeddaa1b2f Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 16:49:27 +0100 Subject: [PATCH 09/21] perf: work out datafile_set details only for someone who reads them setDatafile worked out the changed features, variables, segments and sections, and their dependency closure, on every call, even when no listener and no diagnostic at info received them. It now does only when a datafile_set listener, a child's among them, or an info diagnostic receiver exists, and otherwise skips the details, the diagnostic and the event, and the new provider builds no dependency index, which the next update that is read builds again from the datafile it has. What the SDK answers is unchanged, and so are the details whenever someone receives them. --- .../com/featurevisor/sdk/Featurevisor.java | 28 ++-- .../sdk/DatafileSetDetailsTest.java | 135 ++++++++++++++++++ 2 files changed, 154 insertions(+), 9 deletions(-) create mode 100644 featurevisor-sdk/src/test/java/com/featurevisor/sdk/DatafileSetDetailsTest.java diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java index 1433f98..b2e325c 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/sdk/Featurevisor.java @@ -551,8 +551,14 @@ public boolean setDatafile(DatafileContent datafile, boolean replace) { if (this.closed) { return false; } - FeaturevisorEventDetails details; + FeaturevisorEventDetails details = null; List> normalizationErrors = new ArrayList<>(); + // Only a datafile_set listener or an info diagnostic receiver reads the details, so + // only then are they and the dependency closure worked out. Without them the new + // provider keeps no index, and the next update that is read builds it again from the + // datafile it has. + boolean wantsDetails = emitter.hasListeners(FeaturevisorEventName.DATAFILE_SET) + || hasDiagnosticInterest(FeaturevisorLogLevel.INFO); try { if (datafile == null) { throw new IllegalArgumentException("Datafile must be an object"); @@ -569,8 +575,10 @@ public boolean setDatafile(DatafileContent datafile, boolean replace) { .datafile(nextDatafile) .diagnostics(this.diagnostics)); - details = Events.getParamsForProviderSetEvent( - this.evaluationData, newInstanceEvaluationDataProvider, replace); + if (wantsDetails) { + details = Events.getParamsForProviderSetEvent( + this.evaluationData, newInstanceEvaluationDataProvider, replace); + } if (!replace) newInstanceEvaluationDataProvider.retainCaches(this.evaluationData, incoming); this.evaluationData = newInstanceEvaluationDataProvider; @@ -585,12 +593,14 @@ public boolean setDatafile(DatafileContent datafile, boolean replace) { return false; } this.evaluationData.reportErrors(normalizationErrors); - reportDiagnostic(new FeaturevisorDiagnostic() - .level(FeaturevisorLogLevel.INFO) - .code("datafile_set") - .message("Datafile set") - .details(details), null); - this.emitter.trigger(FeaturevisorEventName.DATAFILE_SET, details); + if (details != null) { + reportDiagnostic(new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.INFO) + .code("datafile_set") + .message("Datafile set") + .details(details), null); + this.emitter.trigger(FeaturevisorEventName.DATAFILE_SET, details); + } return true; } diff --git a/featurevisor-sdk/src/test/java/com/featurevisor/sdk/DatafileSetDetailsTest.java b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/DatafileSetDetailsTest.java new file mode 100644 index 0000000..5be9ed7 --- /dev/null +++ b/featurevisor-sdk/src/test/java/com/featurevisor/sdk/DatafileSetDetailsTest.java @@ -0,0 +1,135 @@ +package com.featurevisor.sdk; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Test; + +/** + * datafile_set details are worked out only when a listener or an info diagnostic receiver reads + * them, as in JavaScript. + */ +class DatafileSetDetailsTest { + private static String datafile(String revision, String country, String features) { + return "{\"schemaVersion\":\"4\",\"revision\":\"" + revision + "\",\"segments\":{" + + "\"netherlands\":{\"conditions\":{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"" + country + "\"}}," + + "\"benelux\":{\"conditions\":[\"netherlands\"]}},\"features\":" + features + ",\"variables\":{}}"; + } + + private static final String FEATURES = "{" + + "\"checkout\":{\"hash\":\"checkout-1\",\"bucketBy\":\"userId\",\"conditions\":\"benelux\",\"traffic\":[{\"key\":\"all\",\"conditions\":\"*\",\"percentage\":100000}]}," + + "\"payments\":{\"hash\":\"payments-1\",\"bucketBy\":\"userId\",\"conditions\":{\"feature\":\"checkout\"},\"traffic\":[{\"key\":\"all\",\"conditions\":\"*\",\"percentage\":100000}]}," + + "\"simple\":{\"hash\":\"simple-1\",\"bucketBy\":\"userId\",\"traffic\":[{\"key\":\"all\",\"conditions\":\"*\",\"percentage\":100000}]}}"; + + private static String datafile(String revision, String country) { + return datafile(revision, country, FEATURES); + } + + private static Featurevisor create(String datafile, FeaturevisorLogLevel level, List diagnostics) { + Featurevisor.FeaturevisorOptions options = new Featurevisor.FeaturevisorOptions() + .datafileString(datafile) + .logLevel(level); + if (diagnostics != null) options.onDiagnostic(diagnostics::add); + return Featurevisor.createFeaturevisor(options); + } + + /** Whether the instance kept a dependency index, the work a skipped update leaves out. */ + private static boolean keepsIndex(Featurevisor f) throws Exception { + Field field = Featurevisor.class.getDeclaredField("evaluationData"); + field.setAccessible(true); + return ((InstanceEvaluationDataProvider) field.get(f)).getCachedDependencyIndexCount() > 0; + } + + private static List sorted(FeaturevisorEventDetails details, String key) { + return ((List) details.get(key)).stream().map(String::valueOf).sorted().collect(Collectors.toList()); + } + + @Test + void anUpdateNobodyReadsStillAppliesAndReportsNothing() throws Exception { + List diagnostics = new ArrayList<>(); + Featurevisor f = create(datafile("1", "nl"), FeaturevisorLogLevel.WARN, diagnostics); + Map context = Map.of("userId", "user-4", "country", "be"); + assertFalse(f.isEnabled("payments", context)); + assertTrue(f.setDatafile(datafile("2", "be"))); + assertTrue(f.setDatafile(datafile("3", "be", "{}"))); + assertTrue(f.isEnabled("payments", context)); + assertEquals("3", f.getRevision()); + assertEquals(List.of(), diagnostics); + assertFalse(keepsIndex(f)); + } + + @Test + void aLateListenerReceivesWhatAFreshInstanceWould() { + Featurevisor quiet = create(datafile("1", "nl"), FeaturevisorLogLevel.FATAL, null); + Featurevisor listening = create(datafile("1", "nl"), FeaturevisorLogLevel.FATAL, null); + List always = new ArrayList<>(); + listening.on(FeaturevisorEventName.DATAFILE_SET, always::add); + for (Featurevisor f : List.of(quiet, listening)) { + f.setDatafile(datafile("2", "de")); + f.setDatafile(datafile("3", "be"), true); + f.setDatafile("{\"schemaVersion\":\"4\",\"revision\":\"4\",\"segments\":{},\"features\":{}}"); + } + List late = new ArrayList<>(); + quiet.on(FeaturevisorEventName.DATAFILE_SET, late::add); + for (Featurevisor f : List.of(quiet, listening)) f.setDatafile(datafile("5", "lu")); + assertEquals(1, late.size()); + FeaturevisorEventDetails last = always.get(always.size() - 1); + for (String key : List.of("features", "variables", "segments")) { + assertEquals(sorted(last, key), sorted(late.get(0), key), key); + } + assertEquals(List.of("checkout", "payments"), sorted(late.get(0), "features")); + assertEquals(List.of("netherlands"), sorted(late.get(0), "segments")); + } + + @Test + void setLogLevelInfoBringsTheDiagnosticBack() { + List diagnostics = new ArrayList<>(); + Featurevisor f = create(datafile("1", "nl"), FeaturevisorLogLevel.WARN, diagnostics); + f.setDatafile(datafile("2", "de")); + f.setLogLevel(FeaturevisorLogLevel.INFO); + f.setDatafile(datafile("3", "be")); + assertEquals(List.of("datafile_set"), diagnostics.stream().map(FeaturevisorDiagnostic::getCode).collect(Collectors.toList())); + assertEquals("2", diagnostics.get(0).getDetails().get("previousRevision")); + } + + @Test + void aChildsListenerAndModuleSubscriptionsAtInfoCount() throws Exception { + Featurevisor f = create(datafile("1", "nl"), FeaturevisorLogLevel.FATAL, null); + ChildInstance child = f.spawn(Map.of("country", "be")); + List events = new ArrayList<>(); + FeaturevisorUnsubscribe stop = child.on(FeaturevisorEventName.DATAFILE_SET, events::add); + f.setDatafile(datafile("2", "be")); + assertEquals(1, events.size()); + assertTrue(keepsIndex(f)); + stop.unsubscribe(); + f.setDatafile(datafile("3", "de")); + assertEquals(1, events.size()); + assertFalse(keepsIndex(f)); + + AtomicReference api = new AtomicReference<>(); + f.addModule(new FeaturevisorModule("details-test").setup(api::set)); + List warn = new ArrayList<>(); + List info = new ArrayList<>(); + Runnable stopWarn = api.get().onDiagnostic(warn::add, new FeaturevisorModuleDiagnosticOptions(FeaturevisorLogLevel.WARN)); + f.setDatafile(datafile("4", "be")); + assertEquals(List.of(), warn); + assertFalse(keepsIndex(f)); + Runnable stopInfo = api.get().onDiagnostic(info::add, new FeaturevisorModuleDiagnosticOptions(FeaturevisorLogLevel.INFO)); + f.setDatafile(datafile("5", "de")); + assertEquals(1, info.size()); + assertEquals("datafile_set", info.get(0).getCode()); + assertTrue(keepsIndex(f)); + stopInfo.run(); + stopWarn.run(); + f.setDatafile(datafile("6", "be")); + assertEquals(1, info.size()); + assertFalse(keepsIndex(f)); + } +} From f75b4a30cee1e99f2b22014a4180ac293f1a72e6 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sat, 28 Nov 2026 20:44:57 +0100 Subject: [PATCH 10/21] fix: read the README example under its new heading The README now calls the section Create an instance, so the README check CI runs could not find the example it compiles and runs. --- scripts/ReadmeInitializationCheck.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/ReadmeInitializationCheck.java b/scripts/ReadmeInitializationCheck.java index d460b0a..ba9c35c 100644 --- a/scripts/ReadmeInitializationCheck.java +++ b/scripts/ReadmeInitializationCheck.java @@ -12,7 +12,7 @@ public class ReadmeInitializationCheck { public static void main(String[] args) throws Exception { String classpath = args[0]; - Matcher fence = Pattern.compile("## Initialization\\n.*?```java\\n(.*?)\\n```", Pattern.DOTALL) + Matcher fence = Pattern.compile("## Create an instance\\n.*?```java\\n(.*?)\\n```", Pattern.DOTALL) .matcher(Files.readString(Path.of("README.md"))); if (!fence.find()) throw new AssertionError("README initialization fence not found"); Path temporary = Files.createTempDirectory("featurevisor-readme-"); From 57847289e441f260b558941a46f6ef5d303e3f17 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 00:25:26 +0100 Subject: [PATCH 11/21] refactor(schemas): keep child, getFieldKeys, hasChecks and validateRules package private The JavaScript package exports none of them. getFields gives the fields' handles, each with its getName, and validate is the one way to validate. --- README.md | 30 +++++++++---------- .../featurevisor/schemas/SchemaHandle.java | 10 +++---- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index 5e42967..3458753 100644 --- a/README.md +++ b/README.md @@ -794,20 +794,20 @@ SchemaHandle signUp = s.get("signUp"); A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. -| Member | What it is | -| ---------------------------------------------------- | ------------------------------------------------------------------------- | -| `validate`, `isValid`, `parse` | As on `s`, without the key | -| `validateAsync` | Validation as a `CompletableFuture`, for [checks in code](#check-in-code) | -| `at(path)` | The handle of one field, such as `at("displayName")` | -| `getFields()`, `getFieldKeys()` | An object's fields' handles and names, in [order](#read-annotations) | -| `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, [below](#read-constraints-and-choices) | -| `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, and one of them by value | -| `getKind()` | What its rules make the field, such as `FieldKind.SELECT` | -| `getAnnotations()` | Its [annotations](#read-annotations) | -| `withInput(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | -| `getReads()` | The fields its rules' conditions read | -| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | -| `getKey()`, `getPath()`, `getName()` | The schema's key, and the field's path and own name | +| Member | What it is | +| ---------------------------------------------------- | ------------------------------------------------------------------------------------- | +| `validate`, `isValid`, `parse` | As on `s`, without the key | +| `validateAsync` | Validation as a `CompletableFuture`, for [checks in code](#check-in-code) | +| `at(path)` | The handle of one field, such as `at("displayName")` | +| `getFields()` | An object's fields' handles, in [order](#read-annotations), each with its `getName()` | +| `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, [below](#read-constraints-and-choices) | +| `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, and one of them by value | +| `getKind()` | What its rules make the field, such as `FieldKind.SELECT` | +| `getAnnotations()` | Its [annotations](#read-annotations) | +| `withInput(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | +| `getReads()` | The fields its rules' conditions read | +| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | +| `getKey()`, `getPath()`, `getName()` | The schema's key, and the field's path and own name | `at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. @@ -1064,7 +1064,7 @@ Every call reads the current datafile, so a new datafile takes effect at the nex ```java SchemaHandle signUp = schemas.get("signUp"); -signUp.getFieldKeys(); // [accountType, displayName, taxId], in the schema's order +signUp.getFields(); // handles for accountType, displayName and taxId, in the schema's order signUp.at("displayName").getConstraints(); // required, minLength and maxLength signUp.at("accountType").getOptions(); // personal and business, with their titles signUp.at("accountType").getKind(); // FieldKind.SELECT diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 4887fd4..3dddd5b 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -208,11 +208,11 @@ public Object parse(Object value, Map context) { } /** The schema's own rules, without checks in code, which always answers at once. */ - public ValidationResult validateRules(Object value) { + ValidationResult validateRules(Object value) { return validateRules(value, null); } - public ValidationResult validateRules(Object value, Map context) { + ValidationResult validateRules(Object value, Map context) { return evaluated(context, run -> { applyRules(Json.plain(value), run); return new ValidationResult(value, run.issues); @@ -220,7 +220,7 @@ public ValidationResult validateRules(Object value, Map context) } /** Whether the handle has checks in code, which can make validation wait for an answer. */ - public boolean hasChecks() { + boolean hasChecks() { return !checks().isEmpty(); } @@ -493,7 +493,7 @@ public SchemaHandle at(String path) { * {@code at} gives when the key reads as itself, and its own for a key such as * {@code a.b}, {@code *} or {@code 2024}, which a path would read otherwise. */ - public SchemaHandle child(String key) { + SchemaHandle child(String key) { if (key.matches("[^.\\[\\]*\\d][^.\\[\\]]*")) return at(key); return handle("\u0000" + key, () -> List.of(Paths.Step.key(key))); } @@ -582,7 +582,7 @@ public Map getAnnotations() { } /** The keys of an object's fields, in its {@code order}. */ - public List getFieldKeys() { + List getFieldKeys() { return derive("fieldKeys", (node, required) -> Derived.fieldKeys(node, context.store), List.of()); } From 35cbcf5721cd1ae2d5081aa6440e688a1117ce02 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 00:30:25 +0100 Subject: [PATCH 12/21] refactor(schemas): drop validateRules and hasChecks, which nothing called JavaScript keeps both for its React hooks, and Java has none. --- .../com/featurevisor/schemas/SchemaHandle.java | 17 ----------------- .../com/featurevisor/schemas/SchemasTest.java | 3 --- 2 files changed, 20 deletions(-) diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 3dddd5b..0e1a6f1 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -207,23 +207,6 @@ public Object parse(Object value, Map context) { return value; } - /** The schema's own rules, without checks in code, which always answers at once. */ - ValidationResult validateRules(Object value) { - return validateRules(value, null); - } - - ValidationResult validateRules(Object value, Map context) { - return evaluated(context, run -> { - applyRules(Json.plain(value), run); - return new ValidationResult(value, run.issues); - }); - } - - /** Whether the handle has checks in code, which can make validation wait for an answer. */ - boolean hasChecks() { - return !checks().isEmpty(); - } - /** * Runs the body with a run in the schema's package evaluation, so modules see it * and its conditions read the context they leave. A view's context comes first, diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java index 68bac47..eaf25dc 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -130,7 +130,6 @@ void refinementsRunAfterTheRulesWhereTheyFoundNothing() { (value, info) -> CompletableFuture.supplyAsync(() -> !"taken".equals(value))); Refinement broken = Refinement.of("broken", "city", (value, info) -> { throw new IllegalStateException("down"); }); SchemaHandle signUp = Schemas.create(instance()).get("signUp", new HandleOptions().refine(match, taken, broken)); - assertTrue(signUp.hasChecks()); assertTrue(signUp.validate(valid()).isValid()); Map wrong = Map.of("username", "taken", "password", "long enough", "confirm", "other", "city", "Utrecht"); @@ -143,8 +142,6 @@ void refinementsRunAfterTheRulesWhereTheyFoundNothing() { // A rule's issue at the field, or in a field a check reads, holds the check back. ValidationResult held = signUp.validate(Map.of("username", "ab", "password", "short", "confirm", "other")); assertEquals(List.of("minLength", "minLength"), codes(held)); - // The rules alone never wait. - assertTrue(signUp.validateRules(Map.of("username", "taken", "password", "long enough")).isValid()); } @Test From 1ba5ed3960cf4371ad08ad9beafbf82082189b67 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 02:12:44 +0100 Subject: [PATCH 13/21] test(schemas): a default annotation, and one a mutation sets The shared fixture's sign up form gives accountType and a newsletter box a default, which the business mutation turns off, and the built datafile test reads both. --- conformance/schemas-datafile.json | 68 ++++++++++++++++--- .../schemas/BuiltDatafileTest.java | 2 + 2 files changed, 61 insertions(+), 9 deletions(-) diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index 1cd37f0..b3e7ca5 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -4,7 +4,7 @@ "datafile": { "schemaVersion": "4", "featurevisorVersion": "4.13.0", - "revision": "lKLik9RrAm", + "revision": "Qw1wESNyKJ", "segments": { "netherlands": { "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" @@ -95,7 +95,7 @@ ] }, "signUp": { - "hash": "wLXjboTQnZ", + "hash": "bKMCwKxTvT", "type": "object", "properties": { "accountType": { @@ -106,6 +106,7 @@ ], "annotations": { "title": "Account type", + "default": "personal", "options": { "personal": { "title": "Personal" @@ -133,6 +134,13 @@ "annotations": { "title": "VAT number" } + }, + "newsletter": { + "type": "boolean", + "annotations": { + "title": "Send me product news", + "default": true + } } }, "required": [ @@ -149,7 +157,8 @@ "order": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ] }, "mutations": [ @@ -183,6 +192,16 @@ "value": { "pattern": "Enter your VAT number, such as DE123456789" } + }, + { + "op": "set", + "path": [ + "properties", + "newsletter", + "annotations", + "default" + ], + "value": false } ] } @@ -526,7 +545,8 @@ "fieldKeys": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ], "constraints": { "accountType": { @@ -537,7 +557,8 @@ "minLength": 2, "maxLength": 40 }, - "taxId": {} + "taxId": {}, + "newsletter": {} }, "options": { "accountType": [ @@ -560,7 +581,8 @@ "order": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ] } }, @@ -584,6 +606,7 @@ "reads": [], "annotations": { "title": "Account type", + "default": "personal", "options": { "personal": { "title": "Personal" @@ -637,12 +660,37 @@ "title": "VAT number" } }, + "newsletter": { + "path": "newsletter", + "fieldKeys": [], + "constraints": {}, + "options": [], + "kind": "boolean", + "reads": [], + "annotations": { + "title": "Send me product news", + "default": true + } + }, + "businessNewsletter": { + "path": "newsletter", + "fieldKeys": [], + "constraints": {}, + "options": [], + "kind": "boolean", + "reads": [], + "annotations": { + "title": "Send me product news", + "default": false + } + }, "business": { "path": "", "fieldKeys": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ], "constraints": { "accountType": { @@ -655,7 +703,8 @@ }, "taxId": { "required": true - } + }, + "newsletter": {} }, "options": { "accountType": [ @@ -678,7 +727,8 @@ "order": [ "accountType", "displayName", - "taxId" + "taxId", + "newsletter" ] } }, diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java index d66e3a5..fc42f88 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java @@ -78,6 +78,8 @@ void describesFieldsAsJavaScriptDoes() throws Exception { handles.put("displayName", signUp.at("displayName")); handles.put("taxId", signUp.at("taxId")); handles.put("businessTaxId", business.at("taxId")); + handles.put("newsletter", signUp.at("newsletter")); + handles.put("businessNewsletter", business.at("newsletter")); handles.put("business", business); handles.put("checkout", schemas.get("checkout")); handles.put("register", schemas.get("register")); From 2dfdc34770d4593264a4b9040e3e61a6a25a075c Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 02:28:33 +0100 Subject: [PATCH 14/21] docs(schemas): the default annotation in Read annotations The README says what default is and that a handle from with input has the one a mutation sets, as the JavaScript page does. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 3458753..9b7b57d 100644 --- a/README.md +++ b/README.md @@ -854,7 +854,7 @@ signUp.getFields().stream().map(SchemaHandle::getPath).toList(); // [displayName, email, country] ``` -Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. +`default` is the value a form starts a field with, and a handle from `withInput` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. ### Choose the messages From 067525595e3d3c5d8f9f30767c49e2b834562b9c Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 02:58:40 +0100 Subject: [PATCH 15/21] feat(schemas): issues entries wait only for the fields they compare, and unlisted fields come in name order An issues entry waited for any issue of shape in its object. It now waits only while one sits at or inside its path, or anywhere in the object without a path, or in a field its conditions read, as JavaScript's does. Fields an order leaves out come in name order by Unicode code point, and the built datafile test compares field order exactly. The README says Schemas are experimental, as JavaScript's does, and that unlisted fields come in name order. --- README.md | 4 +- conformance/schemas-datafile.json | 54 ++++- conformance/schemas-validation.json | 184 +++++++++++++++++- .../com/featurevisor/schemas/Derived.java | 24 ++- .../java/com/featurevisor/schemas/Engine.java | 46 ++++- .../java/com/featurevisor/schemas/Run.java | 5 +- .../java/com/featurevisor/schemas/Views.java | 2 +- .../schemas/BuiltDatafileTest.java | 1 + .../com/featurevisor/schemas/SchemasTest.java | 3 +- 9 files changed, 299 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 9b7b57d..0a99e95 100644 --- a/README.md +++ b/README.md @@ -712,6 +712,8 @@ Feature and variable leaves reach modules as dependencies, naming the package's Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. +Schemas are experimental, so their API may change in a minor release, as in JavaScript. + ### Create a schemas instance They are a separate artifact, released with the same version as the SDK: @@ -854,7 +856,7 @@ signUp.getFields().stream().map(SchemaHandle::getPath).toList(); // [displayName, email, country] ``` -`default` is the value a form starts a field with, and a handle from `withInput` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in key order. A field or schema the datafile lacks has no annotations. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. +`default` is the value a form starts a field with, and a handle from `withInput` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. ### Choose the messages diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index b3e7ca5..affb9bc 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -4,7 +4,7 @@ "datafile": { "schemaVersion": "4", "featurevisorVersion": "4.13.0", - "revision": "Qw1wESNyKJ", + "revision": "Y2jhtKdlDE", "segments": { "netherlands": { "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" @@ -55,6 +55,27 @@ } ] }, + "profile": { + "hash": "Diqw68LeIn", + "type": "object", + "properties": { + "zeta": { + "type": "string" + }, + "alpha": { + "type": "string" + }, + "Beta": { + "type": "string" + }, + "z": { + "type": "string" + }, + "😀": { + "type": "string" + } + } + }, "register": { "hash": "XlDf9sip1o", "type": "object", @@ -736,10 +757,10 @@ "path": "", "fieldKeys": [ "billingCountry", - "shippingCountry", + "confirmPassword", "customsDescription", "password", - "confirmPassword" + "shippingCountry" ], "constraints": { "billingCountry": { @@ -761,10 +782,10 @@ "register": { "path": "", "fieldKeys": [ - "password", + "billingCountry", "confirmPassword", - "shippingCountry", - "billingCountry" + "password", + "shippingCountry" ], "constraints": { "password": { @@ -784,6 +805,27 @@ "billingCountry" ], "annotations": {} + }, + "profile": { + "path": "", + "fieldKeys": [ + "Beta", + "alpha", + "zeta", + "z", + "😀" + ], + "constraints": { + "zeta": {}, + "alpha": {}, + "Beta": {}, + "z": {}, + "😀": {} + }, + "options": {}, + "kind": "object", + "reads": [], + "annotations": {} } } } diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index abf81ab..75222d5 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -2187,7 +2187,7 @@ "issues": [] }, { - "name": "an issue of shape holds every issue entry back", + "name": "an issue of shape elsewhere holds no issue entry back", "schemas": { "subject": { "hash": "subject-1", @@ -2230,6 +2230,186 @@ "password": "lovelace", "confirmPassword": "other" }, + "issues": [ + { + "code": "required", + "path": [ + "email" + ], + "params": { + "key": "email" + } + }, + { + "code": "refine", + "path": [ + "confirmPassword" + ], + "params": { + "refine": "passwordsDiffer" + } + } + ] + }, + { + "name": "an issue of shape in a field an entry reads holds it back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": 5, + "confirmPassword": "other" + }, + "issues": [ + { + "code": "type", + "path": [ + "password" + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "an issue of shape at an entry's path holds it back", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "path": "confirmPassword", + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "email": "a@b.c", + "password": "lovelace", + "confirmPassword": 5 + }, + "issues": [ + { + "code": "type", + "path": [ + "confirmPassword" + ], + "params": { + "type": "string", + "received": "number" + } + } + ] + }, + { + "name": "an issue entry without a path waits for the whole object", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "email": { + "type": "string" + }, + "password": { + "type": "string", + "minLength": 8 + }, + "confirmPassword": { + "type": "string" + } + }, + "required": [ + "email" + ], + "issues": [ + { + "key": "passwordsDiffer", + "conditions": [ + { + "input": "confirmPassword", + "operator": "notEquals", + "valueFrom": { + "input": "password" + } + } + ], + "message": "The passwords do not match" + } + ] + } + }, + "schema": "subject", + "value": { + "password": "lovelace", + "confirmPassword": "other" + }, "issues": [ { "code": "required", @@ -2595,7 +2775,7 @@ ] }, { - "name": "a format issue holds every issue entry back", + "name": "a format issue in a field an issue entry reads holds it back", "schemas": { "subject": { "hash": "subject-1", diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java index c7e3e81..9eac0ec 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java @@ -196,7 +196,24 @@ private static void collectOptions(Map node, String prefix, Reso } } - /** The keys of an object's fields, the ones its {@code order} lists first, then the rest as written. */ + /** + * Orders names by their Unicode code points, which every SDK can do whatever its + * strings' encoding, where {@code String.compareTo} compares UTF-16 units. + */ + static int compareNames(String a, String b) { + int i = 0; + int j = 0; + while (i < a.length() && j < b.length()) { + int x = a.codePointAt(i); + int y = b.codePointAt(j); + if (x != y) return Integer.compare(x, y); + i += Character.charCount(x); + j += Character.charCount(y); + } + return (i < a.length() ? 1 : 0) - (j < b.length() ? 1 : 0); + } + + /** The keys of an object's fields, the ones its {@code order} lists first, then the rest in name order. */ static List fieldKeys(Object node, Resolver resolve) { Map resolved = Engine.resolveNode(node, resolve); Map properties = resolved == null ? null : Json.map(resolved.get("properties")); @@ -209,7 +226,10 @@ static List fieldKeys(Object node, Resolver resolve) { if (key instanceof String && keys.contains(key) && !ordered.contains(key)) ordered.add((String) key); } } - for (String key : keys) if (!ordered.contains(key)) ordered.add(key); + List rest = new ArrayList<>(); + for (String key : keys) if (!ordered.contains(key)) rest.add(key); + rest.sort(Derived::compareNames); + ordered.addAll(rest); return Collections.unmodifiableList(ordered); } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java index d805c08..6d7950a 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java @@ -31,7 +31,7 @@ static void report(Run run, Position at, String code, Map params static void report(Run run, Position at, String code, Map params, List path, Messages.Lookup lookup, String ownMessage) { run.failed = true; - if (SHAPE_CODES.contains(code)) run.shape++; + if (SHAPE_CODES.contains(code)) run.shapes.add(path); if (run.trial) return; // The field's title, so a message can say `{title} is required`. if (lookup.title != null) { @@ -694,21 +694,51 @@ private static boolean setsRule(Map mutation, SchemaIssue issue, return false; } + /** Whether {@code inner}, a path relative to an object, is {@code outer} or a path inside it. */ + private static boolean atOrInside(List inner, List outer) { + if (inner.size() < outer.size()) return false; + for (int index = 0; index < outer.size(); index++) { + if (!String.valueOf(inner.get(index)).equals(outer.get(index))) return false; + } + return true; + } + /** - * An object's {@code issues}: after its own rules, unless an issue of shape - * sits anywhere inside it, each entry whose conditions match reports its issue - * at its path, with that field's title and the messages around it. + * An object's {@code issues}: after its own rules, each entry whose conditions + * match reports its issue at its path, with that field's title and the messages + * around it. An entry waits while an issue of shape sits at or inside its path, + * or anywhere in the object for an entry without one, as a check in code does, + * or at or inside a field its conditions read. */ private static Validator compileIssues(Map node, Validator rules, Resolver resolve) { List entries = (List) node.get("issues"); + List>> waits = new ArrayList<>(); + for (Object item : entries) { + Map entry = Json.map(item); + List> own = new ArrayList<>(); + String ownPath = entry == null ? null : Json.string(entry.get("path")); + own.add(ownPath == null || ownPath.isEmpty() ? List.of() : Arrays.asList(ownPath.split("\\.", -1))); + if (entry != null) { + Views.inputsOf(entry.get("conditions"), read -> { + if (read instanceof String) own.add(Arrays.asList(((String) read).split("\\.", -1))); + }); + } + waits.add(own); + } return (value, run, at) -> { - int shape = run.shape; + int before = run.shapes.size(); rules.validate(value, run, at); - if (run.shape != shape || !(value instanceof Map)) return; + if (!(value instanceof Map)) return; + List> found = new ArrayList<>(); + for (List path : run.shapes.subList(before, run.shapes.size())) { + found.add(path.subList(Math.min(at.path.size(), path.size()), path.size())); + } ConditionReader input = inputReader(value); - for (Object item : entries) { - Map entry = Json.map(item); + for (int entryIndex = 0; entryIndex < entries.size(); entryIndex++) { + Map entry = Json.map(entries.get(entryIndex)); if (entry == null) continue; + List> wait = waits.get(entryIndex); + if (found.stream().anyMatch(path -> wait.stream().anyMatch(scope -> atOrInside(path, scope)))) continue; if (!run.match.match(entry.get("conditions"), input)) continue; String path = Json.string(entry.get("path")); List parts = path == null || path.isEmpty() ? List.of() : Arrays.asList(path.split("\\.", -1)); diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java index 84f1d71..6bd38e5 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Run.java @@ -12,8 +12,8 @@ final class Run { /** Counting {@code oneOf} branches only notes whether a branch failed, without wording anything. */ final boolean trial; boolean failed; - /** How many issues of shape were found, which hold back the {@code issues} of every object around them. */ - int shape; + /** The paths of the issues of shape found so far, which hold back the {@code issues} entries that read them. */ + final List> shapes = new ArrayList<>(); /** How many references the walk follows at this point, which only a value nested as deep can need. */ int depth; /** Answers conditions in the schema's package evaluation, with the context its modules leave. */ @@ -36,7 +36,6 @@ private Run(String schema, List issues, Messages.Sources sources, I /** A run for one {@code oneOf} branch, which only notes whether it fails. */ Run trial() { Run trial = new Run(schema, new ArrayList<>(), sources, translate, true, match); - trial.shape = shape; trial.depth = depth; return trial; } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java index 3fd26aa..90ef032 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java @@ -108,7 +108,7 @@ static Object place(Object values, List steps, Object value) { } /** Calls back with the input paths conditions read, in {@code input} and {@code valueFrom}, through every group. */ - private static void inputsOf(Object conditions, Consumer found) { + static void inputsOf(Object conditions, Consumer found) { // Datafiles can carry conditions as JSON text, as features' are. if (conditions instanceof String) { String text = ((String) conditions).stripLeading(); diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java index fc42f88..313837f 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java @@ -80,6 +80,7 @@ void describesFieldsAsJavaScriptDoes() throws Exception { handles.put("businessTaxId", business.at("taxId")); handles.put("newsletter", signUp.at("newsletter")); handles.put("businessNewsletter", business.at("newsletter")); + handles.put("profile", schemas.get("profile")); handles.put("business", business); handles.put("checkout", schemas.get("checkout")); handles.put("register", schemas.get("register")); diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java index eaf25dc..1678355 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -333,7 +333,8 @@ void contextAModuleAddsReachesMutationsIssueEntriesAndViewsAsItReachesFlags() { })); Schemas s = Schemas.create(f); - assertEquals(List.of("required taxId"), codesAt(s.validate("signUp", Map.of("name", "Ada")))); + // The entry about the name reads no field, so a missing VAT number does not hold it back. + assertEquals(List.of("required taxId", "refine name"), codesAt(s.validate("signUp", Map.of("name", "Ada")))); assertEquals(List.of("refine name"), codesAt(s.validate("signUp", Map.of("name", "Ada", "taxId", "x")))); assertTrue(s.get("signUp").withInput(Map.of()).at("taxId").getConstraints().isRequired()); // One evaluation per validation and per view, each the schema's own. From 917ded47aee1cb11b519a4f4d104b3b35ec27231 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 15:33:31 +0100 Subject: [PATCH 16/21] refactor(schemas): follow the simplified JavaScript package The JavaScript package was simplified for review with no change in behaviour, and this port follows it where it has the same structure: one position for report, an issue entry's path split once, inputsOf keeping only strings, a oneOf branch chosen from a map of kinds, attribution worked out once per issue, and one classifier for path steps. Compiled validators and mutated rules are kept per instance by node identity, in two generations, so an unchanged schema keeps its validator across a datafile change while memory holds two datafiles at most, and an array without items shares one string node. child gives a key such as 2fa the handle at gives, with a test. Messages are typed, so no other bug applied. The shared schemas-validation.json gains two cases for a field a mutation adds by schema reference, which pass. The README follows the JavaScript page: the data is value beside the handle, Follow the values typed so far comes after Read annotations, Check in code names its optional fields, and the constraints and options rows say which member is keyed by field path. --- README.md | 73 +++++----- conformance/schemas-validation.json | 134 ++++++++++++++++++ .../com/featurevisor/schemas/Derived.java | 48 +++---- .../java/com/featurevisor/schemas/Engine.java | 126 ++++++++-------- .../java/com/featurevisor/schemas/Paths.java | 16 ++- .../com/featurevisor/schemas/Position.java | 8 +- .../featurevisor/schemas/SchemaHandle.java | 7 +- .../java/com/featurevisor/schemas/Store.java | 94 ++++++------ .../java/com/featurevisor/schemas/Views.java | 9 +- .../com/featurevisor/schemas/SchemasTest.java | 59 ++++++++ 10 files changed, 382 insertions(+), 192 deletions(-) diff --git a/README.md b/README.md index 0a99e95..d033428 100644 --- a/README.md +++ b/README.md @@ -45,10 +45,10 @@ The Featurevisor Java SDK evaluates flags, variations and variables in Java and - [Get a handle](#get-a-handle) - [Read constraints and choices](#read-constraints-and-choices) - [Read annotations](#read-annotations) + - [Follow the values typed so far](#follow-the-values-typed-so-far) - [Choose the messages](#choose-the-messages) - [Check in code](#check-in-code) - [Options from your application](#options-from-your-application) - - [Follow the values typed so far](#follow-the-values-typed-so-far) - [Validate on the server](#validate-on-the-server) - [Listen for changes](#listen-for-changes) - [Patterns](#patterns) @@ -739,13 +739,13 @@ It holds no copy of the schemas. Every call reads the datafile `f` has now, so a ### Validate a value ```java -Map signUp = Map.of( +Map value = Map.of( "email", "user-1@example.com", "displayName", "A", "country", "nl" ); -ValidationResult result = s.validate("signUp", signUp); +ValidationResult result = s.validate("signUp", value); if (!result.isValid()) { // show result.getIssues() beside the form's fields @@ -788,7 +788,7 @@ Validation reports every issue it finds, so a form can mark every field at once. ### Get a handle -`s.get(key)` gives the schema's handle: +A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. `s.get(key)` gives one: ```java SchemaHandle signUp = s.get("signUp"); @@ -796,20 +796,20 @@ SchemaHandle signUp = s.get("signUp"); A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. -| Member | What it is | -| ---------------------------------------------------- | ------------------------------------------------------------------------------------- | -| `validate`, `isValid`, `parse` | As on `s`, without the key | -| `validateAsync` | Validation as a `CompletableFuture`, for [checks in code](#check-in-code) | -| `at(path)` | The handle of one field, such as `at("displayName")` | -| `getFields()` | An object's fields' handles, in [order](#read-annotations), each with its `getName()` | -| `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, [below](#read-constraints-and-choices) | -| `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, and one of them by value | -| `getKind()` | What its rules make the field, such as `FieldKind.SELECT` | -| `getAnnotations()` | Its [annotations](#read-annotations) | -| `withInput(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | -| `getReads()` | The fields its rules' conditions read | -| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | -| `getKey()`, `getPath()`, `getName()` | The schema's key, and the field's path and own name | +| Member | What it is | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- | +| `validate`, `isValid`, `parse` | As on `s`, without the key | +| `validateAsync` | Validation as a `CompletableFuture`, for [checks in code](#check-in-code) | +| `at(path)` | The handle of one field, such as `at("displayName")` | +| `getFields()` | An object's fields' handles, in [order](#read-annotations), each with its `getName()` | +| `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, by field path on an object, [below](#read-constraints-and-choices) | +| `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, by field path on an object, and one choice by value | +| `getKind()` | What its rules make the field, such as `FieldKind.SELECT` | +| `getAnnotations()` | Its [annotations](#read-annotations) | +| `withInput(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | +| `getReads()` | The fields its rules' conditions read | +| `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | +| `getKey()`, `getPath()`, `getName()` | The schema's key, and the field's path and own name | `at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. @@ -858,6 +858,22 @@ signUp.getFields().stream().map(SchemaHandle::getPath).toList(); `default` is the value a form starts a field with, and a handle from `withInput` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). Fields an `order` annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations. [Annotations](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them. +### Follow the values typed so far + +A handle's constraints and choices describe the schema's own rules, which no condition changes. `withInput(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen: + +```java +Map values = Map.of( + "accountType", "business", + "country", "nl" +); + +signUp.at("taxId").getConstraints().isRequired(); // false +signUp.withInput(values).at("taxId").getConstraints().isRequired(); // true +``` + +Every member follows the input, at every depth. `getReads()` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. + ### Choose the messages `SchemasOptions` words every schema's issues, per code, as a template or a `SchemaMessage`: @@ -874,11 +890,11 @@ Schemas s = Schemas.create(f, new SchemasOptions() 3. The application's, from `SchemasOptions`. 4. The default, in English. -A `translator` on `SchemasOptions` gets each issue, with the message chosen, and returns what the issue says, or `null` to keep it. Keep the text in your translation system, and let schemas and messages hold keys, such as `errors.required`, which the translator turns into text. +A `translator` on `SchemasOptions` gets each issue, with the message chosen, and returns what the issue says, or `null` to keep it. With translations, messages hold keys, such as `errors.required`, and the translator turns each into text. ### Check in code -Some checks need your application, such as whether a display name is taken. Give them to a handle with `HandleOptions.refine`, each a `Refinement` with a key, a path, a check and a message: +Some checks need your application, such as whether a display name is taken. Give them to a handle with `HandleOptions.refine`, each a `Refinement` with a key and a check, and the path it checks, a message and `reads` as it needs them: ```java SchemaHandle signUp = s.get("signUp", new HandleOptions() @@ -891,6 +907,7 @@ ValidationResult result = signUp.validate(value); - A check gets the value at its path, and a `CheckInfo` with the whole input and the context, where `info.read("country")` reads another field. It returns `true` when the value passes. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. +- Without a path, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total. - Its issue has code `refine` and the `refine` param `"nameAvailable"`, with the field's title. A check that throws gives `refineError`, and validation fails closed. - `Refinement.async` takes a check returning a `CompletionStage`. `validate` waits for it, and `validateAsync` returns a `CompletableFuture` instead. @@ -916,22 +933,6 @@ List suggestions = city.search("am").join(); - `lookup` returns the choice for a value, `true` when it carries nothing more, or `null` when there is none. A handle's `lookup(value)` returns the schema's own choice first, then the source's. - Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by its message. `searchAsync` and `lookupAsync` take sources that answer later. -### Follow the values typed so far - -A handle's constraints and choices describe the schema's own rules, which no condition changes. `withInput(input)` gives the same handle with an input, such as a form's values, with the [mutations](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen: - -```java -Map values = Map.of( - "accountType", "business", - "country", "nl" -); - -signUp.at("taxId").getConstraints().isRequired(); // false -signUp.withInput(values).at("taxId").getConstraints().isRequired(); // true -``` - -Every member follows the input, at every depth. `getReads()` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. - ### Validate on the server `parse` answers a request with a value or a `SchemaValidationException`, whose `flatten()` gives the issues by field: diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index 75222d5..b5fbdcb 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -4303,6 +4303,140 @@ "mutation": "numeric" } ] + }, + { + "name": "a field a mutation adds by reference validates with the referenced schema", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "country": { + "type": "string" + } + }, + "mutations": [ + { + "key": "withAddress", + "conditions": [ + { + "input": "country", + "operator": "equals", + "value": "de" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "address" + ], + "value": { + "schema": "address" + } + } + ] + } + ] + }, + "address": { + "hash": "address-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + }, + "schema": "subject", + "value": { + "country": "de", + "address": {} + }, + "issues": [ + { + "code": "required", + "path": [ + "address", + "city" + ], + "params": { + "key": "city" + }, + "mutation": "withAddress" + } + ] + }, + { + "name": "without the mutation, the field it adds by reference is not allowed", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "properties": { + "country": { + "type": "string" + } + }, + "mutations": [ + { + "key": "withAddress", + "conditions": [ + { + "input": "country", + "operator": "equals", + "value": "de" + } + ], + "operations": [ + { + "op": "set", + "path": [ + "properties", + "address" + ], + "value": { + "schema": "address" + } + } + ] + } + ] + }, + "address": { + "hash": "address-1", + "type": "object", + "properties": { + "city": { + "type": "string" + } + }, + "required": [ + "city" + ] + } + }, + "schema": "subject", + "value": { + "country": "nl", + "address": {} + }, + "issues": [ + { + "code": "additionalProperties", + "path": [ + "address" + ], + "params": { + "key": "address" + } + } + ] } ] } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java index 9eac0ec..032cb53 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java @@ -7,6 +7,7 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.function.BiFunction; /** What a handle derives from its node: constraints, choices, kind, field order and annotations. */ final class Derived { @@ -99,28 +100,37 @@ static FieldConstraints constraints(Object node, boolean required, Resolver reso return new FieldConstraints(isRequired, minLength, maxLength, min, max, step, multiple); } - /** An object's fields' constraints by dot path, nested objects included and lists left to their rows' handles. */ - static Map fieldConstraints(Object node, Resolver resolve) { + /** + * What {@code read} makes of each field of an object, by dot path, nested objects + * included and lists left to their rows' handles. A field it reads null for has no entry. + */ + private static Map byPath(Object node, Resolver resolve, BiFunction read) { Map resolved = Engine.resolveNode(node, resolve); - Map result = new LinkedHashMap<>(); - if (isObjectNode(resolved)) collectConstraints(resolved, "", resolve, result, identitySet()); + Map result = new LinkedHashMap<>(); + if (isObjectNode(resolved)) walk(resolved, "", resolve, read, result, identitySet()); return Collections.unmodifiableMap(result); } - private static void collectConstraints(Map node, String prefix, Resolver resolve, - Map result, Set seen) { + private static void walk(Map node, String prefix, Resolver resolve, + BiFunction read, Map result, Set seen) { if (!seen.add(node)) return; Map properties = Json.map(node.get("properties")); if (properties == null) return; List required = node.get("required") instanceof List ? (List) node.get("required") : List.of(); for (Map.Entry entry : properties.entrySet()) { String path = prefix + entry.getKey(); - result.put(path, constraints(entry.getValue(), required.contains(entry.getKey()), resolve)); + T found = read.apply(entry.getValue(), required.contains(entry.getKey())); + if (found != null) result.put(path, found); Map child = Engine.resolveNode(entry.getValue(), resolve); - if (isObjectNode(child)) collectConstraints(child, path + ".", resolve, result, seen); + if (isObjectNode(child)) walk(child, path + ".", resolve, read, result, seen); } } + /** An object's fields' constraints by dot path. */ + static Map fieldConstraints(Object node, Resolver resolve) { + return byPath(node, resolve, (property, required) -> constraints(property, required, resolve)); + } + /** * A node's choices in the order its rules list them, each as its value with * what the schema says about it: an {@code enum} value's entry in the @@ -176,24 +186,10 @@ static List options(Object node, Resolver resolve) { /** An object's fields' choices by dot path, only for fields that list some. */ static Map> fieldOptions(Object node, Resolver resolve) { - Map resolved = Engine.resolveNode(node, resolve); - Map> result = new LinkedHashMap<>(); - if (isObjectNode(resolved)) collectOptions(resolved, "", resolve, result, identitySet()); - return Collections.unmodifiableMap(result); - } - - private static void collectOptions(Map node, String prefix, Resolver resolve, - Map> result, Set seen) { - if (!seen.add(node)) return; - Map properties = Json.map(node.get("properties")); - if (properties == null) return; - for (Map.Entry entry : properties.entrySet()) { - String path = prefix + entry.getKey(); - List choices = choicesOf(entry.getValue(), resolve, false, identitySet()); - if (choices != null) result.put(path, Collections.unmodifiableList(choices)); - Map child = Engine.resolveNode(entry.getValue(), resolve); - if (isObjectNode(child)) collectOptions(child, path + ".", resolve, result, seen); - } + return byPath(node, resolve, (property, required) -> { + List choices = choicesOf(property, resolve, false, identitySet()); + return choices == null ? null : Collections.unmodifiableList(choices); + }); } /** diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java index 6d7950a..8a2c008 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java @@ -6,6 +6,7 @@ import com.featurevisor.sdk.VariableMutations; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -25,21 +26,21 @@ private Engine() {} "format")); static void report(Run run, Position at, String code, Map params) { - report(run, at, code, params, at.path, at, null); + report(run, at, code, params, null); } - static void report(Run run, Position at, String code, Map params, List path, - Messages.Lookup lookup, String ownMessage) { + /** Reports an issue at a position, with the message a check in code brings, which wins over every other. */ + static void report(Run run, Position at, String code, Map params, String ownMessage) { run.failed = true; - if (SHAPE_CODES.contains(code)) run.shapes.add(path); + if (SHAPE_CODES.contains(code)) run.shapes.add(at.path); if (run.trial) return; // The field's title, so a message can say `{title} is required`. - if (lookup.title != null) { + if (at.title != null) { params = new LinkedHashMap<>(params); - params.put("title", lookup.title); + params.put("title", at.title); } - String message = Messages.choose(code, params, path, lookup, run.sources, ownMessage); - SchemaIssue issue = new SchemaIssue(message, new ArrayList<>(path), code, params, run.schema, null); + String message = Messages.choose(code, params, at.path, at, run.sources, ownMessage); + SchemaIssue issue = new SchemaIssue(message, new ArrayList<>(at.path), code, params, run.schema, null); if (run.translate != null) { String translated = run.translate.translate(issue, run.sources.info); if (translated != null) issue = issue.withMessage(translated); @@ -118,13 +119,15 @@ private static List ownScopes(Object node, int base, Resolver re /** The node a reference resolves to, through any chain of references. */ static Map resolveNode(Object node, Resolver resolve) { - Set seen = new HashSet<>(); + // Only a reference needs to remember where it has been. + Set seen = null; Object current = node; while (true) { Map map = Json.map(current); if (map == null) return null; String schema = Json.string(map.get("schema")); if (schema == null) return map; + if (seen == null) seen = new HashSet<>(); if (!seen.add(schema)) return null; current = resolve.node(schema); } @@ -175,16 +178,15 @@ private static Validator compileConstList(Map node, Resolver res }; } - /** The kinds each branch takes, kept until a branch's reference resolves to another schema. */ - private static final class OneOfKinds { + /** The branches a {@code oneOf} selects by the kind of the value, kept until a branch's reference resolves to another schema. */ + private static final class OneOfSelect { final List> nodes; - final List> kinds; - final boolean disjoint; + /** The branch each kind of value selects, or null when the branches do not tell their values apart by kind. */ + final Map select; - OneOfKinds(List> nodes, List> kinds, boolean disjoint) { + OneOfSelect(List> nodes, Map select) { this.nodes = nodes; - this.kinds = kinds; - this.disjoint = disjoint; + this.select = select; } } @@ -193,43 +195,31 @@ private static Validator compileOneOf(Map node, Resolver resolve List branchNodes = (List) node.get("oneOf"); List branches = new ArrayList<>(); for (Object branch : branchNodes) branches.add(compileNode(branch, resolve)); - OneOfKinds[] cached = new OneOfKinds[1]; + OneOfSelect[] cached = new OneOfSelect[1]; return (value, run, at) -> { List> nodes = new ArrayList<>(); for (Object branch : branchNodes) nodes.add(resolveNode(branch, resolve)); - OneOfKinds kinds = cached[0]; - if (kinds == null || !sameNodes(kinds.nodes, nodes)) { - List> sets = new ArrayList<>(); - boolean all = true; - for (Map resolved : nodes) { - Set set = resolved == null ? null : branchKinds(resolved); - if (set == null) all = false; - sets.add(set); - } - boolean disjoint = all; - for (int index = 0; disjoint && index < sets.size(); index++) { - for (int other = 0; other < sets.size(); other++) { - if (other == index) continue; - for (String kind : sets.get(index)) { - if (sets.get(other).contains(kind)) { disjoint = false; break; } - } + OneOfSelect current = cached[0]; + if (current == null || !sameNodes(current.nodes, nodes)) { + // The branches are disjoint when no kind of value is taken by two of them, so a kind selects its branch. + Map select = new HashMap<>(); + for (int index = 0; select != null && index < nodes.size(); index++) { + Set kinds = nodes.get(index) == null ? null : branchKinds(nodes.get(index)); + if (kinds == null) select = null; + else for (String kind : kinds) { + if (select.putIfAbsent(kind, index) != null) { select = null; break; } } } - kinds = new OneOfKinds(nodes, sets, disjoint); - cached[0] = kinds; + current = new OneOfSelect(nodes, select); + cached[0] = current; } - if (kinds.disjoint) { + if (current.select != null) { // The value's type selects a branch, whose own issues are the ones reported. - String kind = Json.kindOf(value); - for (int index = 0; index < kinds.kinds.size(); index++) { - if (kinds.kinds.get(index).contains(kind)) { - branches.get(index).validate(value, run, at); - return; - } - } - report(run, at, "oneOf", params("matches", 0)); + Integer selected = current.select.get(Json.kindOf(value)); + if (selected == null) report(run, at, "oneOf", params("matches", 0)); + else branches.get(selected).validate(value, run, at); return; } @@ -334,11 +324,6 @@ else if (!(list.get(index) instanceof String)) { }; } - /** An object's messages for a key it has no field for, which has no title of its own. */ - private static Messages.Lookup untitled(Position at) { - return new Messages.Lookup(at.mpath, at.scopes, null, null); - } - private static Validator compileObject(Map node, Resolver resolve) { Map properties = Json.map(node.get("properties")); Map compiled = new LinkedHashMap<>(); @@ -367,8 +352,8 @@ private static Validator compileObject(Map node, Resolver resolv List mpath = append(at.mpath, key); List scopes = new ArrayList<>(at.scopes); ownScopes(properties.get(key), mpath.size(), resolve, scopes); - report(run, at, "required", params("key", key), append(at.path, key), - new Messages.Lookup(mpath, scopes, titleOf(properties.get(key), resolve), null), null); + report(run, new Position(append(at.path, key), mpath, scopes, titleOf(properties.get(key), resolve)), + "required", params("key", key)); } } @@ -384,11 +369,12 @@ private static Validator compileObject(Map node, Resolver resolv compiledAdditional.validate(child, run, new Position(append(at.path, key), append(at.mpath, "*"), at.scopes, null)); } else if (properties != null || closed) { // An extra key has no field of its own, so the object that rejects it words its issue, without a title. - report(run, at, "additionalProperties", params("key", key), append(at.path, key), untitled(at), null); + report(run, new Position(append(at.path, key), at.mpath, at.scopes, null), + "additionalProperties", params("key", key)); } else if (!Json.isPrimitive(child)) { // Without `properties` or `additionalProperties`, an object is flat. - report(run, at, "type", params("type", "primitive", "received", Json.kindOf(child)), - append(at.path, key), untitled(at), null); + report(run, new Position(append(at.path, key), at.mpath, at.scopes, null), + "type", params("type", "primitive", "received", Json.kindOf(child))); } } }; @@ -595,6 +581,13 @@ static String matchingMutations(Map node, Object value, Matcher return id.toString(); } + /** The indexes of the mutations an id such as {@code 0,2,} names, in order. */ + private static List matchedOf(String id) { + List matched = new ArrayList<>(); + for (String index : id.split(",")) if (!index.isEmpty()) matched.add(Integer.parseInt(index)); + return matched; + } + /** A node's rules with the mutations an id names applied in order, without {@code mutations}, the same object for the same id. */ @SuppressWarnings("unchecked") static Map mutatedRules(Map node, String id, Resolver resolve) { @@ -602,9 +595,8 @@ static Map mutatedRules(Map node, String id, Res List> mutations = mutationsOf(node); Object rules = new LinkedHashMap<>(node); ((Map) rules).remove("mutations"); - for (String index : id.split(",")) { - if (index.isEmpty()) continue; - Object operations = mutations.get(Integer.parseInt(index)).get("operations"); + for (int index : matchedOf(id)) { + Object operations = mutations.get(index).get("operations"); rules = VariableMutations.applyVariableOperations(rules, operations instanceof List ? (List) operations : null); } return (Map) rules; @@ -648,9 +640,7 @@ private static Validator compileMutations(Map node, Resolver res if (variant == null) { try { Map rules = mutatedRules(node, id, resolve); - List matched = new ArrayList<>(); - for (String index : id.split(",")) if (!index.isEmpty()) matched.add(Integer.parseInt(index)); - variant = new Variant(compileNode(rules, resolve), rules, matched); + variant = new Variant(compileNode(rules, resolve), rules, matchedOf(id)); } catch (RuntimeException failure) { variant = new Variant(failure); } @@ -670,8 +660,9 @@ private static Validator compileMutations(Map node, Resolver res // A mutation inside the node applies last, so its claim stands. if (issue.getMutation() != null) continue; List relative = issue.getPath().subList(Math.min(at.path.size(), issue.getPath().size()), issue.getPath().size()); + // An `issues` entry is claimed by the node's `issues`, which no rule's place says. List rule = new ArrayList<>(); - boolean whole = ruleOf(variant.rules, relative, issue.getCode(), rule); + boolean whole = !issue.getCode().equals("refine") && ruleOf(variant.rules, relative, issue.getCode(), rule); for (int index = variant.matched.size() - 1; index >= 0; index--) { Map mutation = mutations.get(variant.matched.get(index)); if (setsRule(mutation, issue, rule, whole)) { @@ -719,9 +710,7 @@ private static Validator compileIssues(Map node, Validator rules String ownPath = entry == null ? null : Json.string(entry.get("path")); own.add(ownPath == null || ownPath.isEmpty() ? List.of() : Arrays.asList(ownPath.split("\\.", -1))); if (entry != null) { - Views.inputsOf(entry.get("conditions"), read -> { - if (read instanceof String) own.add(Arrays.asList(((String) read).split("\\.", -1))); - }); + Views.inputsOf(entry.get("conditions"), read -> own.add(Arrays.asList(read.split("\\.", -1)))); } waits.add(own); } @@ -740,8 +729,8 @@ private static Validator compileIssues(Map node, Validator rules List> wait = waits.get(entryIndex); if (found.stream().anyMatch(path -> wait.stream().anyMatch(scope -> atOrInside(path, scope)))) continue; if (!run.match.match(entry.get("conditions"), input)) continue; - String path = Json.string(entry.get("path")); - List parts = path == null || path.isEmpty() ? List.of() : Arrays.asList(path.split("\\.", -1)); + // The entry's own path, split once when compiled. + List parts = wait.get(0); List scopes = new ArrayList<>(at.scopes); Object field = node; for (int index = 0; index < parts.size(); index++) { @@ -754,9 +743,8 @@ private static Validator compileIssues(Map node, Validator rules issuePath.addAll(parts); List mpath = new ArrayList<>(at.mpath); mpath.addAll(parts); - report(run, at, "refine", params("refine", entry.get("key")), issuePath, - new Messages.Lookup(mpath, scopes, parts.isEmpty() ? at.title : titleOf(field, resolve), - Json.string(entry.get("message"))), null); + report(run, new Position(issuePath, mpath, scopes, parts.isEmpty() ? at.title : titleOf(field, resolve), + Json.string(entry.get("message"))), "refine", params("refine", entry.get("key"))); } }; } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java index dc8ca4d..7987d84 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Paths.java @@ -56,9 +56,7 @@ static List parse(String path) { int end = path.indexOf(']', index); String inside = end == -1 ? path.substring(index + 1) : path.substring(index + 1, end); if (inside.isEmpty()) steps.add(Step.ITEMS); - else if (inside.equals("*")) steps.add(Step.VALUES); - else if (isIndex(inside)) steps.add(Step.index(Integer.parseInt(inside))); - else steps.add(Step.key(inside.replaceAll("^[\"']|[\"']$", ""))); + else steps.add(stepOf(inside, inside.replaceAll("^[\"']|[\"']$", ""))); index = end == -1 ? path.length() : end + 1; } else { key.append(character); @@ -69,16 +67,20 @@ static List parse(String path) { return steps; } - private static boolean isIndex(String text) { + /** A step from its text: {@code *}, an index, or a key, which is {@code key} when quotes were taken off it. */ + private static Step stepOf(String text, String key) { + if (text.equals("*")) return Step.VALUES; + return isIndex(text) ? Step.index(Integer.parseInt(text)) : Step.key(key); + } + + static boolean isIndex(String text) { return text.length() < 10 && INDEX.matcher(text).matches(); } private static void flush(StringBuilder key, List steps) { if (key.length() == 0) return; String text = key.toString(); - if (text.equals("*")) steps.add(Step.VALUES); - else if (isIndex(text)) steps.add(Step.index(Integer.parseInt(text))); - else steps.add(Step.key(text)); + steps.add(stepOf(text, text)); key.setLength(0); } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java index 3e93a03..8578d28 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Position.java @@ -7,12 +7,12 @@ final class Position extends Messages.Lookup { final List path; Position(List path, List mpath, List scopes, String title) { - super(mpath, scopes, title, null); - this.path = path; + this(path, mpath, scopes, title, null); } - Position(List path, Messages.Lookup lookup) { - super(lookup.mpath, lookup.scopes, lookup.title, lookup.own); + /** With the message an {@code issues} entry words its issue by. */ + Position(List path, List mpath, List scopes, String title, String own) { + super(mpath, scopes, title, own); this.path = path; } } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 0e1a6f1..131ffc8 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -457,7 +457,7 @@ private void reportCheck(Run run, Located located, List slot, Strin // Answers can arrive on other threads, and the run's list is not theirs to share. synchronized (run) { int before = run.issues.size(); - Engine.report(run, new Position(at, lookup), code, params, at, lookup, own); + Engine.report(run, new Position(at, lookup.mpath, lookup.scopes, lookup.title), code, params, own); List added = run.issues.subList(before, run.issues.size()); slot.addAll(added); added.clear(); @@ -477,7 +477,10 @@ public SchemaHandle at(String path) { * {@code a.b}, {@code *} or {@code 2024}, which a path would read otherwise. */ SchemaHandle child(String key) { - if (key.matches("[^.\\[\\]*\\d][^.\\[\\]]*")) return at(key); + if (!key.isEmpty() && !key.equals("*") && !Paths.isIndex(key) && key.indexOf('.') < 0 && key.indexOf('[') < 0 + && key.indexOf(']') < 0) { + return at(key); + } return handle("\u0000" + key, () -> List.of(Paths.Step.key(key))); } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java index 869d44b..db2067e 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java @@ -34,18 +34,8 @@ final class Store implements Resolver { private final Runnable removeModule; private FeaturevisorUnsubscribe stopListening; - private static final class Compiled { - final Object entry; - final Validator validate; - - Compiled(Object entry, Validator validate) { - this.entry = entry; - this.validate = validate; - } - } - /** A key that compares by identity, for caches of the datafile's own nodes. */ - private static final class Identity { + static final class Identity { final Object value; Identity(Object value) { this.value = value; } @@ -54,14 +44,42 @@ private static final class Identity { @Override public int hashCode() { return System.identityHashCode(value); } } - private final Map compiled = new ConcurrentHashMap<>(); - private volatile Map>> mutated = new ConcurrentHashMap<>(); - private volatile Map nodes = new ConcurrentHashMap<>(); + private final Generations>> mutated = new Generations<>(); + private final Generations nodes = new Generations<>(); private final Set reported = ConcurrentHashMap.newKeySet(); private final Set reportedPatterns = ConcurrentHashMap.newKeySet(); private final Set reportedDepths = ConcurrentHashMap.newKeySet(); private final Set reportedMutations = ConcurrentHashMap.newKeySet(); + /** + * A cache keyed by the datafile's own nodes, in two generations. A datafile change starts a new + * one, and a lookup that misses it moves a hit from the one before, so a node the new datafile + * keeps stays cached, and one unused for two changes goes. Memory holds two datafiles' worth. + */ + static final class Generations { + private volatile Map current = new ConcurrentHashMap<>(); + private volatile Map previous = new ConcurrentHashMap<>(); + + V get(Identity key) { + V found = current.get(key); + if (found != null) return found; + found = previous.get(key); + if (found == null) return null; + V existing = current.putIfAbsent(key, found); + return existing != null ? existing : found; + } + + V putIfAbsent(Identity key, V value) { + V existing = current.putIfAbsent(key, value); + return existing != null ? existing : value; + } + + void next() { + previous = current; + current = new ConcurrentHashMap<>(); + } + } + /** SDK instances whose schemas module holds the package's name, which only one module on an instance can. */ private static final Map NAMED = Collections.synchronizedMap(new WeakHashMap<>()); private static final String NAME = "@featurevisor/schemas"; @@ -91,11 +109,10 @@ private static final class Identity { + Schemas.FIRST_RELEASE + " or later."); } this.api = moduleApi; - // Caches keyed by the datafile's nodes start afresh with every datafile, whose - // entries are new objects even when their hashes stay, so they never outgrow one. + // Caches keyed by the datafile's nodes keep what a datafile leaves alone, for two datafiles at most. this.stopListening = f.on(FeaturevisorEventName.DATAFILE_SET, details -> { - mutated = new ConcurrentHashMap<>(); - nodes = new ConcurrentHashMap<>(); + mutated.next(); + nodes.next(); }); } @@ -147,25 +164,18 @@ public Map node(String key) { @Override public Resolved resolve(String key) { Map node = entry(key); - if (node == null) return null; - Compiled cached = compiled.get(key); - if (cached != null && cached.entry == node) return new Resolved(node, cached.validate); - Validator validate = Engine.compileNode(node, this); - compiled.put(key, new Compiled(node, validate)); - return new Resolved(node, validate); + return node == null ? null : new Resolved(node, compile(node)); } - /** A node's validator, kept per node, since a view's nodes are the same object for the same mutations. */ + /** + * A node's validator, kept per node and shared by every handle, since a datafile's entries + * and a view's nodes are the same object for the same mutations. + */ Validator compile(Object node) { if (!(node instanceof Map)) return Engine.compileNode(node, this); Identity key = new Identity(node); - Map current = nodes; - Validator validate = current.get(key); - if (validate == null) { - validate = Engine.compileNode(node, this); - current.putIfAbsent(key, validate); - } - return validate; + Validator validate = nodes.get(key); + return validate != null ? validate : nodes.putIfAbsent(key, Engine.compileNode(node, this)); } /** What a schema's package evaluation gives: its context and a matcher for its conditions. */ @@ -192,13 +202,9 @@ T evaluate(String key, Map context, Function callb @Override public Map mutated(Map node, String id, Supplier> make) { - Map>> current = mutated; Identity key = new Identity(node); - Map> byId = current.get(key); - if (byId == null) { - current.putIfAbsent(key, new ConcurrentHashMap<>()); - byId = current.get(key); - } + Map> byId = mutated.get(key); + if (byId == null) byId = mutated.putIfAbsent(key, new ConcurrentHashMap<>()); Map rules = byId.get(id); if (rules == null) { rules = make.get(); @@ -272,6 +278,9 @@ static final class Location { } } + /** The node of every item of an array without {@code items}, one object so a cache keyed by node hits. */ + private static final Map STRING_ITEMS = Map.of("type", "string"); + /** How a view walks: its values, from which step they apply, and what applies a node's matching mutations. */ static final class Walk { final Object value; @@ -302,7 +311,8 @@ static Location locate(Resolver resolve, Object root, List steps, Li for (int index = 0; index < steps.size(); index++) { Paths.Step step = steps.get(index); - BiFunction adjust = walk != null && index >= walk.from ? walk.adjust : null; + boolean inView = walk != null && index >= walk.from; + BiFunction adjust = inView ? walk.adjust : null; // The node's messages, then those of each schema it references, at the same depth. List seen = new ArrayList<>(); Object resolved = adjust != null ? adjust.apply(node, value) : node; @@ -320,11 +330,10 @@ static Location locate(Resolver resolve, Object root, List steps, Li resolved = adjust != null ? adjust.apply(targetNode, value) : targetNode; } if (current.get("oneOf") instanceof List) return null; - boolean inView = walk != null && index >= walk.from; + required = false; if (step.kind == Paths.Kind.KEY) { Map properties = Json.map(current.get("properties")); - required = false; if (properties != null && properties.containsKey(step.key)) { node = properties.get(step.key); mpath.add(step.key); @@ -339,7 +348,6 @@ static Location locate(Resolver resolve, Object root, List steps, Li continue; } - required = false; if (step.kind == Paths.Kind.VALUES) { if (!(current.get("additionalProperties") instanceof Map)) return null; node = current.get("additionalProperties"); @@ -351,7 +359,7 @@ static Location locate(Resolver resolve, Object root, List steps, Li // An index or `[]`: every item of an array is described alike. if (!"array".equals(current.get("type"))) return null; - node = current.containsKey("items") ? current.get("items") : Map.of("type", "string"); + node = current.containsKey("items") ? current.get("items") : STRING_ITEMS; mpath.add("[]"); if (inView) { List list = Json.list(value); diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java index 90ef032..d128148 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Views.java @@ -108,7 +108,7 @@ static Object place(Object values, List steps, Object value) { } /** Calls back with the input paths conditions read, in {@code input} and {@code valueFrom}, through every group. */ - static void inputsOf(Object conditions, Consumer found) { + static void inputsOf(Object conditions, Consumer found) { // Datafiles can carry conditions as JSON text, as features' are. if (conditions instanceof String) { String text = ((String) conditions).stripLeading(); @@ -125,8 +125,8 @@ static void inputsOf(Object conditions, Consumer found) { } Map map = Json.map(conditions); if (map == null) return; - found.accept(map.get("input")); - if (map.get("valueFrom") instanceof Map) found.accept(Json.get(map.get("valueFrom"), "input")); + if (map.get("input") instanceof String) found.accept((String) map.get("input")); + if (Json.get(map.get("valueFrom"), "input") instanceof String) found.accept((String) Json.get(map.get("valueFrom"), "input")); for (String group : List.of("and", "or", "not")) inputsOf(map.get(group), found); } @@ -148,8 +148,7 @@ private static void visit(Object node, String at, List seen, Resolver re if (!(current.get(list) instanceof List)) continue; for (Object entry : (List) current.get(list)) { inputsOf(Json.get(entry, "conditions"), path -> { - if (!(path instanceof String)) return; - String joined = at.isEmpty() ? (String) path : at + "." + path; + String joined = join(at, path); if (!reads.contains(joined)) reads.add(joined); }); } diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java index 1678355..168fe4c 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -342,6 +342,65 @@ void contextAModuleAddsReachesMutationsIssueEntriesAndViewsAsItReachesFlags() { for (String evaluation : seen) assertEquals("schema signUp", evaluation); } + @Test + void aFieldKeyThatStartsWithADigitButIsNotAnIndexGivesTheHandleAtGives() { + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile("1", "{\"login\":{\"hash\":\"l1\",\"type\":\"object\",\"properties\":{" + + "\"2fa\":{\"type\":\"string\"},\"01\":{\"type\":\"string\"},\"a.b\":{\"type\":\"string\"}}}}")) + .logLevel(FeaturevisorLogLevel.WARN)); + SchemaHandle login = Schemas.create(f).get("login"); + List fields = login.getFields(); + assertEquals(List.of("01", "2fa", "a.b"), List.of(fields.get(0).getName(), fields.get(1).getName(), fields.get(2).getName())); + assertSame(login.at("01"), fields.get(0)); + assertSame(login.at("2fa"), fields.get(1)); + assertEquals("2fa", fields.get(1).getPath()); + } + + @Test + void aNodeCompilesOnceForTheInstanceWhateverHandleAsksForIt() { + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile("1", "{\"list\":{\"hash\":\"l1\",\"type\":\"array\"}}")) + .logLevel(FeaturevisorLogLevel.WARN)); + Store store = new Store(f); + try { + Resolver.Resolved root = store.resolve("list"); + assertSame(root.validate, store.resolve("list").validate); + assertSame(root.validate, store.compile(root.node)); + // Every item of an array without `items` is the same node, so a view's fields share a validator too. + Store.Location first = Store.locate(store, root.node, Paths.parse("[0]"), List.of(), List.of(), null); + Store.Location second = Store.locate(store, root.node, Paths.parse("[1]"), List.of(), List.of(), null); + assertSame(first.node, second.node); + } finally { + store.close(); + } + } + + @Test + void compiledNodesSurviveADatafileThatLeavesThemAloneForOneChangeAndGoAfterTwo() { + Featurevisor f = Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile("1", SCHEMAS)) + .logLevel(FeaturevisorLogLevel.WARN)); + Store store = new Store(f); + try { + Resolver.Resolved first = store.resolve("signUp"); + // A merge whose patch leaves the schemas section out keeps the entry objects. + f.setDatafile("{\"schemaVersion\":\"4\",\"revision\":\"2\",\"segments\":{},\"features\":{},\"variables\":{}}", false); + assertSame(first.node, store.entry("signUp")); + assertSame(first.validate, store.resolve("signUp").validate); + // The hit moved into the new generation, so it outlives the next change as well. + f.setDatafile("{\"schemaVersion\":\"4\",\"revision\":\"3\",\"segments\":{},\"features\":{},\"variables\":{}}", false); + assertSame(first.validate, store.resolve("signUp").validate); + // A node nobody asked for through two changes is gone. + Resolver.Resolved unused = store.resolve("spaced"); + f.setDatafile("{\"schemaVersion\":\"4\",\"revision\":\"4\",\"segments\":{},\"features\":{},\"variables\":{}}", false); + f.setDatafile("{\"schemaVersion\":\"4\",\"revision\":\"5\",\"segments\":{},\"features\":{},\"variables\":{}}", false); + assertSame(unused.node, store.entry("spaced")); + assertFalse(unused.validate == store.resolve("spaced").validate); + } finally { + store.close(); + } + } + private static List codesAt(ValidationResult result) { List codes = new ArrayList<>(); for (SchemaIssue issue : result.getIssues()) { From 7670c75be8158f81d6fbae941b494a5d3cbe9031 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Sun, 29 Nov 2026 23:22:47 +0100 Subject: [PATCH 17/21] docs: beforeEvaluation runs for a schema validation too The Modules section said beforeEvaluation and afterEvaluation run for flags, variations and both kinds of variable, while a schema validation also runs every module's beforeEvaluation, with getType() and getKey() naming the schema instead of a feature key, and never runs afterEvaluation. It now says so, and to check the type before reading the keys, as the JavaScript SDK's page does. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index d033428..01a3747 100644 --- a/README.md +++ b/README.md @@ -673,6 +673,8 @@ FeaturevisorModule auditModule = new FeaturevisorModule("audit") `beforeEvaluation` and `afterEvaluation` run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a feature key is a global one. +`beforeEvaluation` also runs when a [schema](#schemas) validates, with `getType()` `schema` and the schema's key in `getKey()` instead of a feature key, so context it adds reaches the schema's conditions too. `afterEvaluation` does not run then, since a validation's result is not an evaluation. Check the type before reading the keys. + The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress. If `setup` throws, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports `module_setup_error`, and calls its `close` if it has one. From 473fc0a825332b27b3dc2881c4a374fe6eea3429 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Mon, 30 Nov 2026 20:06:43 +0100 Subject: [PATCH 18/21] fix(schemas): follow the JavaScript release fixes A schema used twice, such as an address for billing and for shipping, lost its constraints and choices the second time, since walks stopped at any schema already seen. The port now follows the JavaScript package's release fixes. Walks guard only the current path, and kind stops on a list of itself. A missing field reports no missing schema, the message translator runs last, and required applies without properties. A value nested more than 128 references deep fails closed at the 129th, and a check that throws fails closed with schema_check_error. Every diagnostic's dedupe resets with a new datafile, no handle is kept for a key the datafile lacks, patterns compile once into a cache capped at 4096 that holds failures, and an unknown type fails every value. Both conformance fixtures are copied again from the monorepo, with 150 validation cases and an address schema used twice. The README says how a field's handle treats a missing value and when schema_check_error is reported, and gives no minimum CLI version. HandleOptions keeps the handles made from it for as long as it lives, and a view's memo follows the context and sticky values. The release scripts check every artifact's version, and the README's stale second Schemas section is gone. --- README.md | 129 +++---------- conformance/schemas-datafile.json | 110 ++++++++++- conformance/schemas-validation.json | 83 +++++++- .../com/featurevisor/schemas/Derived.java | 40 +++- .../java/com/featurevisor/schemas/Engine.java | 52 +++-- .../featurevisor/schemas/HandleOptions.java | 24 ++- .../com/featurevisor/schemas/Patterns.java | 11 +- .../com/featurevisor/schemas/Resolver.java | 9 +- .../featurevisor/schemas/SchemaHandle.java | 55 ++++-- .../com/featurevisor/schemas/Schemas.java | 18 +- .../java/com/featurevisor/schemas/Store.java | 86 +++++++-- .../schemas/SchemasReleaseTest.java | 179 ++++++++++++++++++ scripts/test-release.sh | 11 +- scripts/verify-release.sh | 21 +- 14 files changed, 655 insertions(+), 173 deletions(-) create mode 100644 featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java diff --git a/README.md b/README.md index 01a3747..0415764 100644 --- a/README.md +++ b/README.md @@ -52,13 +52,9 @@ The Featurevisor Java SDK evaluates flags, variations and variables in Java and - [Validate on the server](#validate-on-the-server) - [Listen for changes](#listen-for-changes) - [Patterns](#patterns) + - [When a schema fails values closed](#when-a-schema-fails-values-closed) - [Close](#close) - [OpenFeature](#openfeature) -- [Schemas](#schemas) - - [Handles](#handles) - - [Messages](#messages) - - [Checks in code](#checks-in-code) - - [Patterns](#patterns) - [CLI usage](#cli-usage) - [Test](#test) - [Benchmark](#benchmark) @@ -796,7 +792,7 @@ A handle is one schema as an object your code holds: it validates, and describes SchemaHandle signUp = s.get("signUp"); ``` -A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. +A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application. `s.get(key, options)` gives the same handle for the same `HandleOptions` object, so build the options once. A key the datafile lacks keeps no handle. | Member | What it is | | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- | @@ -854,7 +850,7 @@ A handle's `getAnnotations()` are its node's own, and `getFields()` gives an obj ```java signUp.getAnnotations().get("title"); // "Create your account" -signUp.getFields().stream().map(SchemaHandle::getPath).toList(); +signUp.getFields().stream().map(SchemaHandle::getPath).collect(Collectors.toList()); // [displayName, email, country] ``` @@ -907,11 +903,12 @@ SchemaHandle signUp = s.get("signUp", new HandleOptions() ValidationResult result = signUp.validate(value); ``` -- A check gets the value at its path, and a `CheckInfo` with the whole input and the context, where `info.read("country")` reads another field. It returns `true` when the value passes. +- A check gets the value at its path, and a `CheckInfo` with the context and the input, where `info.read("country")` reads another field. The input is the whole value, except in a field's handle outside a [view](#follow-the-values-typed-so-far) taken at the schema's root, where it is the field's value. It returns `true` when the value passes. - It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database. - Without a path, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total. - Its issue has code `refine` and the `refine` param `"nameAvailable"`, with the field's title. A check that throws gives `refineError`, and validation fails closed. -- `Refinement.async` takes a check returning a `CompletionStage`. `validate` waits for it, and `validateAsync` returns a `CompletableFuture` instead. +- `Refinement.async` takes a check returning a `CompletionStage`. `validate` waits for it, and `validateAsync` returns a `CompletableFuture` instead. Cancelling that future stops waiting for the checks. It does not reach the work your application started. +- A check that throws, or completes exceptionally, also reports one `schema_check_error` [diagnostic](#when-a-schema-fails-values-closed). ### Options from your application @@ -966,7 +963,20 @@ A datafile whose schema is unchanged calls nothing. `s.close()` stops every list ### Patterns -Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. +Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value. + +### When a schema fails values closed + +A schema that cannot answer fails the value closed and says why with an `ERROR` [diagnostic](#diagnostics), once per schema and datafile revision: + +- `schema_pattern_unsupported`: a pattern does not compile. +- `schema_mutation_error`: a mutation's operations cannot be applied. The value fails with `refineError`. +- `schema_reference_depth`: the value is nested more than 128 references deep, which is how deep a tree of nodes that each reference the tree's schema can go. The 129th fails with `refineError`. +- `schema_check_error`: a [check in code](#check-in-code) or an option source's lookup threw, or completed exceptionally. The value fails with `refineError`. `details` holds `schemaKey`, `check` and `path`, and `originalError` the exception. A check that fails because the validation was cancelled reports nothing. + +A `type` the package does not know fails every value with a `type` issue. `required` lists keys that must be there whatever `properties` holds, so an object with `additionalProperties` only, or no `properties` at all, still reports each missing key. + +A field handle for a field the schema lacks reports its `schemaNotFound` issue, with `field`, and no `schema_not_found` diagnostic, which is for a schema the datafile lacks. Java has no "no value" for a field handle to validate, since `null` is a value, so a field validated alone is never read as absent. Validate the whole value to have `required` reported. ## Close @@ -1028,94 +1038,6 @@ Composed values map to `TARGETING_MATCH` without additional JSON decoding. Unmet See the [OpenFeature provider guide](https://featurevisor.com/docs/sdks/openfeature/) for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages. -## Schemas - -Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/) a datafile carries, such as a sign up form's request, with the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript. They are published as a separate artifact, with the same version as the Featurevisor Java SDK: - -```xml - - com.featurevisor - featurevisor-schemas - 5.0.0 - -``` - -Create one `Schemas` instance per Featurevisor instance, and validate by a schema's key: - -```java -import com.featurevisor.schemas.Schemas; -import com.featurevisor.schemas.SchemaIssue; -import com.featurevisor.schemas.ValidationResult; - -Schemas schemas = Schemas.create(f); - -ValidationResult result = schemas.validate("signUp", request); - -if (!result.isValid()) { - for (SchemaIssue issue : result.getIssues()) { - System.out.println(issue.getField() + ": " + issue.getMessage()); - } -} -``` - -A value can be maps, lists, strings, numbers, booleans and `null`, a Jackson `JsonNode`, or any object Jackson can convert, such as a request class with getters. `parse` returns the value when it passes and throws a `SchemaValidationException` with the issues when it does not. `flatten()` on a result or an exception groups the messages by field name, such as `displayName` or `items.0.name`, for an error response. - -Every call reads the current datafile, so a new datafile takes effect at the next validation. A context passed to `validate` is merged over the instance's, for rules that change by segment. Validation runs as the schema's evaluation, so a module's `beforeEvaluation` sees type `schema` and the schema's key, and context it adds reaches every condition, as it does for flags. - -### Handles - -`schemas.get(key)` returns a schema's handle, and `at(path)` a field's, such as `address.city` or `items[].name`. A handle describes what its rules imply for rendering a form: - -```java -SchemaHandle signUp = schemas.get("signUp"); - -signUp.getFields(); // handles for accountType, displayName and taxId, in the schema's order -signUp.at("displayName").getConstraints(); // required, minLength and maxLength -signUp.at("accountType").getOptions(); // personal and business, with their titles -signUp.at("accountType").getKind(); // FieldKind.SELECT -``` - -`getConstraints().toAttributes()` gives them as HTML attributes, such as `required` and `maxlength`. `withInput(values)` returns the same handle for the values a form has so far, so its members describe the rules every matching mutation sets, such as a VAT number that becomes required for a business account. - -### Messages - -Issues are worded by the form's messages, then the schema's, then the application's, then a default in English: - -```java -Schemas schemas = Schemas.create(f, new SchemasOptions() - .message("required", "{title} is required") - .translator((issue, info) -> translations.get(issue.getCode()))); -``` - -A translator returning `null` keeps the chosen message. - -### Checks in code - -Refinements check what rules cannot express, and option sources check a value against choices from the application. Both run after the rules, only where the rules found nothing: - -```java -SchemaHandle signUp = schemas.get("signUp", new HandleOptions() - .refine( - Refinement.of("passwordsMatch", "confirmPassword", - (value, info) -> value.equals(info.read("password"))) - .reads("password") - .message("Passwords must match"), - Refinement.async("usernameFree", "username", - (value, info) -> users.isFreeAsync((String) value))) - .optionSource( - OptionSource.of("cities", "city") - .search((query, info) -> cities.search(query)) - .lookup((value, info) -> cities.find((String) value)))); -``` - -`validate` waits for checks that answer later, and `validateAsync` returns a `CompletableFuture` instead. A lookup that finds nothing reports `enum`, and a check that throws reports `refineError`. `search(query)` on the field's handle returns the source's suggestions. - -Handles are safe to share between threads. `close()` on the instance stops its subscriptions and removes its module from the Featurevisor instance. - -### Patterns - -Schema patterns are JavaScript regular expressions with the `u` flag, and they mean the same here: `$` is the end of the value, `\s` is JavaScript's whitespace, and `.` reads an emoji as one character, as lengths do. A pattern that does not compile with `u`, such as `[a-z\_]`, fails every value with one `schema_pattern_unsupported` diagnostic. A mutation whose operations cannot be applied fails the value with `refineError` and one `schema_mutation_error` diagnostic, and so does a schema that follows references more than 128 deep without reading deeper into the value, with `schema_reference_depth`. - ## CLI usage Compile the CLI module from this SDK repository: @@ -1124,7 +1046,7 @@ Compile the CLI module from this SDK repository: mvn -pl featurevisor-sdk compile ``` -The native test runner requires `@featurevisor/cli` 4.0.0 or later and Node.js 24 or later. Install the Node.js CLI in your Featurevisor project: +The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project: ```bash npm install --save-dev @featurevisor/cli@^4.0.0 @@ -1240,11 +1162,14 @@ bash scripts/test-release.sh 5.0.0 These checks create temporary flat, environment and sets projects without changing the monorepo or downloading packages. The classpath command above uses the POSIX `:` separator. -The repository is a Maven reactor with two published libraries: +The repository is a Maven reactor with three published libraries: - `com.featurevisor:featurevisor-java` +- `com.featurevisor:featurevisor-schemas` - `com.featurevisor:featurevisor-openfeature` +Every installation example in this README must match the release version, whichever artifact it installs. + To verify their published JAR and POM boundaries locally: ```bash @@ -1253,11 +1178,11 @@ $ make verify-artifacts ### Releasing -The SDK, provider and parent POM share version `5.0.0`. Before tagging, run `bash scripts/verify-release.sh v5.0.0` to check the Maven revision, CLI and both README installation examples. +The SDK, schemas, provider and parent POM share version `5.0.0`. Before tagging, run `bash scripts/verify-release.sh v5.0.0` to check the Maven revision, CLI and every README installation example. 1. Merge the release changes into `main`. 2. Tag the release with a `v` prefix, such as `vX.Y.Z`, and push the tag. -3. GitHub Actions verifies and publishes the parent POM, Java SDK, and OpenFeature provider to [GitHub Packages](https://github.com/orgs/featurevisor/packages?repo_name=featurevisor-java). +3. GitHub Actions verifies and publishes the parent POM, Java SDK, schemas and OpenFeature provider to [GitHub Packages](https://github.com/orgs/featurevisor/packages?repo_name=featurevisor-java). 4. Create the corresponding [GitHub release](https://github.com/featurevisor/featurevisor-java/releases). ## License diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index affb9bc..e0642b2 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -4,7 +4,7 @@ "datafile": { "schemaVersion": "4", "featurevisorVersion": "4.13.0", - "revision": "Y2jhtKdlDE", + "revision": "IvtVCaCgSZ", "segments": { "netherlands": { "conditions": "{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}" @@ -16,8 +16,28 @@ "features": {}, "variables": {}, "schemas": { + "address": { + "hash": "VGKVaf20da", + "type": "object", + "properties": { + "city": { + "type": "string", + "maxLength": 40 + }, + "country": { + "type": "string", + "enum": [ + "GB", + "NL" + ] + } + }, + "required": [ + "city" + ] + }, "checkout": { - "hash": "gSboXrZWcM", + "hash": "CrZt1Can24", "type": "object", "properties": { "billingCountry": { @@ -34,6 +54,12 @@ }, "confirmPassword": { "type": "string" + }, + "billing": { + "schema": "address" + }, + "shipping": { + "schema": "address" } }, "required": [ @@ -77,7 +103,7 @@ } }, "register": { - "hash": "XlDf9sip1o", + "hash": "FxQEbFSCyQ", "type": "object", "properties": { "password": { @@ -451,6 +477,49 @@ }, "issues": [] }, + { + "schema": "checkout", + "value": { + "billingCountry": "nl", + "billing": { + "city": "Amsterdam", + "country": "NL" + }, + "shipping": { + "country": "FR" + } + }, + "context": {}, + "issues": [ + { + "message": "Value at \"shipping.city\" is required.", + "path": [ + "shipping", + "city" + ], + "code": "required", + "params": { + "key": "city" + }, + "schema": "checkout" + }, + { + "message": "Value at \"shipping.country\" must be one of GB, NL.", + "path": [ + "shipping", + "country" + ], + "code": "enum", + "params": { + "options": [ + "GB", + "NL" + ] + }, + "schema": "checkout" + } + ] + }, { "schema": "register", "value": { @@ -756,10 +825,12 @@ "checkout": { "path": "", "fieldKeys": [ + "billing", "billingCountry", "confirmPassword", "customsDescription", "password", + "shipping", "shippingCountry" ], "constraints": { @@ -769,9 +840,38 @@ "shippingCountry": {}, "customsDescription": {}, "password": {}, - "confirmPassword": {} + "confirmPassword": {}, + "billing": {}, + "billing.city": { + "required": true, + "maxLength": 40 + }, + "billing.country": {}, + "shipping": {}, + "shipping.city": { + "required": true, + "maxLength": 40 + }, + "shipping.country": {} + }, + "options": { + "billing.country": [ + { + "value": "GB" + }, + { + "value": "NL" + } + ], + "shipping.country": [ + { + "value": "GB" + }, + { + "value": "NL" + } + ] }, - "options": {}, "kind": "object", "reads": [ "shippingCountry", diff --git a/conformance/schemas-validation.json b/conformance/schemas-validation.json index b5fbdcb..c16ed64 100644 --- a/conformance/schemas-validation.json +++ b/conformance/schemas-validation.json @@ -3716,6 +3716,45 @@ "schema_reference_depth" ] }, + { + "name": "a value nested 128 references deep passes", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "schema": "subject" + } + } + }, + "schema": "subject", + "value": [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + "issues": [] + }, + { + "name": "a value nested more than 128 references deep fails closed at the 129th", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "array", + "items": { + "schema": "subject" + } + } + }, + "schema": "subject", + "value": [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]], + "issues": [ + { + "code": "refineError", + "path": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + "params": {} + } + ], + "diagnostics": [ + "schema_reference_depth" + ] + }, { "name": "a mutation's conditions can be JSON text", "schemas": { @@ -4115,7 +4154,7 @@ "issues": [] }, { - "name": "required without properties is ignored", + "name": "required applies to an object without properties", "schemas": { "subject": { "hash": "subject-1", @@ -4127,7 +4166,47 @@ }, "schema": "subject", "value": {}, - "issues": [] + "issues": [ + { + "code": "required", + "path": [ + "a" + ], + "params": { + "key": "a" + } + } + ] + }, + { + "name": "required applies to an object with additionalProperties only", + "schemas": { + "subject": { + "hash": "subject-1", + "type": "object", + "additionalProperties": { + "type": "string" + }, + "required": [ + "en" + ] + } + }, + "schema": "subject", + "value": { + "nl": "Hallo" + }, + "issues": [ + { + "code": "required", + "path": [ + "en" + ], + "params": { + "key": "en" + } + } + ] }, { "name": "const skips the typed rules", diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java index 032cb53..5a59797 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java @@ -113,7 +113,18 @@ private static Map byPath(Object node, Resolver resolve, BiFuncti private static void walk(Map node, String prefix, Resolver resolve, BiFunction read, Map result, Set seen) { + // The objects on the way to this one, so a schema that comes back to itself stops, + // while one used by two fields, such as an address, is walked for each. if (!seen.add(node)) return; + try { + walkFields(node, prefix, resolve, read, result, seen); + } finally { + seen.remove(node); + } + } + + private static void walkFields(Map node, String prefix, Resolver resolve, + BiFunction read, Map result, Set seen) { Map properties = Json.map(node.get("properties")); if (properties == null) return; List required = node.get("required") instanceof List ? (List) node.get("required") : List.of(); @@ -140,7 +151,17 @@ static Map fieldConstraints(Object node, Resolver reso */ private static List choicesOf(Object node, Resolver resolve, boolean branch, Set seen) { Map resolved = Engine.resolveNode(node, resolve); + // The nodes on the way, so a loop stops while two branches naming one schema both count. if (resolved == null || !seen.add(resolved)) return null; + try { + return choicesFrom(node, resolved, resolve, branch, seen); + } finally { + seen.remove(resolved); + } + } + + private static List choicesFrom(Object node, Map resolved, Resolver resolve, + boolean branch, Set seen) { if (resolved.get("enum") instanceof List) { List choices = new ArrayList<>(); for (Object value : (List) resolved.get("enum")) choices.add(new SchemaOption(value, Engine.optionEntry(resolved, value))); @@ -237,22 +258,35 @@ static Map annotations(Object node, Resolver resolve) { /** What a node's rules make a field, or null for a {@code oneOf} of shapes. */ static FieldKind kind(Object node, Resolver resolve) { + return kind(node, resolve, identitySet()); + } + + /** With the nodes on the way, so a schema that comes back to itself, such as a list of such lists, stops. */ + private static FieldKind kind(Object node, Resolver resolve, Set seen) { Map resolved = Engine.resolveNode(node, resolve); - if (resolved == null) return null; + if (resolved == null || !seen.add(resolved)) return null; + try { + return kindOf(resolved, resolve, seen); + } finally { + seen.remove(resolved); + } + } + + private static FieldKind kindOf(Map resolved, Resolver resolve, Set seen) { if (resolved.get("enum") instanceof List || resolved.containsKey("const") || Engine.isConstList(resolved, resolve)) { return isBooleanChoice(valuesOf(resolved, resolve)) ? FieldKind.BOOLEAN : FieldKind.SELECT; } if (resolved.get("oneOf") instanceof List) { // A nullable field is what its other branch is. Map rules = nonNullBranch(resolved, resolve); - return rules == null ? null : kind(rules, resolve); + return rules == null ? null : kind(rules, resolve, seen); } Object type = resolved.get("type"); if ("string".equals(type)) { Object format = resolved.get("format"); return "date-time".equals(format) ? FieldKind.DATE_TIME : "semver".equals(format) ? FieldKind.VERSION : FieldKind.TEXT; } - if ("array".equals(type)) return kind(resolved.get("items"), resolve) == FieldKind.SELECT ? FieldKind.MULTISELECT : FieldKind.LIST; + if ("array".equals(type)) return kind(resolved.get("items"), resolve, seen) == FieldKind.SELECT ? FieldKind.MULTISELECT : FieldKind.LIST; if ("integer".equals(type) || "number".equals(type)) return FieldKind.NUMBER; if ("boolean".equals(type)) return FieldKind.BOOLEAN; return isObjectNode(resolved) ? FieldKind.OBJECT : null; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java index 8a2c008..c0991eb 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Engine.java @@ -40,12 +40,28 @@ static void report(Run run, Position at, String code, Map params params.put("title", at.title); } String message = Messages.choose(code, params, at.path, at, run.sources, ownMessage); - SchemaIssue issue = new SchemaIssue(message, new ArrayList<>(at.path), code, params, run.schema, null); - if (run.translate != null) { + run.issues.add(new SchemaIssue(message, new ArrayList<>(at.path), code, params, run.schema, null)); + } + + /** + * Hands each issue from an index on to the instance's message translator, the last step of + * its wording, once mutations have named their issues, so a translator sees {@code mutation}. + */ + static void translate(Run run, int from) { + if (run.translate == null) return; + for (int index = from; index < run.issues.size(); index++) { + SchemaIssue issue = run.issues.get(index); String translated = run.translate.translate(issue, run.sources.info); - if (translated != null) issue = issue.withMessage(translated); + if (translated != null) run.issues.set(index, issue.withMessage(translated)); } - run.issues.add(issue); + } + + /** Where a missing field's issue sits: at the field, worded by the messages for that field, with its title. */ + static Position missingField(List path, List mpath, List scopes, Object field, + Resolver resolve) { + List all = new ArrayList<>(scopes); + ownScopes(field, mpath.size(), resolve, all); + return new Position(path, mpath, all, titleOf(field, resolve)); } static Map params(Object... pairs) { @@ -345,16 +361,12 @@ private static Validator compileObject(Map node, Resolver resolv return (value, run, at) -> { Map object = (Map) value; - if (properties != null) { - for (String key : required) { - if (object.containsKey(key)) continue; - // A missing key's issue is at the key, worded by the messages for that field, with its title. - List mpath = append(at.mpath, key); - List scopes = new ArrayList<>(at.scopes); - ownScopes(properties.get(key), mpath.size(), resolve, scopes); - report(run, new Position(append(at.path, key), mpath, scopes, titleOf(properties.get(key), resolve)), - "required", params("key", key)); - } + // Each key `required` lists must be there, whatever `properties` holds. + for (String key : required) { + if (object.containsKey(key)) continue; + // A missing key's issue is at the key, worded by the messages for that field, with its title. + report(run, missingField(append(at.path, key), append(at.mpath, key), at.scopes, + properties == null ? null : properties.get(key), resolve), "required", params("key", key)); } for (Map.Entry entry : object.entrySet()) { @@ -393,8 +405,10 @@ private static boolean typeMatches(String type, Object value) { } /** - * References a walk follows inside one another. Only a schema that references itself - * without reading deeper into the value gets this far, so the walk fails closed there. + * The most references a validation follows inside one another, which limits how deep a value + * can nest through them: a tree whose nodes each reference the tree's schema can be 128 levels + * deep. A loop of references at one value, which lint rejects, reaches the limit too. Past it, + * the walk fails closed. */ static final int MAX_REFERENCE_DEPTH = 128; @@ -457,6 +471,8 @@ private static Validator compileRules(Map node, Resolver resolve /** A node's rules by its type: the type itself, then the keywords that type takes. */ private static Validator compileTyped(Map node, Resolver resolve) { String type = Json.string(node.get("type")); + // A type it does not know, such as `null` or any other name, fails every value. + boolean typed = node.containsKey("type"); boolean known = type != null && List.of("string", "integer", "number", "boolean", "array", "object").contains(type); // With a type, only its own keywords can apply, so only they are compiled. Validator string = type == null || type.equals("string") ? compileString(node, resolve) : null; @@ -465,8 +481,8 @@ private static Validator compileTyped(Map node, Resolver resolve Validator object = type == null || type.equals("object") ? compileObject(node, resolve) : null; return (value, run, at) -> { - if (known && !typeMatches(type, value)) { - report(run, at, "type", params("type", type, "received", Json.kindOf(value))); + if (typed && (!known || !typeMatches(type, value))) { + report(run, at, "type", params("type", node.get("type"), "received", Json.kindOf(value))); return; } if (value instanceof String) { if (string != null) string.validate(value, run, at); } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java index 0a07fc9..eec0967 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/HandleOptions.java @@ -9,7 +9,8 @@ /** * What a form brings to a schema's handle: its own messages by field, * refinements, and option sources. Build one once and reuse it, since - * {@link Schemas#get(String, HandleOptions)} keeps a handle per options object. + * {@link Schemas#get(String, HandleOptions)} keeps a handle per options object, + * compared by identity, for as long as the options object lives. */ public final class HandleOptions { private final Map messages = new LinkedHashMap<>(); @@ -55,6 +56,27 @@ public HandleOptions optionSource(OptionSource... sources) { return this; } + /** + * The handles made from this object, by the instance that made them and the schema's key. The map + * lives with this object, so options that are no longer used take their handles with them. + */ + private final Map> handles = + Collections.synchronizedMap(new java.util.WeakHashMap<>()); + + SchemaHandle handle(SchemaHandle.Context context, String key, boolean keep) { + synchronized (handles) { + Map byKey = handles.get(context); + SchemaHandle handle = byKey == null ? null : byKey.get(key); + if (handle != null) return handle; + handle = new SchemaHandle(context, key, this); + if (keep) { + if (byKey == null) handles.put(context, byKey = new java.util.HashMap<>()); + byKey.put(key, handle); + } + return handle; + } + } + Map getMessages() { return messages; } List getRefinements() { return refinements; } List getOptionSources() { return optionSources; } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java index 0b1297b..5b00c82 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Patterns.java @@ -27,6 +27,12 @@ private Patterns() {} private static final Object FAILED = new Object(); private static final Map CACHE = new ConcurrentHashMap<>(); + /** The most patterns kept, compiled or failed, so patterns a datafile never repeats cannot grow it. */ + static final int MAX_CACHED = 4096; + + static int cached() { + return CACHE.size(); + } /** The pattern compiled, or null when Java cannot compile it. */ static Pattern compile(String source) { @@ -37,7 +43,10 @@ static Pattern compile(String source) { } catch (IllegalArgumentException failed) { cached = FAILED; } - if (CACHE.size() < 4096) CACHE.put(source, cached); + // Failures too, and never more than the bound, which a check and a put apart could pass. + synchronized (CACHE) { + if (CACHE.size() < MAX_CACHED) CACHE.put(source, cached); + } } return cached == FAILED ? null : (Pattern) cached; } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java index 945f1c7..6673ba0 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Resolver.java @@ -10,18 +10,21 @@ interface Resolver { /** A schema's node, without compiling it, for what reads a node: references, annotations and messages. */ Map node(String key); - /** Reports, once, a schema that follows references deeper than any value can need, which fails the value. */ + /** Reports, once per datafile revision, a value nested too many references deep, which fails closed. */ void referenceTooDeep(String schema); /** A node's rules with a combination of its mutations applied, the same object for the same combination. */ Map mutated(Map node, String id, java.util.function.Supplier> make); - /** Reports, once, a pattern Java cannot compile, which fails every value. */ + /** Reports, once per datafile revision, a pattern Java cannot compile, which fails every value. */ void unsupportedPattern(String pattern); - /** Reports, once per schema, mutations whose operations cannot be applied, which fail the value. */ + /** Reports, once per schema and datafile revision, mutations whose operations cannot be applied, which fail the value. */ void mutationFailed(String schema, RuntimeException error); + /** Reports, once per schema and check and datafile revision, a check or lookup that threw or completed exceptionally. */ + void checkFailed(String schema, String check, String path, Throwable error); + final class Resolved { final Map node; final Validator validate; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 131ffc8..7a50676 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -12,6 +12,7 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; @@ -97,12 +98,15 @@ private static final class Described { private static final class Memo { final Object entry; final String revision; + /** For a view, how many times the context or sticky values had changed, or null for a handle without one. */ + final Long contextVersion; final Described described; final Map made = new ConcurrentHashMap<>(); - Memo(Object entry, String revision, Described described) { + Memo(Object entry, String revision, Long contextVersion, Described described) { this.entry = entry; this.revision = revision; + this.contextVersion = contextVersion; this.described = described; } } @@ -175,7 +179,8 @@ public CompletableFuture validateAsync(Object value) { /** * Validates a value, completing when every check in code has answered. The - * rules and checks that answer at once run on the calling thread. + * rules and checks that answer at once run on the calling thread. Cancelling the + * future stops waiting for the checks, and does not reach the application's own work. */ public CompletableFuture validateAsync(Object value, Map context) { Object input = Json.plain(value); @@ -247,13 +252,16 @@ private Located locate(Object value, Run run) { private Located applyRules(Object value, Run run) { Located located = locate(value, run); if (located == null) { - context.store.reportMissing(key); + // A field the schema lacks is not a schema the datafile lacks. + if (context.store.entry(key) == null) context.store.reportMissing(key); Position position = new Position(new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), null); Engine.report(run, position, "schemaNotFound", steps.isEmpty() ? Engine.params("schema", key) : Engine.params("schema", key, "field", path)); - return null; + } else { + located.validate.validate(value, run, new Position(new ArrayList<>(), located.lookup.mpath, located.lookup.scopes, null)); } - located.validate.validate(value, run, new Position(new ArrayList<>(), located.lookup.mpath, located.lookup.scopes, null)); + // Last, once mutations have named their issues. + Engine.translate(run, 0); return located; } @@ -366,6 +374,8 @@ private CompletableFuture runChecks(Object original, Object va // Each check's issues keep their place, whatever order answers arrive in. List> slots = new ArrayList<>(); List> pending = new ArrayList<>(); + // Set once the validation is cancelled, since a check that fails then says nothing. + AtomicBoolean stopped = new AtomicBoolean(); for (Check check : checks) { List targets = new ArrayList<>(); @@ -380,12 +390,16 @@ private CompletableFuture runChecks(Object original, Object va ? ((Refinement) check.owner).run(target.value, info) : ((OptionSource) check.owner).runLookup(target.value, info); } catch (RuntimeException failed) { + broke(check, failed, stopped); reportCheck(run, located, slot, "refineError", check, target.path); continue; } if (outcome instanceof CompletionStage) { pending.add(((CompletionStage) outcome).toCompletableFuture().handle((answer, error) -> { - if (error != null) reportCheck(run, located, slot, "refineError", check, target.path); + if (error != null) { + broke(check, error, stopped); + reportCheck(run, located, slot, "refineError", check, target.path); + } else if (!passes(check.kind, answer)) reportCheck(run, located, slot, failure(check.kind), check, target.path); return null; })); @@ -404,13 +418,25 @@ private CompletableFuture runChecks(Object original, Object va if (pending.isEmpty()) return CompletableFuture.completedFuture(finish.get()); CompletableFuture result = CompletableFuture.allOf(pending.toArray(new CompletableFuture[0])) .thenApply(done -> finish.get()); - // Cancelling the validation cancels what it waits for. + // Cancelling the validation stops waiting for the checks. It does not reach the application's own work. result.whenComplete((done, error) -> { - if (result.isCancelled()) for (CompletableFuture future : pending) future.cancel(true); + if (result.isCancelled()) { + stopped.set(true); + for (CompletableFuture future : pending) future.cancel(true); + } }); return result; } + /** A check that threw or completed exceptionally says why once per datafile, unless cancelling made it. */ + private void broke(Check check, Throwable error, AtomicBoolean stopped) { + if (stopped.get()) return; + Throwable cause = error instanceof CompletionException && error.getCause() != null ? error.getCause() : error; + String owner = check.owner instanceof Refinement ? ((Refinement) check.owner).getKey() : ((OptionSource) check.owner).getKey(); + String at = check.owner instanceof Refinement ? ((Refinement) check.owner).getPath() : ((OptionSource) check.owner).getPath(); + context.store.checkFailed(key, owner, at, cause); + } + private static boolean blocked(Target target, Check check, List ruleIssues, List readIssues) { for (SchemaIssue issue : ruleIssues) if (Paths.isAtOrInside(issue.getPath(), target.path)) return true; for (List read : check.reads) { @@ -458,6 +484,7 @@ private void reportCheck(Run run, Located located, List slot, Strin synchronized (run) { int before = run.issues.size(); Engine.report(run, new Position(at, lookup.mpath, lookup.scopes, lookup.title), code, params, own); + Engine.translate(run, before); List added = run.issues.subList(before, run.issues.size()); slot.addAll(added); added.clear(); @@ -530,16 +557,22 @@ private Described describe(View view) { }); } - /** What a member derives from the node, kept until the datafile changes, since a field's can come from a referenced schema. */ + /** + * What a member derives from the node, kept until the datafile changes, since a field's can come from a + * referenced schema. A view's is kept until the context or sticky values change too, since its mutations' + * conditions read them. + */ @SuppressWarnings("unchecked") private T derive(String kind, BiFunction make, T otherwise) { Store store = context.store; Object entry = store.entry(key); if (entry == null) return otherwise; String revision = store.api.getRevision(); + Long contextVersion = view == null ? null : store.contextVersion(); Memo current = memo; - if (current == null || current.entry != entry || !java.util.Objects.equals(current.revision, revision)) { - current = new Memo(entry, revision, describe(view)); + if (current == null || current.entry != entry || !java.util.Objects.equals(current.revision, revision) + || !java.util.Objects.equals(current.contextVersion, contextVersion)) { + current = new Memo(entry, revision, contextVersion, describe(view)); memo = current; } Described described = current.described; diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java index 29bcd30..e19a294 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Schemas.java @@ -42,20 +42,28 @@ public static Schemas create(Featurevisor f, SchemasOptions options) { return new Schemas(f, options); } - /** A schema's handle, the same one for the same key. */ + /** A schema's handle, the same one for the same key. A key the datafile lacks keeps no handle. */ public SchemaHandle get(String key) { SchemaHandle handle = handles.get(key); if (handle == null) { handle = new SchemaHandle(context, key, null); - SchemaHandle existing = handles.putIfAbsent(key, handle); - if (existing != null) handle = existing; + // Only for a key the datafile has, so asking for keys it lacks keeps nothing. + if (store.entry(key) != null) { + SchemaHandle existing = handles.putIfAbsent(key, handle); + if (existing != null) handle = existing; + } } return handle; } - /** A schema's handle with a form's messages, refinements and option sources. */ + /** + * A schema's handle with a form's messages, refinements and option sources, the same one for the + * same options object, compared by identity. The handles are kept with the options object, so they + * go when it does. + */ public SchemaHandle get(String key, HandleOptions options) { - return options == null ? get(key) : new SchemaHandle(context, key, options); + if (options == null) return get(key); + return options.handle(context, key, store.entry(key) != null); } public ValidationResult validate(String key, Object value) { diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java index db2067e..799b977 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Store.java @@ -46,10 +46,14 @@ static final class Identity { private final Generations>> mutated = new Generations<>(); private final Generations nodes = new Generations<>(); - private final Set reported = ConcurrentHashMap.newKeySet(); - private final Set reportedPatterns = ConcurrentHashMap.newKeySet(); - private final Set reportedDepths = ConcurrentHashMap.newKeySet(); - private final Set reportedMutations = ConcurrentHashMap.newKeySet(); + /** What was reported for the datafile of {@code reportedRevision}, dropped when the revision changes. */ + private final Set reported = new java.util.HashSet<>(); + private String reportedRevision; + private boolean reportedAny; + /** How many times the SDK instance's context or sticky values have changed, counted from the first view. */ + private final java.util.concurrent.atomic.AtomicLong contextChanges = new java.util.concurrent.atomic.AtomicLong(); + private final List contextListeners = new ArrayList<>(); + private boolean watching; /** * A cache keyed by the datafile's own nodes, in two generations. A datafile change starts a new @@ -131,6 +135,10 @@ void close() { private void close(boolean listening) { if (listening) stopListening.unsubscribe(); + synchronized (contextListeners) { + for (FeaturevisorUnsubscribe stop : contextListeners) stop.unsubscribe(); + contextListeners.clear(); + } removeModule.run(); if (named) NAMED.remove(f); } @@ -214,10 +222,42 @@ public Map mutated(Map node, String id, Supplier return rules; } + /** + * A number that changes when the SDK instance's context or sticky values do, which a view's + * conditions read. It listens from its first call on, so an instance without a view never + * makes the SDK work out what changed. + */ + long contextVersion() { + synchronized (contextListeners) { + if (!watching) { + watching = true; + for (FeaturevisorEventName event : new FeaturevisorEventName[] { + FeaturevisorEventName.CONTEXT_SET, FeaturevisorEventName.STICKY_FEATURES_SET, + FeaturevisorEventName.STICKY_VARIABLES_SET }) { + contextListeners.add(f.on(event, details -> contextChanges.incrementAndGet())); + } + } + } + return contextChanges.get(); + } + + /** Reports a diagnostic once per id and datafile revision. */ + private void once(String id, FeaturevisorDiagnostic diagnostic) { + synchronized (reported) { + String revision = api.getRevision(); + if (!reportedAny || !java.util.Objects.equals(revision, reportedRevision)) { + reportedAny = true; + reportedRevision = revision; + reported.clear(); + } + if (!reported.add(id)) return; + } + api.reportDiagnostic(diagnostic); + } + @Override public void unsupportedPattern(String pattern) { - if (!reportedPatterns.add(pattern)) return; - api.reportDiagnostic(new FeaturevisorDiagnostic() + once("pattern\0" + pattern, new FeaturevisorDiagnostic() .level(FeaturevisorLogLevel.ERROR) .code("schema_pattern_unsupported") .message("Pattern " + Json.stringify(pattern) + " does not compile in Java, so it fails every value.") @@ -226,8 +266,7 @@ public void unsupportedPattern(String pattern) { @Override public void mutationFailed(String schema, RuntimeException error) { - if (!reportedMutations.add(schema)) return; - api.reportDiagnostic(new FeaturevisorDiagnostic() + once("mutation\0" + schema, new FeaturevisorDiagnostic() .level(FeaturevisorLogLevel.ERROR) .code("schema_mutation_error") .message("A mutation of schema " + Json.stringify(schema) + " cannot be applied, so the rules it changes" @@ -238,20 +277,32 @@ public void mutationFailed(String schema, RuntimeException error) { @Override public void referenceTooDeep(String schema) { - if (!reportedDepths.add(schema)) return; - api.reportDiagnostic(new FeaturevisorDiagnostic() + once("depth\0" + schema, new FeaturevisorDiagnostic() .level(FeaturevisorLogLevel.ERROR) .code("schema_reference_depth") - .message("Schema " + Json.stringify(schema) + " follows references more than " - + Engine.MAX_REFERENCE_DEPTH + " deep, so it fails the value. A schema that references itself" - + " must read deeper into the value each time.") + .message("Schema " + Json.stringify(schema) + " fails the value closed, since the value is nested more than " + + Engine.MAX_REFERENCE_DEPTH + " references deep.") .details(Map.of("schemaKey", schema))); } - /** Reports {@code schema_not_found} once per key. */ + @Override + public void checkFailed(String schema, String check, String path, Throwable error) { + Map details = new java.util.LinkedHashMap<>(); + details.put("schemaKey", schema); + details.put("check", check); + details.put("path", path == null ? "" : path); + once("check\0" + schema + "\0" + check, new FeaturevisorDiagnostic() + .level(FeaturevisorLogLevel.ERROR) + .code("schema_check_error") + .message("Check " + Json.stringify(check) + " of schema " + Json.stringify(schema) + + " threw or rejected, so the value it checks fails closed.") + .details(details) + .originalError(error)); + } + + /** Reports {@code schema_not_found} once per key and datafile revision. */ void reportMissing(String key) { - if (!reported.add(key)) return; - api.reportDiagnostic(new FeaturevisorDiagnostic() + once("missing\0" + key, new FeaturevisorDiagnostic() .level(FeaturevisorLogLevel.WARN) .code("schema_not_found") .message("Schema \"" + key + "\" is not in the datafile. Check that a target delivers it.") @@ -334,10 +385,11 @@ static Location locate(Resolver resolve, Object root, List steps, Li if (step.kind == Paths.Kind.KEY) { Map properties = Json.map(current.get("properties")); + // A key `required` lists is required whatever `properties` holds. + required = current.get("required") instanceof List && ((List) current.get("required")).contains(step.key); if (properties != null && properties.containsKey(step.key)) { node = properties.get(step.key); mpath.add(step.key); - required = current.get("required") instanceof List && ((List) current.get("required")).contains(step.key); } else if (current.get("additionalProperties") instanceof Map) { node = current.get("additionalProperties"); mpath.add("*"); diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java new file mode 100644 index 0000000..ace9bd2 --- /dev/null +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java @@ -0,0 +1,179 @@ +package com.featurevisor.schemas; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.featurevisor.sdk.Featurevisor; +import com.featurevisor.sdk.FeaturevisorDiagnostic; +import com.featurevisor.sdk.FeaturevisorLogLevel; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CompletableFuture; +import org.junit.jupiter.api.Test; + +/** Behaviour added before the release: references, diagnostics, handles and views. */ +class SchemasReleaseTest { + private final List diagnostics = Collections.synchronizedList(new ArrayList<>()); + + private static String datafile(String revision, String schemas) { + return "{\"schemaVersion\":\"4\",\"revision\":\"" + revision + "\",\"segments\":{},\"features\":{},\"variables\":{},\"schemas\":" + schemas + "}"; + } + + private Featurevisor instance(String schemas) { + return Featurevisor.createFeaturevisor(new Featurevisor.FeaturevisorOptions() + .datafileString(datafile("1", schemas)) + .logLevel(FeaturevisorLogLevel.WARN) + .onDiagnostic(diagnostics::add)); + } + + private long count(String code) { + synchronized (diagnostics) { + return diagnostics.stream().filter(diagnostic -> code.equals(diagnostic.getCode())).count(); + } + } + + private FeaturevisorDiagnostic first(String code) { + synchronized (diagnostics) { + return diagnostics.stream().filter(diagnostic -> code.equals(diagnostic.getCode())).findFirst().orElse(null); + } + } + + private static List codes(ValidationResult result) { + List codes = new ArrayList<>(); + for (SchemaIssue issue : result.getIssues()) codes.add(issue.getCode()); + return codes; + } + + @Test + void choicesFromTwoBranchesNamingOneSchemaAndAListOfListsDoNotStopEarlyOrLoop() { + Schemas s = Schemas.create(instance("{" + + "\"size\":{\"hash\":\"a\",\"enum\":[\"s\",\"m\"]}," + + "\"pick\":{\"hash\":\"b\",\"oneOf\":[{\"schema\":\"size\"},{\"schema\":\"size\"}]}," + + "\"list\":{\"hash\":\"c\",\"type\":\"array\",\"items\":{\"schema\":\"list\"}}}")); + assertEquals(2, s.get("pick").getOptions().size()); + assertEquals(FieldKind.LIST, s.get("list").getKind()); + } + + @Test + void unknownTypesFailEveryValueAndAMissingFieldIsNoMissingSchema() { + Schemas s = Schemas.create(instance("{\"weird\":{\"hash\":\"a\",\"type\":\"nothing\"}," + + "\"form\":{\"hash\":\"b\",\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"string\"}}}}")); + assertEquals(List.of("type"), codes(s.validate("weird", "x"))); + assertEquals(List.of("type"), codes(s.validate("weird", 1))); + assertEquals(List.of("schemaNotFound"), codes(s.get("form").at("nope").validate("x"))); + assertEquals(0, count("schema_not_found")); + s.validate("absent", "x"); + assertEquals(1, count("schema_not_found")); + } + + @Test + void theNestingLimitMessageAndItsDedupeResetWithTheRevision() { + Featurevisor f = instance("{\"tree\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"child\":{\"schema\":\"tree\"}}}}"); + Schemas s = Schemas.create(f); + assertTrue(s.isValid("tree", nested(128))); + assertEquals(0, count("schema_reference_depth")); + assertEquals(List.of("refineError"), codes(s.validate("tree", nested(129)))); + s.validate("tree", nested(129)); + assertEquals(1, count("schema_reference_depth")); + assertEquals("Schema \"tree\" fails the value closed, since the value is nested more than 128 references deep.", + first("schema_reference_depth").getMessage()); + f.setDatafile(datafile("2", "{\"tree\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"child\":{\"schema\":\"tree\"}}}}")); + s.validate("tree", nested(129)); + assertEquals(2, count("schema_reference_depth")); + } + + private static Map nested(int children) { + Map value = new LinkedHashMap<>(); + for (int index = 0; index < children; index++) { + Map parent = new LinkedHashMap<>(); + parent.put("child", value); + value = parent; + } + return value; + } + + @Test + void aCheckThatThrowsOrRejectsFailsClosedAndSaysSoOncePerRevision() { + Featurevisor f = instance("{\"form\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"}}}}"); + Refinement throwing = Refinement.of("boom", "name", (value, info) -> { throw new IllegalStateException("down"); }); + Refinement rejecting = Refinement.async("later", "city", (value, info) -> CompletableFuture.failedFuture(new IllegalStateException("no"))); + SchemaHandle form = Schemas.create(f).get("form", new HandleOptions().refine(throwing, rejecting)); + Map value = Map.of("name", "a", "city", "b"); + assertEquals(List.of("refineError", "refineError"), codes(form.validate(value))); + form.validate(value); + assertEquals(2, count("schema_check_error")); + FeaturevisorDiagnostic diagnostic = first("schema_check_error"); + assertEquals(FeaturevisorLogLevel.ERROR, diagnostic.getLevel()); + assertEquals("Check \"boom\" of schema \"form\" threw or rejected, so the value it checks fails closed.", diagnostic.getMessage()); + assertEquals(Map.of("schemaKey", "form", "check", "boom", "path", "name"), diagnostic.getDetails()); + assertTrue(diagnostic.getOriginalError() instanceof IllegalStateException); + f.setDatafile(datafile("2", "{\"form\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"},\"city\":{\"type\":\"string\"}}}}")); + form.validate(value); + assertEquals(4, count("schema_check_error")); + } + + @Test + void aCancelledValidationReportsNoCheckError() { + Featurevisor f = instance("{\"form\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}}}}"); + CompletableFuture answer = new CompletableFuture<>(); + Refinement slow = Refinement.async("slow", "name", (value, info) -> answer); + SchemaHandle form = Schemas.create(f).get("form", new HandleOptions().refine(slow)); + CompletableFuture result = form.validateAsync(Map.of("name", "a")); + result.cancel(true); + answer.completeExceptionally(new IllegalStateException("late")); + assertEquals(0, count("schema_check_error")); + } + + @Test + void theTranslatorRunsLastAndSeesTheMutation() { + Featurevisor f = instance("{\"form\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\"}}," + + "\"mutations\":[{\"key\":\"strict\",\"conditions\":[{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}],\"operations\":[{\"op\":\"set\",\"path\":[\"properties\",\"name\",\"minLength\"],\"value\":5}]}]}}"); + List seen = new ArrayList<>(); + Schemas s = Schemas.create(f, new SchemasOptions().translator((issue, info) -> { + seen.add(issue.getCode() + ":" + issue.getMutation()); + return null; + })); + assertEquals(List.of("minLength"), codes(s.validate("form", Map.of("name", "ab"), Map.of("country", "nl")))); + assertEquals(List.of("minLength:strict"), seen); + } + + @Test + void sameOptionsGiveTheSameHandleAndMissingKeysKeepNone() { + Schemas s = Schemas.create(instance("{\"form\":{\"hash\":\"a\",\"type\":\"object\"}}")); + HandleOptions options = new HandleOptions(); + assertSame(s.get("form", options), s.get("form", options)); + assertNotSame(s.get("form", options), s.get("form", new HandleOptions())); + assertNotSame(s.get("form", options), s.get("form")); + assertNotSame(s.get("nope"), s.get("nope")); + assertNotSame(s.get("nope", options), s.get("nope", options)); + assertNull(s.get("form").at("a").getKind()); + } + + @Test + void aViewFollowsTheContext() { + Featurevisor f = instance("{\"form\":{\"hash\":\"a\",\"type\":\"object\",\"properties\":{\"tax\":{\"type\":\"string\"}}," + + "\"mutations\":[{\"key\":\"dutch\",\"conditions\":[{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}]," + + "\"operations\":[{\"op\":\"appendUnique\",\"path\":[\"required\"],\"value\":\"tax\"}]}]}}"); + SchemaHandle view = Schemas.create(f).get("form").withInput(new HashMap<>()); + assertFalse(view.at("tax").getConstraints().isRequired()); + f.setContext(Map.of("country", "nl")); + assertTrue(view.at("tax").getConstraints().isRequired()); + f.setContext(Map.of("country", "de")); + assertFalse(view.at("tax").getConstraints().isRequired()); + } + + @Test + void thePatternCacheIsBounded() { + for (int index = 0; index < Patterns.MAX_CACHED + 500; index++) Patterns.compile("^a" + index + "$"); + for (int index = 0; index < 100; index++) Patterns.compile("(" + index); + assertTrue(Patterns.cached() <= Patterns.MAX_CACHED); + } +} diff --git a/scripts/test-release.sh b/scripts/test-release.sh index 66e8f44..0798cce 100644 --- a/scripts/test-release.sh +++ b/scripts/test-release.sh @@ -20,8 +20,13 @@ if [[ -f pom.xml ]]; then mkdir -p "$directory/featurevisor-sdk/src/main/java/com/featurevisor/cli" cp featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java "$directory/featurevisor-sdk/src/main/java/com/featurevisor/cli/" fi -# Both installation examples must agree, even when the other is correct. -for occurrence in 1 2; do +# Every installation example must agree, even when the others are correct. +occurrences="$(grep -Ec "$version|from: .*$version" README.md)" +if [[ "$occurrences" -lt 3 ]]; then + echo "Expected an installation version for the SDK, schemas and provider, found $occurrences" >&2 + exit 1 +fi +for occurrence in $(seq 1 "$occurrences"); do awk -v version="$version" -v occurrence="$occurrence" ' index($0, version) && (/from: / || //) { count++ @@ -34,7 +39,7 @@ for occurrence in 1 2; do exit 1 fi done -checks=9 +checks=$((7 + occurrences)) if [[ -f pom.xml ]]; then cp README.md "$directory/" for file in pom.xml featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java; do diff --git a/scripts/verify-release.sh b/scripts/verify-release.sh index 7b8267d..fd9f37b 100644 --- a/scripts/verify-release.sh +++ b/scripts/verify-release.sh @@ -11,8 +11,25 @@ if ! grep -Fq "$version" pom.xml; then echo "Tag $tag does not match the Maven revision" >&2 exit 1 fi -if [[ "$(grep -Fc "$version" README.md)" != 2 ]]; then - echo "SDK and provider README installation versions must match $tag" >&2 +# Every of a com.featurevisor artifact in the README's installation snippets must match the tag, +# and each published artifact must have at least one. +readme_versions="$(awk ' + // { group = ""; artifact = "" } + // { group = $0; sub(/.*/, "", group); sub(/<\/groupId>.*/, "", group) } + // { artifact = $0; sub(/.*/, "", artifact); sub(/<\/artifactId>.*/, "", artifact) } + // && group == "com.featurevisor" { + found = $0; sub(/.*/, "", found); sub(/<\/version>.*/, "", found) + print artifact " " found + } +' README.md)" +for artifact in featurevisor-java featurevisor-schemas featurevisor-openfeature; do + if ! grep -q "^$artifact " <<<"$readme_versions"; then + echo "The README has no installation snippet for $artifact" >&2 + exit 1 + fi +done +if grep -qv " $version\$" <<<"$readme_versions"; then + echo "Every com.featurevisor installation version in the README must match $tag" >&2 exit 1 fi if ! grep -Fq "version = \"$version\"" featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java; then From 9793b78c06b8f05945506563182a25c049227b50 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Mon, 30 Nov 2026 21:05:20 +0100 Subject: [PATCH 19/21] refactor(schemas): a field's handle comes from field(path), not at(path) Test specs already use at for a bucket position, and schema specs may need it too once their conditions read rollouts, so at(path) on a handle read as one more meaning of the same word. The port follows the JavaScript package: field(path) pairs with fields and is what the docs call the result, a field's handle. Nothing is released yet, so the rename needs no deprecation. The README's Schemas section, the tests and the comments say field now. --- README.md | 16 +++++++-------- .../featurevisor/schemas/SchemaHandle.java | 6 +++--- .../schemas/BuiltDatafileTest.java | 12 +++++------ .../schemas/SchemasReleaseTest.java | 10 +++++----- .../com/featurevisor/schemas/SchemasTest.java | 20 +++++++++---------- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 0415764..a565bf1 100644 --- a/README.md +++ b/README.md @@ -798,7 +798,7 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------- | | `validate`, `isValid`, `parse` | As on `s`, without the key | | `validateAsync` | Validation as a `CompletableFuture`, for [checks in code](#check-in-code) | -| `at(path)` | The handle of one field, such as `at("displayName")` | +| `field(path)` | The handle of one field, such as `field("displayName")` | | `getFields()` | An object's fields' handles, in [order](#read-annotations), each with its `getName()` | | `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, by field path on an object, [below](#read-constraints-and-choices) | | `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, by field path on an object, and one choice by value | @@ -809,14 +809,14 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | `subscribe(listener)` | A call when a [new datafile](#listen-for-changes) changes the schema | | `getKey()`, `getPath()`, `getName()` | The schema's key, and the field's path and own name | -`at` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. +`field` takes a field name as form libraries write it: `address.city`, `items.0.name` or `items[0].name`, and `items[].name` for every item alike. It follows references and stops at `oneOf`. A path the schema lacks fails closed with `schemaNotFound`. ### Read constraints and choices `getConstraints()` are named after HTML attributes: ```java -FieldConstraints constraints = signUp.at("displayName").getConstraints(); +FieldConstraints constraints = signUp.field("displayName").getConstraints(); constraints.isRequired(); // true constraints.getMinLength(); // 2 constraints.getMaxLength(); // 40 @@ -834,7 +834,7 @@ constraints.toAttributes(); `getOptions()` lists a field's choices in the order of its rules, each with what its [annotations](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `option(value)` finds one, for showing a value saved earlier: ```java -SchemaHandle country = signUp.at("country"); +SchemaHandle country = signUp.field("country"); country.getOptions(); // nl, de and be, each a SchemaOption country.option("nl").getTitle(); // "Netherlands" @@ -866,8 +866,8 @@ Map values = Map.of( "country", "nl" ); -signUp.at("taxId").getConstraints().isRequired(); // false -signUp.withInput(values).at("taxId").getConstraints().isRequired(); // true +signUp.field("taxId").getConstraints().isRequired(); // false +signUp.withInput(values).field("taxId").getConstraints().isRequired(); // true ``` Every member follows the input, at every depth. `getReads()` lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes. @@ -922,7 +922,7 @@ SchemaHandle signUp = s.get("signUp", new HandleOptions() .lookup((city, info) -> cities.find((String) info.read("country"), (String) city)) .message("Choose a city from the list"))); -SchemaHandle city = signUp.withInput(Map.of("country", "nl")).at("city"); +SchemaHandle city = signUp.withInput(Map.of("country", "nl")).field("city"); List suggestions = city.search("am").join(); // Amsterdam and Amersfoort @@ -955,7 +955,7 @@ A rule changed in your project reaches the browser and the server at their next `subscribe` calls back when a new datafile changes the schema, through a schema it references too, and returns a `FeaturevisorUnsubscribe` that stops it: ```java -FeaturevisorUnsubscribe stop = s.get("signUp").at("country") +FeaturevisorUnsubscribe stop = s.get("signUp").field("country") .subscribe(() -> renderChoices()); ``` diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 7a50676..40210ad 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -25,7 +25,7 @@ *
{@code
  * SchemaHandle signUp = schemas.get("signUp");
  * ValidationResult result = signUp.validate(request);
- * FieldConstraints email = signUp.at("email").getConstraints();
+ * FieldConstraints email = signUp.field("email").getConstraints();
  * }
*/ public final class SchemaHandle { @@ -494,7 +494,7 @@ private void reportCheck(Run run, Located located, List slot, Strin // Fields /** The handle for a field at a path, such as {@code address.city}, {@code items[].name} or {@code labels.*}. */ - public SchemaHandle at(String path) { + public SchemaHandle field(String path) { return handle(path, () -> Paths.parse(path)); } @@ -506,7 +506,7 @@ public SchemaHandle at(String path) { SchemaHandle child(String key) { if (!key.isEmpty() && !key.equals("*") && !Paths.isIndex(key) && key.indexOf('.') < 0 && key.indexOf('[') < 0 && key.indexOf(']') < 0) { - return at(key); + return field(key); } return handle("\u0000" + key, () -> List.of(Paths.Step.key(key))); } diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java index 313837f..c2cdd7c 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java @@ -74,12 +74,12 @@ void describesFieldsAsJavaScriptDoes() throws Exception { SchemaHandle business = signUp.withInput(Map.of("accountType", "business")); Map handles = new LinkedHashMap<>(); handles.put("signUp", signUp); - handles.put("accountType", signUp.at("accountType")); - handles.put("displayName", signUp.at("displayName")); - handles.put("taxId", signUp.at("taxId")); - handles.put("businessTaxId", business.at("taxId")); - handles.put("newsletter", signUp.at("newsletter")); - handles.put("businessNewsletter", business.at("newsletter")); + handles.put("accountType", signUp.field("accountType")); + handles.put("displayName", signUp.field("displayName")); + handles.put("taxId", signUp.field("taxId")); + handles.put("businessTaxId", business.field("taxId")); + handles.put("newsletter", signUp.field("newsletter")); + handles.put("businessNewsletter", business.field("newsletter")); handles.put("profile", schemas.get("profile")); handles.put("business", business); handles.put("checkout", schemas.get("checkout")); diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java index ace9bd2..0393131 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java @@ -68,7 +68,7 @@ void unknownTypesFailEveryValueAndAMissingFieldIsNoMissingSchema() { + "\"form\":{\"hash\":\"b\",\"type\":\"object\",\"properties\":{\"a\":{\"type\":\"string\"}}}}")); assertEquals(List.of("type"), codes(s.validate("weird", "x"))); assertEquals(List.of("type"), codes(s.validate("weird", 1))); - assertEquals(List.of("schemaNotFound"), codes(s.get("form").at("nope").validate("x"))); + assertEquals(List.of("schemaNotFound"), codes(s.get("form").field("nope").validate("x"))); assertEquals(0, count("schema_not_found")); s.validate("absent", "x"); assertEquals(1, count("schema_not_found")); @@ -154,7 +154,7 @@ void sameOptionsGiveTheSameHandleAndMissingKeysKeepNone() { assertNotSame(s.get("form", options), s.get("form")); assertNotSame(s.get("nope"), s.get("nope")); assertNotSame(s.get("nope", options), s.get("nope", options)); - assertNull(s.get("form").at("a").getKind()); + assertNull(s.get("form").field("a").getKind()); } @Test @@ -163,11 +163,11 @@ void aViewFollowsTheContext() { + "\"mutations\":[{\"key\":\"dutch\",\"conditions\":[{\"attribute\":\"country\",\"operator\":\"equals\",\"value\":\"nl\"}]," + "\"operations\":[{\"op\":\"appendUnique\",\"path\":[\"required\"],\"value\":\"tax\"}]}]}}"); SchemaHandle view = Schemas.create(f).get("form").withInput(new HashMap<>()); - assertFalse(view.at("tax").getConstraints().isRequired()); + assertFalse(view.field("tax").getConstraints().isRequired()); f.setContext(Map.of("country", "nl")); - assertTrue(view.at("tax").getConstraints().isRequired()); + assertTrue(view.field("tax").getConstraints().isRequired()); f.setContext(Map.of("country", "de")); - assertFalse(view.at("tax").getConstraints().isRequired()); + assertFalse(view.field("tax").getConstraints().isRequired()); } @Test diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java index 168fe4c..4d4313e 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasTest.java @@ -157,10 +157,10 @@ void optionSourcesLookUpValuesAndSuggestChoices() { }) .lookup((value, info) -> cities.containsKey(value) ? Map.of("title", cities.get(value)) : null); SchemaHandle signUp = Schemas.create(instance()).get("signUp", new HandleOptions().optionSource(source)); - SchemaHandle city = signUp.at("city"); + SchemaHandle city = signUp.field("city"); assertTrue(city.canSearch()); - assertFalse(signUp.at("username").canSearch()); + assertFalse(signUp.field("username").canSearch()); List suggestions = city.search("ut").join(); assertEquals(1, suggestions.size()); assertEquals("utrecht", suggestions.get(0).getValue()); @@ -168,7 +168,7 @@ void optionSourcesLookUpValuesAndSuggestChoices() { assertEquals("Rotterdam", city.lookup("rotterdam").join().getTitle()); assertNull(city.lookup("amstelveen").join()); // The schema's own choices come first. - assertEquals("nl", signUp.at("country").lookup("nl").join().getValue()); + assertEquals("nl", signUp.field("country").lookup("nl").join().getValue()); Map value = Map.of("username", "ada", "password", "long enough", "city", "amstelveen"); ValidationResult result = signUp.validate(value); @@ -212,7 +212,7 @@ void aMissingSchemaOrFieldIsAnIssueReportedOnce() { schemas.validate("nothing", Map.of()); assertEquals(1, Collections.frequency(diagnostics, "schema_not_found")); assertEquals(Map.of("schema", "signUp", "field", "address.city"), - schemas.get("signUp").at("address.city").validate("x").getIssues().get(0).getParams()); + schemas.get("signUp").field("address.city").validate("x").getIssues().get(0).getParams()); assertEquals(List.of("signUp", "spaced", "braces", "dots", "broken"), schemas.getKeys()); assertTrue(schemas.has("signUp")); assertFalse(schemas.has("nothing")); @@ -224,17 +224,17 @@ void handlesReadTheCurrentDatafileAndTellWhenTheirSchemaChanges() { Schemas schemas = Schemas.create(f); SchemaHandle signUp = schemas.get("signUp"); assertSame(signUp, schemas.get("signUp")); - assertSame(signUp.at("username"), signUp.at("username")); + assertSame(signUp.field("username"), signUp.field("username")); AtomicInteger changes = new AtomicInteger(); FeaturevisorUnsubscribe stop = signUp.subscribe(changes::incrementAndGet); - assertEquals(3, signUp.at("username").getConstraints().getMinLength()); + assertEquals(3, signUp.field("username").getConstraints().getMinLength()); // A datafile that leaves the schema alone changes nothing. f.setDatafile(datafile("2", "{}")); assertEquals(0, changes.get()); f.setDatafile(datafile("3", "{\"signUp\":{\"hash\":\"s2\",\"type\":\"object\",\"properties\":{\"username\":{\"type\":\"string\",\"minLength\":5}}}}")); assertEquals(1, changes.get()); - assertEquals(5, signUp.at("username").getConstraints().getMinLength()); + assertEquals(5, signUp.field("username").getConstraints().getMinLength()); assertEquals(List.of("minLength"), codes(signUp.validate(Map.of("username", "ada")))); stop.unsubscribe(); f.setDatafile(datafile("4", "{\"signUp\":{\"hash\":\"s3\",\"type\":\"object\"}}")); @@ -336,7 +336,7 @@ void contextAModuleAddsReachesMutationsIssueEntriesAndViewsAsItReachesFlags() { // The entry about the name reads no field, so a missing VAT number does not hold it back. assertEquals(List.of("required taxId", "refine name"), codesAt(s.validate("signUp", Map.of("name", "Ada")))); assertEquals(List.of("refine name"), codesAt(s.validate("signUp", Map.of("name", "Ada", "taxId", "x")))); - assertTrue(s.get("signUp").withInput(Map.of()).at("taxId").getConstraints().isRequired()); + assertTrue(s.get("signUp").withInput(Map.of()).field("taxId").getConstraints().isRequired()); // One evaluation per validation and per view, each the schema's own. assertFalse(seen.isEmpty()); for (String evaluation : seen) assertEquals("schema signUp", evaluation); @@ -351,8 +351,8 @@ void aFieldKeyThatStartsWithADigitButIsNotAnIndexGivesTheHandleAtGives() { SchemaHandle login = Schemas.create(f).get("login"); List fields = login.getFields(); assertEquals(List.of("01", "2fa", "a.b"), List.of(fields.get(0).getName(), fields.get(1).getName(), fields.get(2).getName())); - assertSame(login.at("01"), fields.get(0)); - assertSame(login.at("2fa"), fields.get(1)); + assertSame(login.field("01"), fields.get(0)); + assertSame(login.field("2fa"), fields.get(1)); assertEquals("2fa", fields.get(1).getPath()); } From dbd9ca8223c17ce9ce0108be00d8ae17f435b950 Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Mon, 30 Nov 2026 23:02:14 +0100 Subject: [PATCH 20/21] refactor(schemas): a handle says what a field renders as with getRenderAs(), not getKind() getKind() named what a field's rules say it renders as, such as select or list, but the word told a reader nothing without the docs and already names condition kinds. The port follows the JavaScript package, which calls it renderAs. The values are unchanged, and nothing is released yet, so the rename needs no deprecation. The handle's getRenderAs() returns the RenderAs enum, where getKind() returned FieldKind. The README's Schemas section, the tests, the comments and the datafile fixture, whose member is renderAs, follow. --- README.md | 4 +-- conformance/schemas-datafile.json | 22 +++++++-------- .../com/featurevisor/schemas/Derived.java | 28 +++++++++---------- .../schemas/{FieldKind.java => RenderAs.java} | 8 +++--- .../featurevisor/schemas/SchemaHandle.java | 6 ++-- .../schemas/BuiltDatafileTest.java | 4 +-- .../schemas/SchemasReleaseTest.java | 4 +-- 7 files changed, 38 insertions(+), 38 deletions(-) rename featurevisor-schemas/src/main/java/com/featurevisor/schemas/{FieldKind.java => RenderAs.java} (63%) diff --git a/README.md b/README.md index a565bf1..e9100bd 100644 --- a/README.md +++ b/README.md @@ -802,7 +802,7 @@ A handle is stable, and reads the current datafile whenever it is used, so keep | `getFields()` | An object's fields' handles, in [order](#read-annotations), each with its `getName()` | | `getConstraints()`, `getFieldConstraints()` | HTML validation attributes, by field path on an object, [below](#read-constraints-and-choices) | | `getOptions()`, `getFieldOptions()`, `option(value)` | Its choices, by field path on an object, and one choice by value | -| `getKind()` | What its rules make the field, such as `FieldKind.SELECT` | +| `getRenderAs()` | What its rules say the field renders as, such as `RenderAs.SELECT` | | `getAnnotations()` | Its [annotations](#read-annotations) | | `withInput(input)` | The same handle with an [input](#follow-the-values-typed-so-far) | | `getReads()` | The fields its rules' conditions read | @@ -841,7 +841,7 @@ country.option("nl").getTitle(); // "Netherlands" country.option("fr"); // null ``` -A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `getKind()` answers the switch every generic form writes, from the field's rules alone: `TEXT`, `DATE_TIME`, `VERSION`, `NUMBER`, `BOOLEAN`, `SELECT`, `MULTISELECT`, `OBJECT` or `LIST`. Your own annotation, such as `input: select`, still wins over it. +A schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. `getRenderAs()` answers the switch every generic form writes, from the field's rules alone: `TEXT`, `DATE_TIME`, `VERSION`, `NUMBER`, `BOOLEAN`, `SELECT`, `MULTISELECT`, `OBJECT` or `LIST`. Your own annotation, such as `input: select`, still wins over it. ### Read annotations diff --git a/conformance/schemas-datafile.json b/conformance/schemas-datafile.json index e0642b2..1c78756 100644 --- a/conformance/schemas-datafile.json +++ b/conformance/schemas-datafile.json @@ -662,7 +662,7 @@ } ] }, - "kind": "object", + "renderAs": "object", "reads": [ "accountType" ], @@ -692,7 +692,7 @@ "title": "Business" } ], - "kind": "select", + "renderAs": "select", "reads": [], "annotations": { "title": "Account type", @@ -716,7 +716,7 @@ "maxLength": 40 }, "options": [], - "kind": "text", + "renderAs": "text", "reads": [], "annotations": { "title": "Display name", @@ -731,7 +731,7 @@ "fieldKeys": [], "constraints": {}, "options": [], - "kind": "text", + "renderAs": "text", "reads": [], "annotations": { "title": "VAT number" @@ -744,7 +744,7 @@ "required": true }, "options": [], - "kind": "text", + "renderAs": "text", "reads": [], "annotations": { "title": "VAT number" @@ -755,7 +755,7 @@ "fieldKeys": [], "constraints": {}, "options": [], - "kind": "boolean", + "renderAs": "boolean", "reads": [], "annotations": { "title": "Send me product news", @@ -767,7 +767,7 @@ "fieldKeys": [], "constraints": {}, "options": [], - "kind": "boolean", + "renderAs": "boolean", "reads": [], "annotations": { "title": "Send me product news", @@ -808,7 +808,7 @@ } ] }, - "kind": "object", + "renderAs": "object", "reads": [ "accountType" ], @@ -872,7 +872,7 @@ } ] }, - "kind": "object", + "renderAs": "object", "reads": [ "shippingCountry", "billingCountry" @@ -897,7 +897,7 @@ "billingCountry": {} }, "options": {}, - "kind": "object", + "renderAs": "object", "reads": [ "confirmPassword", "password", @@ -923,7 +923,7 @@ "😀": {} }, "options": {}, - "kind": "object", + "renderAs": "object", "reads": [], "annotations": {} } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java index 5a59797..23d8205 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/Derived.java @@ -9,7 +9,7 @@ import java.util.Set; import java.util.function.BiFunction; -/** What a handle derives from its node: constraints, choices, kind, field order and annotations. */ +/** What a handle derives from its node: constraints, choices, what a field renders as, field order and annotations. */ final class Derived { private Derived() {} @@ -256,39 +256,39 @@ static Map annotations(Object node, Resolver resolve) { return annotations == null ? Map.of() : Collections.unmodifiableMap(new LinkedHashMap<>(annotations)); } - /** What a node's rules make a field, or null for a {@code oneOf} of shapes. */ - static FieldKind kind(Object node, Resolver resolve) { - return kind(node, resolve, identitySet()); + /** What a node's rules say a field renders as, or null for a {@code oneOf} of shapes. */ + static RenderAs renderAs(Object node, Resolver resolve) { + return renderAs(node, resolve, identitySet()); } /** With the nodes on the way, so a schema that comes back to itself, such as a list of such lists, stops. */ - private static FieldKind kind(Object node, Resolver resolve, Set seen) { + private static RenderAs renderAs(Object node, Resolver resolve, Set seen) { Map resolved = Engine.resolveNode(node, resolve); if (resolved == null || !seen.add(resolved)) return null; try { - return kindOf(resolved, resolve, seen); + return renderAsOf(resolved, resolve, seen); } finally { seen.remove(resolved); } } - private static FieldKind kindOf(Map resolved, Resolver resolve, Set seen) { + private static RenderAs renderAsOf(Map resolved, Resolver resolve, Set seen) { if (resolved.get("enum") instanceof List || resolved.containsKey("const") || Engine.isConstList(resolved, resolve)) { - return isBooleanChoice(valuesOf(resolved, resolve)) ? FieldKind.BOOLEAN : FieldKind.SELECT; + return isBooleanChoice(valuesOf(resolved, resolve)) ? RenderAs.BOOLEAN : RenderAs.SELECT; } if (resolved.get("oneOf") instanceof List) { // A nullable field is what its other branch is. Map rules = nonNullBranch(resolved, resolve); - return rules == null ? null : kind(rules, resolve, seen); + return rules == null ? null : renderAs(rules, resolve, seen); } Object type = resolved.get("type"); if ("string".equals(type)) { Object format = resolved.get("format"); - return "date-time".equals(format) ? FieldKind.DATE_TIME : "semver".equals(format) ? FieldKind.VERSION : FieldKind.TEXT; + return "date-time".equals(format) ? RenderAs.DATE_TIME : "semver".equals(format) ? RenderAs.VERSION : RenderAs.TEXT; } - if ("array".equals(type)) return kind(resolved.get("items"), resolve, seen) == FieldKind.SELECT ? FieldKind.MULTISELECT : FieldKind.LIST; - if ("integer".equals(type) || "number".equals(type)) return FieldKind.NUMBER; - if ("boolean".equals(type)) return FieldKind.BOOLEAN; - return isObjectNode(resolved) ? FieldKind.OBJECT : null; + if ("array".equals(type)) return renderAs(resolved.get("items"), resolve, seen) == RenderAs.SELECT ? RenderAs.MULTISELECT : RenderAs.LIST; + if ("integer".equals(type) || "number".equals(type)) return RenderAs.NUMBER; + if ("boolean".equals(type)) return RenderAs.BOOLEAN; + return isObjectNode(resolved) ? RenderAs.OBJECT : null; } } diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/RenderAs.java similarity index 63% rename from featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java rename to featurevisor-schemas/src/main/java/com/featurevisor/schemas/RenderAs.java index 62b80bc..0e20332 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/FieldKind.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/RenderAs.java @@ -1,7 +1,7 @@ package com.featurevisor.schemas; -/** What a field's rules make it, for choosing an input. */ -public enum FieldKind { +/** What a field's rules say it renders as, for choosing an input. */ +public enum RenderAs { TEXT("text"), DATE_TIME("date-time"), VERSION("version"), @@ -14,9 +14,9 @@ public enum FieldKind { private final String value; - FieldKind(String value) { this.value = value; } + RenderAs(String value) { this.value = value; } - /** The kind as the JavaScript package names it, such as {@code date-time}. */ + /** The value as the JavaScript package names it, such as {@code date-time}. */ public String getValue() { return value; } @Override diff --git a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java index 40210ad..ebf844a 100644 --- a/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java +++ b/featurevisor-schemas/src/main/java/com/featurevisor/schemas/SchemaHandle.java @@ -639,9 +639,9 @@ public SchemaOption option(Object value) { return null; } - /** What the rules make the field, for choosing an input, or null for a {@code oneOf} of shapes. */ - public FieldKind getKind() { - return derive("kind", (node, required) -> Derived.kind(node, context.store), null); + /** What the rules say the field renders as, for choosing an input, or null for a {@code oneOf} of shapes. */ + public RenderAs getRenderAs() { + return derive("renderAs", (node, required) -> Derived.renderAs(node, context.store), null); } // Option sources diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java index c2cdd7c..0a81e15 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/BuiltDatafileTest.java @@ -88,10 +88,10 @@ void describesFieldsAsJavaScriptDoes() throws Exception { SchemaHandle handle = entry.getValue(); JsonNode wanted = expected.get(entry.getKey()); String name = entry.getKey(); - boolean object = handle.getKind() == FieldKind.OBJECT; + boolean object = handle.getRenderAs() == RenderAs.OBJECT; assertEquals(wanted.get("path").asText(), handle.getPath(), name); assertEquals(canonical(wanted.get("fieldKeys")), canonical(handle.getFieldKeys()), name + " fieldKeys"); - assertEquals(canonical(wanted.get("kind")), canonical(handle.getKind() == null ? null : handle.getKind().getValue()), name + " kind"); + assertEquals(canonical(wanted.get("renderAs")), canonical(handle.getRenderAs() == null ? null : handle.getRenderAs().getValue()), name + " renderAs"); assertEquals(canonical(wanted.get("reads")), canonical(handle.getReads()), name + " reads"); assertEquals(canonical(wanted.get("annotations")), canonical(handle.getAnnotations()), name + " annotations"); Object constraints; diff --git a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java index 0393131..4f1f526 100644 --- a/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java +++ b/featurevisor-schemas/src/test/java/com/featurevisor/schemas/SchemasReleaseTest.java @@ -59,7 +59,7 @@ void choicesFromTwoBranchesNamingOneSchemaAndAListOfListsDoNotStopEarlyOrLoop() + "\"pick\":{\"hash\":\"b\",\"oneOf\":[{\"schema\":\"size\"},{\"schema\":\"size\"}]}," + "\"list\":{\"hash\":\"c\",\"type\":\"array\",\"items\":{\"schema\":\"list\"}}}")); assertEquals(2, s.get("pick").getOptions().size()); - assertEquals(FieldKind.LIST, s.get("list").getKind()); + assertEquals(RenderAs.LIST, s.get("list").getRenderAs()); } @Test @@ -154,7 +154,7 @@ void sameOptionsGiveTheSameHandleAndMissingKeysKeepNone() { assertNotSame(s.get("form", options), s.get("form")); assertNotSame(s.get("nope"), s.get("nope")); assertNotSame(s.get("nope", options), s.get("nope", options)); - assertNull(s.get("form").field("a").getKind()); + assertNull(s.get("form").field("a").getRenderAs()); } @Test From 0bf906da401c220f68f9d25e0aee3e4a05b48fec Mon Sep 17 00:00:00 2001 From: Fahad Heylaal Date: Tue, 1 Dec 2026 00:16:26 +0100 Subject: [PATCH 21/21] chore(release): 5.1.0 5.1.0 ships the extension seam and featurevisor-schemas, a minor as decided. The Maven revision, the CLI version and every README installation example say 5.1.0, which verify-release.sh and test-release.sh check. --- README.md | 10 +++++----- .../src/main/java/com/featurevisor/cli/CLI.java | 2 +- pom.xml | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index e9100bd..1fa3c61 100644 --- a/README.md +++ b/README.md @@ -91,7 +91,7 @@ The SDK is published to GitHub Packages. Add the repository and the dependency t com.featurevisor featurevisor-java - 5.0.0 + 5.1.0 ``` @@ -720,7 +720,7 @@ They are a separate artifact, released with the same version as the SDK: com.featurevisor featurevisor-schemas - 5.0.0 + 5.1.0 ``` @@ -996,7 +996,7 @@ Add the provider with the same version as the Featurevisor Java SDK: com.featurevisor featurevisor-openfeature - 5.0.0 + 5.1.0 ``` @@ -1157,7 +1157,7 @@ mvn -pl featurevisor-sdk test-compile dependency:build-classpath -Dmdep.outputFi node scripts/test-runtime-commands.mjs ../featurevisor java \ -cp "featurevisor-sdk/target/classes:$(cat featurevisor-sdk/target/runtime-classpath.txt)" \ com.featurevisor.cli.CLI -bash scripts/test-release.sh 5.0.0 +bash scripts/test-release.sh 5.1.0 ``` These checks create temporary flat, environment and sets projects without changing the monorepo or downloading packages. The classpath command above uses the POSIX `:` separator. @@ -1178,7 +1178,7 @@ $ make verify-artifacts ### Releasing -The SDK, schemas, provider and parent POM share version `5.0.0`. Before tagging, run `bash scripts/verify-release.sh v5.0.0` to check the Maven revision, CLI and every README installation example. +The SDK, schemas, provider and parent POM share version `5.1.0`. Before tagging, run `bash scripts/verify-release.sh v5.1.0` to check the Maven revision, CLI and every README installation example. 1. Merge the release changes into `main`. 2. Tag the release with a `v` prefix, such as `vX.Y.Z`, and push the tag. diff --git a/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java b/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java index 95f7dbf..d9c533d 100644 --- a/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java +++ b/featurevisor-sdk/src/main/java/com/featurevisor/cli/CLI.java @@ -37,7 +37,7 @@ @Command( name = "featurevisor", mixinStandardHelpOptions = true, - version = "5.0.0", + version = "5.1.0", description = "Featurevisor Java Library CLI - Test runner, benchmark, and distribution assessment", footer = { "Node.js owns project parsing, test expansion and datafile building; Java evaluates the inputs.", diff --git a/pom.xml b/pom.xml index b8ac80b..69150ec 100644 --- a/pom.xml +++ b/pom.xml @@ -20,7 +20,7 @@ - 5.0.0 + 5.1.0 11 11 15