You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@nifi.apache.org by "dan-s1 (via GitHub)" <gi...@apache.org> on 2026/05/27 20:59:30 UTC
[PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
dan-s1 opened a new pull request, #11290:
URL: https://github.com/apache/nifi/pull/11290
<!-- Licensed to the Apache Software Foundation (ASF) under one or more -->
<!-- contributor license agreements. See the NOTICE file distributed with -->
<!-- this work for additional information regarding copyright ownership. -->
<!-- The ASF licenses this file to You under the Apache License, Version 2.0 -->
<!-- (the "License"); you may not use this file except in compliance with -->
<!-- the License. You may obtain a copy of the License at -->
<!-- http://www.apache.org/licenses/LICENSE-2.0 -->
<!-- Unless required by applicable law or agreed to in writing, software -->
<!-- distributed under the License is distributed on an "AS IS" BASIS, -->
<!-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -->
<!-- See the License for the specific language governing permissions and -->
<!-- limitations under the License. -->
# Summary
[NIFI-15960](https://issues.apache.org/jira/browse/NIFI-15960)
# Tracking
Please complete the following tracking steps prior to pull request creation.
### Issue Tracking
- [Apache NiFi Jira](https://issues.apache.org/jira/browse/NIFI) issue created
### Pull Request Tracking
- Pull Request title starts with Apache NiFi Jira issue number, such as `NIFI-00000`
- Pull Request commit message starts with Apache NiFi Jira issue number, as such `NIFI-00000`
- Pull request contains [commits signed](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits) with a registered key indicating `Verified` status
### Pull Request Formatting
- Pull Request based on current revision of the `main` branch
- Pull Request refers to a feature branch with one commit containing changes
# Verification
Please indicate the verification steps performed prior to pull request creation.
### Build
- [ ] Build completed using `./mvnw clean install -P contrib-check`
- [ ] JDK 21
- [ ] JDK 25
### Licensing
- [ ] New dependencies are compatible with the [Apache License 2.0](https://apache.org/licenses/LICENSE-2.0) according to the [License Policy](https://www.apache.org/legal/resolved.html)
- [ ] New dependencies are documented in applicable `LICENSE` and `NOTICE` files
### Documentation
- [ ] Documentation formatting appears as expected in rendered files
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "dan-s1 (via GitHub)" <gi...@apache.org>.
dan-s1 commented on code in PR #11290:
URL: https://github.com/apache/nifi/pull/11290#discussion_r3344556990
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -138,7 +137,22 @@ public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) thro
@Override
public void migrateProperties(PropertyConfiguration config) {
- config.renameProperty("avro-reg-validated-field-names", VALIDATE_FIELD_NAMES.getName());
+ // NOTE: Although there are multiple names for OBSOLETE_VALIDATE_FIELD_NAMES, the code in the if statement
+ // will execute at most once as the assumption is a configuration has one of the obsolete property names but not all.
+ for (String obsoletePropertyName : OBSOLETE_VALIDATE_FIELD_NAMES) {
+ if (config.hasProperty(obsoletePropertyName) && config.isPropertySet(obsoletePropertyName)) {
+ final String validateFieldNamesRawValue = config.getRawPropertyValue(obsoletePropertyName).orElse(Boolean.FALSE.toString());
+ final boolean validateFieldNames = Boolean.parseBoolean(validateFieldNamesRawValue);
+
+ if (validateFieldNames) {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+ } else {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.NONE.getValue());
+ }
+ }
+
+ config.removeProperty(obsoletePropertyName);
Review Comment:
@pvillard31 Are you okay if this is left as is?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "dan-s1 (via GitHub)" <gi...@apache.org>.
dan-s1 commented on code in PR #11290:
URL: https://github.com/apache/nifi/pull/11290#discussion_r3336413336
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -138,7 +137,22 @@ public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) thro
@Override
public void migrateProperties(PropertyConfiguration config) {
- config.renameProperty("avro-reg-validated-field-names", VALIDATE_FIELD_NAMES.getName());
+ // NOTE: Although there are multiple names for OBSOLETE_VALIDATE_FIELD_NAMES, the code in the if statement
+ // will execute at most once as the assumption is a configuration has one of the obsolete property names but not all.
+ for (String obsoletePropertyName : OBSOLETE_VALIDATE_FIELD_NAMES) {
+ if (config.hasProperty(obsoletePropertyName) && config.isPropertySet(obsoletePropertyName)) {
+ final String validateFieldNamesRawValue = config.getRawPropertyValue(obsoletePropertyName).orElse(Boolean.FALSE.toString());
+ final boolean validateFieldNames = Boolean.parseBoolean(validateFieldNamesRawValue);
+
+ if (validateFieldNames) {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+ } else {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.NONE.getValue());
+ }
+ }
+
+ config.removeProperty(obsoletePropertyName);
Review Comment:
Javadoc on remove is
`Removes the property with the given name, if it exists. If the property does not exist, this is a no-op.`
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "dan-s1 (via GitHub)" <gi...@apache.org>.
dan-s1 commented on PR #11290:
URL: https://github.com/apache/nifi/pull/11290#issuecomment-4691943094
@pvillard31 Thank you very much for approving my other PRs. Can you please take another look at this PR? My teammates are interested in having this documentation so it is clear what parts of the Avro schema are validated. Thanks!
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "pvillard31 (via GitHub)" <gi...@apache.org>.
pvillard31 commented on code in PR #11290:
URL: https://github.com/apache/nifi/pull/11290#discussion_r3539321855
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/test/java/org/apache/nifi/schemaregistry/services/TestAvroSchemaRegistry.java:
##########
@@ -17,93 +17,186 @@
package org.apache.nifi.schemaregistry.services;
import org.apache.nifi.components.PropertyDescriptor;
-import org.apache.nifi.components.PropertyValue;
-import org.apache.nifi.components.ValidationContext;
-import org.apache.nifi.components.ValidationResult;
-import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.schema.access.SchemaNotFoundException;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.SchemaIdentifier;
+import org.apache.nifi.util.MockPropertyConfiguration;
+import org.apache.nifi.util.NoOpProcessor;
+import org.apache.nifi.util.PropertyMigrationResult;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
-import java.util.Collection;
-import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
public class TestAvroSchemaRegistry {
-
- @Test
- public void validateSchemaRegistrationFromrDynamicProperties() throws Exception {
- String schemaName = "fooSchema";
-
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
+ private static final String SCHEMA_NAME = "fooSchema";
+ private static final PropertyDescriptor SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR = new PropertyDescriptor.Builder()
+ .name(SCHEMA_NAME)
+ .required(false)
+ .addValidator(StandardValidators.NON_BLANK_VALIDATOR)
.dynamic(true)
- .build();
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"User\", "
- + "\"fields\": [ " + "{\"name\": \"name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
+ .expressionLanguageSupported(ExpressionLanguageScope.NONE)
.build();
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.onPropertyModified(fooSchema, null, fooSchemaText);
- delegate.onPropertyModified(barSchema, null, "");
+ private static final String NON_PERIOD_NAMESPACE_SEPARATOR = """
+ {"namespace": "example-avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
- SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
- RecordSchema locatedSchema = delegate.retrieveSchema(schemaIdentifier);
- assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
- assertThrows(SchemaNotFoundException.class, () -> delegate.retrieveSchema(SchemaIdentifier.builder().name("barSchema").build()));
+ private static final String ILLEGAL_CHARACTER_IN_RECORD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "$User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String ILLEGAL_CHARACTER_IN_FIELD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "@name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": "int", "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_UNION_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"], "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private TestRunner runner;
+ private AvroSchemaRegistry avroSchemaRegistry;
+
+ @BeforeEach
+ void setup() throws Exception {
+ runner = TestRunners.newTestRunner(NoOpProcessor.class);
+ avroSchemaRegistry = new AvroSchemaRegistry();
+ runner.addControllerService("avroSchemaRegistry", avroSchemaRegistry);
}
@Test
- public void validateStrictAndNonStrictSchemaRegistrationFromDynamicProperties() {
+ public void testRetrievalOfNonExistentSchema() {
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+ final SchemaIdentifier nonExistentSchemaIdentifier = SchemaIdentifier.builder().name("barSchema").build();
+
+ assertThrows(SchemaNotFoundException.class, () -> avroSchemaRegistry.retrieveSchema(nonExistentSchemaIdentifier));
+ }
+
+ @Test
+ public void validateSchemaRegistration() throws Exception {
String schemaName = "fooSchema";
- ConfigurationContext configContext = mock(ConfigurationContext.class);
- Map<PropertyDescriptor, String> properties = new HashMap<>();
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
- .dynamic(true)
- .build();
- // NOTE: name of record and name of first field are not Avro-compliant, verified below
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"$User\", "
- + "\"fields\": [ " + "{\"name\": \"@name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
- .build();
- properties.put(fooSchema, fooSchemaText);
- properties.put(barSchema, "");
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.getSupportedPropertyDescriptors().forEach(prop -> properties.put(prop, prop.getDisplayName()));
- when(configContext.getProperties()).thenReturn(properties);
-
- ValidationContext validationContext = mock(ValidationContext.class);
- when(validationContext.getProperties()).thenReturn(properties);
- PropertyValue propertyValue = mock(PropertyValue.class);
- when(validationContext.getProperty(AvroSchemaRegistry.VALIDATE_FIELD_NAMES)).thenReturn(propertyValue);
-
- // Strict parsing
- when(propertyValue.asBoolean()).thenReturn(true);
- Collection<ValidationResult> results = delegate.customValidate(validationContext);
- assertTrue(results.stream().anyMatch(result -> !result.isValid()));
-
- // Non-strict parsing
- when(propertyValue.asBoolean()).thenReturn(false);
- results = delegate.customValidate(validationContext);
- results.forEach(result -> assertTrue(result.isValid()));
+ String fooSchemaText = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, fooSchemaText);
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+
+ final SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
+ final RecordSchema locatedSchema = avroSchemaRegistry.retrieveSchema(schemaIdentifier);
+ assertTrue(locatedSchema.getSchemaText().isPresent());
+ assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidSchemas")
+ public void testWhereSchemasValidated(String schema) {
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+
+ runner.assertNotValid(avroSchemaRegistry);
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidSchemas")
+ public void testWhereSchemasNotValidated(String schema) {
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, ValidationStrategy.NONE.getValue());
+
+ runner.assertValid(avroSchemaRegistry);
+ }
+
+ @ParameterizedTest
+ @EnumSource(ValidationStrategy.class)
+ public void testDuplicateFieldsInvalidRegardlessOfValidation(ValidationStrategy validationStrategy) {
+ final String schema = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, validationStrategy.getValue());
+
+ runner.assertNotValid(avroSchemaRegistry);
+ }
+
+ @ParameterizedTest
+ @MethodSource("migrationConfigurations")
+ void testMigrateProperties(MockPropertyConfiguration configuration) {
+ final Set<String> expectedRemoved = new HashSet<>(AvroSchemaRegistry.OBSOLETE_VALIDATE_FIELD_NAMES);
+ final Set<String> expectedUpdated = Set.of(AvroSchemaRegistry.VALIDATION_STRATEGY.getName());
+
+ final AvroSchemaRegistry service = new AvroSchemaRegistry();
+ service.migrateProperties(configuration);
+
+ final PropertyMigrationResult result = configuration.toPropertyMigrationResult();
+ final Set<String> propertiesRemoved = result.getPropertiesRemoved();
+ assertEquals(expectedRemoved, propertiesRemoved);
+ assertEquals(expectedUpdated, result.getPropertiesUpdated());
Review Comment:
Should this test also assert the migrated value of Validation Strategy, so the true to VALIDATE and false to NONE mapping is verified and the test fails if that mapping ever breaks?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/test/java/org/apache/nifi/schemaregistry/services/TestAvroSchemaRegistry.java:
##########
@@ -17,93 +17,186 @@
package org.apache.nifi.schemaregistry.services;
import org.apache.nifi.components.PropertyDescriptor;
-import org.apache.nifi.components.PropertyValue;
-import org.apache.nifi.components.ValidationContext;
-import org.apache.nifi.components.ValidationResult;
-import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.schema.access.SchemaNotFoundException;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.SchemaIdentifier;
+import org.apache.nifi.util.MockPropertyConfiguration;
+import org.apache.nifi.util.NoOpProcessor;
+import org.apache.nifi.util.PropertyMigrationResult;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
-import java.util.Collection;
-import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
public class TestAvroSchemaRegistry {
-
- @Test
- public void validateSchemaRegistrationFromrDynamicProperties() throws Exception {
- String schemaName = "fooSchema";
-
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
+ private static final String SCHEMA_NAME = "fooSchema";
+ private static final PropertyDescriptor SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR = new PropertyDescriptor.Builder()
+ .name(SCHEMA_NAME)
+ .required(false)
+ .addValidator(StandardValidators.NON_BLANK_VALIDATOR)
.dynamic(true)
- .build();
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"User\", "
- + "\"fields\": [ " + "{\"name\": \"name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
+ .expressionLanguageSupported(ExpressionLanguageScope.NONE)
.build();
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.onPropertyModified(fooSchema, null, fooSchemaText);
- delegate.onPropertyModified(barSchema, null, "");
+ private static final String NON_PERIOD_NAMESPACE_SEPARATOR = """
+ {"namespace": "example-avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
- SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
- RecordSchema locatedSchema = delegate.retrieveSchema(schemaIdentifier);
- assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
- assertThrows(SchemaNotFoundException.class, () -> delegate.retrieveSchema(SchemaIdentifier.builder().name("barSchema").build()));
+ private static final String ILLEGAL_CHARACTER_IN_RECORD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "$User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String ILLEGAL_CHARACTER_IN_FIELD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "@name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": "int", "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_UNION_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"], "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private TestRunner runner;
+ private AvroSchemaRegistry avroSchemaRegistry;
+
+ @BeforeEach
+ void setup() throws Exception {
+ runner = TestRunners.newTestRunner(NoOpProcessor.class);
+ avroSchemaRegistry = new AvroSchemaRegistry();
+ runner.addControllerService("avroSchemaRegistry", avroSchemaRegistry);
}
@Test
- public void validateStrictAndNonStrictSchemaRegistrationFromDynamicProperties() {
+ public void testRetrievalOfNonExistentSchema() {
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+ final SchemaIdentifier nonExistentSchemaIdentifier = SchemaIdentifier.builder().name("barSchema").build();
+
+ assertThrows(SchemaNotFoundException.class, () -> avroSchemaRegistry.retrieveSchema(nonExistentSchemaIdentifier));
+ }
+
+ @Test
+ public void validateSchemaRegistration() throws Exception {
String schemaName = "fooSchema";
- ConfigurationContext configContext = mock(ConfigurationContext.class);
- Map<PropertyDescriptor, String> properties = new HashMap<>();
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
- .dynamic(true)
- .build();
- // NOTE: name of record and name of first field are not Avro-compliant, verified below
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"$User\", "
- + "\"fields\": [ " + "{\"name\": \"@name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
- .build();
- properties.put(fooSchema, fooSchemaText);
- properties.put(barSchema, "");
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.getSupportedPropertyDescriptors().forEach(prop -> properties.put(prop, prop.getDisplayName()));
- when(configContext.getProperties()).thenReturn(properties);
-
- ValidationContext validationContext = mock(ValidationContext.class);
- when(validationContext.getProperties()).thenReturn(properties);
- PropertyValue propertyValue = mock(PropertyValue.class);
- when(validationContext.getProperty(AvroSchemaRegistry.VALIDATE_FIELD_NAMES)).thenReturn(propertyValue);
-
- // Strict parsing
- when(propertyValue.asBoolean()).thenReturn(true);
- Collection<ValidationResult> results = delegate.customValidate(validationContext);
- assertTrue(results.stream().anyMatch(result -> !result.isValid()));
-
- // Non-strict parsing
- when(propertyValue.asBoolean()).thenReturn(false);
- results = delegate.customValidate(validationContext);
- results.forEach(result -> assertTrue(result.isValid()));
+ String fooSchemaText = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, fooSchemaText);
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+
+ final SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
+ final RecordSchema locatedSchema = avroSchemaRegistry.retrieveSchema(schemaIdentifier);
+ assertTrue(locatedSchema.getSchemaText().isPresent());
+ assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidSchemas")
+ public void testWhereSchemasValidated(String schema) {
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+
+ runner.assertNotValid(avroSchemaRegistry);
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidSchemas")
+ public void testWhereSchemasNotValidated(String schema) {
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, ValidationStrategy.NONE.getValue());
+
+ runner.assertValid(avroSchemaRegistry);
+ }
+
+ @ParameterizedTest
+ @EnumSource(ValidationStrategy.class)
+ public void testDuplicateFieldsInvalidRegardlessOfValidation(ValidationStrategy validationStrategy) {
+ final String schema = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, validationStrategy.getValue());
+
+ runner.assertNotValid(avroSchemaRegistry);
+ }
+
+ @ParameterizedTest
+ @MethodSource("migrationConfigurations")
+ void testMigrateProperties(MockPropertyConfiguration configuration) {
+ final Set<String> expectedRemoved = new HashSet<>(AvroSchemaRegistry.OBSOLETE_VALIDATE_FIELD_NAMES);
+ final Set<String> expectedUpdated = Set.of(AvroSchemaRegistry.VALIDATION_STRATEGY.getName());
+
+ final AvroSchemaRegistry service = new AvroSchemaRegistry();
+ service.migrateProperties(configuration);
+
+ final PropertyMigrationResult result = configuration.toPropertyMigrationResult();
+ final Set<String> propertiesRemoved = result.getPropertiesRemoved();
+ assertEquals(expectedRemoved, propertiesRemoved);
Review Comment:
This expects both obsolete names in the removed set, but production StandardPropertyConfiguration.removeProperty records nothing for an absent property while the mock records it unconditionally. Should the test assert only the obsolete name that was actually present, so it matches production behavior?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "pvillard31 (via GitHub)" <gi...@apache.org>.
pvillard31 merged PR #11290:
URL: https://github.com/apache/nifi/pull/11290
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "pvillard31 (via GitHub)" <gi...@apache.org>.
pvillard31 commented on code in PR #11290:
URL: https://github.com/apache/nifi/pull/11290#discussion_r3336067997
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -52,20 +51,20 @@
description = "Adds a named schema using the JSON string representation of an Avro schema",
expressionLanguageScope = ExpressionLanguageScope.NONE)
public class AvroSchemaRegistry extends AbstractControllerService implements SchemaRegistry {
+ static final List<String> OBSOLETE_VALIDATE_FIELD_NAMES = List.of("avro-reg-validated-field-names", "Validate Field Names");
private static final Set<SchemaField> schemaFields = EnumSet.of(SchemaField.SCHEMA_NAME, SchemaField.SCHEMA_TEXT, SchemaField.SCHEMA_TEXT_FORMAT);
private final ConcurrentMap<String, RecordSchema> recordSchemas = new ConcurrentHashMap<>();
- static final PropertyDescriptor VALIDATE_FIELD_NAMES = new PropertyDescriptor.Builder()
- .name("Validate Field Names")
- .description("Whether or not to validate the field names in the Avro schema based on Avro naming rules. If set to true, all field names must be valid Avro names, "
- + "which must begin with [A-Za-z_], and subsequently contain only [A-Za-z0-9_]. If set to false, no validation will be performed on the field names.")
- .allowableValues("true", "false")
- .defaultValue("true")
+ public static final PropertyDescriptor VALIDATION_STRATEGY = new PropertyDescriptor.Builder()
Review Comment:
Is there a consumer outside this module that needs `VALIDATION_STRATEGY`, or can it stay package-private like the previous `VALIDATE_FIELD_NAMES`?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -138,7 +137,22 @@ public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) thro
@Override
public void migrateProperties(PropertyConfiguration config) {
- config.renameProperty("avro-reg-validated-field-names", VALIDATE_FIELD_NAMES.getName());
+ // NOTE: Although there are multiple names for OBSOLETE_VALIDATE_FIELD_NAMES, the code in the if statement
+ // will execute at most once as the assumption is a configuration has one of the obsolete property names but not all.
+ for (String obsoletePropertyName : OBSOLETE_VALIDATE_FIELD_NAMES) {
+ if (config.hasProperty(obsoletePropertyName) && config.isPropertySet(obsoletePropertyName)) {
+ final String validateFieldNamesRawValue = config.getRawPropertyValue(obsoletePropertyName).orElse(Boolean.FALSE.toString());
+ final boolean validateFieldNames = Boolean.parseBoolean(validateFieldNamesRawValue);
+
+ if (validateFieldNames) {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+ } else {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.NONE.getValue());
+ }
+ }
+
+ config.removeProperty(obsoletePropertyName);
Review Comment:
Should `removeProperty(obsoletePropertyName)` be guarded by `hasProperty(obsoletePropertyName)` (or the loop broken after the first match), so that the migration result only reports the property that was actually present?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -138,7 +137,22 @@ public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) thro
@Override
public void migrateProperties(PropertyConfiguration config) {
- config.renameProperty("avro-reg-validated-field-names", VALIDATE_FIELD_NAMES.getName());
+ // NOTE: Although there are multiple names for OBSOLETE_VALIDATE_FIELD_NAMES, the code in the if statement
+ // will execute at most once as the assumption is a configuration has one of the obsolete property names but not all.
+ for (String obsoletePropertyName : OBSOLETE_VALIDATE_FIELD_NAMES) {
+ if (config.hasProperty(obsoletePropertyName) && config.isPropertySet(obsoletePropertyName)) {
+ final String validateFieldNamesRawValue = config.getRawPropertyValue(obsoletePropertyName).orElse(Boolean.FALSE.toString());
Review Comment:
Should the fallback in `getRawPropertyValue(...).orElse(Boolean.FALSE.toString())` be `Boolean.TRUE.toString()` instead, so that the rare empty-value case maps to `VALIDATE` (the historical default of the old `Validate Field Names` property) rather than `NONE`?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/ValidationStrategy.java:
##########
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.nifi.schemaregistry.services;
+
+import org.apache.nifi.components.DescribedValue;
+
+public enum ValidationStrategy implements DescribedValue {
+ VALIDATE("Validate Schemas", """
+ Validate incoming Avro schemas. Validation includes field name,
+ namespace and default value validation. All field names must be valid Avro names
+ that match the following regular expression [A-Za-z_][A-Za-z0-9_]* (i.e. a name that starts with a letter or an underscore, followed by zero or more alphanumeric,
+ characters or underscores), all namespaces must be one or more valid Avro names each matching the aforementioned regular expression and separated by periods
+ and any default value specified must match the field type (e.g. a field with type int must specify a number such as 9 or null)"""),
Review Comment:
Should the `VALIDATE` description drop the stray comma after `alphanumeric` and remove `or null` from the `int` default example, since `null` is not a valid default for a non-nullable `int`?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/test/java/org/apache/nifi/schemaregistry/services/TestAvroSchemaRegistry.java:
##########
@@ -17,93 +17,199 @@
package org.apache.nifi.schemaregistry.services;
import org.apache.nifi.components.PropertyDescriptor;
-import org.apache.nifi.components.PropertyValue;
-import org.apache.nifi.components.ValidationContext;
-import org.apache.nifi.components.ValidationResult;
-import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.schema.access.SchemaNotFoundException;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.SchemaIdentifier;
+import org.apache.nifi.util.MockPropertyConfiguration;
+import org.apache.nifi.util.NoOpProcessor;
+import org.apache.nifi.util.PropertyMigrationResult;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.opentest4j.AssertionFailedError;
-import java.util.Collection;
-import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
public class TestAvroSchemaRegistry {
-
- @Test
- public void validateSchemaRegistrationFromrDynamicProperties() throws Exception {
- String schemaName = "fooSchema";
-
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
+ private static final String SCHEMA_NAME = "fooSchema";
+ private static final PropertyDescriptor SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR = new PropertyDescriptor.Builder()
+ .name(SCHEMA_NAME)
+ .required(false)
+ .addValidator(StandardValidators.NON_BLANK_VALIDATOR)
.dynamic(true)
- .build();
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"User\", "
- + "\"fields\": [ " + "{\"name\": \"name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
+ .expressionLanguageSupported(ExpressionLanguageScope.NONE)
.build();
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.onPropertyModified(fooSchema, null, fooSchemaText);
- delegate.onPropertyModified(barSchema, null, "");
+ private static final String NON_PERIOD_NAMESPACE_SEPARATOR = """
+ {"namespace": "example-avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
- SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
- RecordSchema locatedSchema = delegate.retrieveSchema(schemaIdentifier);
- assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
- assertThrows(SchemaNotFoundException.class, () -> delegate.retrieveSchema(SchemaIdentifier.builder().name("barSchema").build()));
+ private static final String ILLEGAL_CHARACTER_IN_RECORD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "$User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String ILLEGAL_CHARACTER_IN_FIELD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "@name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": "int", "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_UNION_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"], "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private TestRunner runner;
+ private AvroSchemaRegistry avroSchemaRegistry;
+
+ @BeforeEach
+ void setup() throws Exception {
+ runner = TestRunners.newTestRunner(NoOpProcessor.class);
+ avroSchemaRegistry = new AvroSchemaRegistry();
+ runner.addControllerService("avroSchemaRegistry", avroSchemaRegistry);
+ }
+
+ @Test
+ public void testRetrievalOfNonExistentSchema() {
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+ final SchemaIdentifier nonExistentSchemaIdentifier = SchemaIdentifier.builder().name("barSchema").build();
+
+ assertThrows(SchemaNotFoundException.class, () -> avroSchemaRegistry.retrieveSchema(nonExistentSchemaIdentifier));
}
@Test
- public void validateStrictAndNonStrictSchemaRegistrationFromDynamicProperties() {
+ public void validateSchemaRegistration() throws Exception {
String schemaName = "fooSchema";
- ConfigurationContext configContext = mock(ConfigurationContext.class);
- Map<PropertyDescriptor, String> properties = new HashMap<>();
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
- .dynamic(true)
- .build();
- // NOTE: name of record and name of first field are not Avro-compliant, verified below
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"$User\", "
- + "\"fields\": [ " + "{\"name\": \"@name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
- .build();
- properties.put(fooSchema, fooSchemaText);
- properties.put(barSchema, "");
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.getSupportedPropertyDescriptors().forEach(prop -> properties.put(prop, prop.getDisplayName()));
- when(configContext.getProperties()).thenReturn(properties);
-
- ValidationContext validationContext = mock(ValidationContext.class);
- when(validationContext.getProperties()).thenReturn(properties);
- PropertyValue propertyValue = mock(PropertyValue.class);
- when(validationContext.getProperty(AvroSchemaRegistry.VALIDATE_FIELD_NAMES)).thenReturn(propertyValue);
-
- // Strict parsing
- when(propertyValue.asBoolean()).thenReturn(true);
- Collection<ValidationResult> results = delegate.customValidate(validationContext);
- assertTrue(results.stream().anyMatch(result -> !result.isValid()));
-
- // Non-strict parsing
- when(propertyValue.asBoolean()).thenReturn(false);
- results = delegate.customValidate(validationContext);
- results.forEach(result -> assertTrue(result.isValid()));
+ String fooSchemaText = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, fooSchemaText);
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+
+ final SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
+ final RecordSchema locatedSchema = avroSchemaRegistry.retrieveSchema(schemaIdentifier);
+ assertTrue(locatedSchema.getSchemaText().isPresent());
+ assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidSchemasForStrictValidation")
+ public void testStrictValidation(String schema, List<String> keyWordsInExceptionMessage) {
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, schema);
+ runner.setProperty(avroSchemaRegistry, AvroSchemaRegistry.VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+
+ final AssertionFailedError assertionFailedError = assertThrows(AssertionFailedError.class, () -> runner.assertValid(avroSchemaRegistry));
+ keyWordsInExceptionMessage.forEach(keyword -> assertTrue(assertionFailedError.getMessage().contains(keyword)));
Review Comment:
Can these assertions check the `customValidate` results (for example, that `runner.assertNotValid(...)` is satisfied, or that a `ValidationResult` for the failing dynamic property is reported) instead of matching literal substrings from Avro's exception messages, so an Avro version bump that rewords its errors does not break the tests?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/test/java/org/apache/nifi/schemaregistry/services/TestAvroSchemaRegistry.java:
##########
@@ -17,93 +17,199 @@
package org.apache.nifi.schemaregistry.services;
import org.apache.nifi.components.PropertyDescriptor;
-import org.apache.nifi.components.PropertyValue;
-import org.apache.nifi.components.ValidationContext;
-import org.apache.nifi.components.ValidationResult;
-import org.apache.nifi.controller.ConfigurationContext;
+import org.apache.nifi.expression.ExpressionLanguageScope;
+import org.apache.nifi.processor.util.StandardValidators;
import org.apache.nifi.schema.access.SchemaNotFoundException;
import org.apache.nifi.serialization.record.RecordSchema;
import org.apache.nifi.serialization.record.SchemaIdentifier;
+import org.apache.nifi.util.MockPropertyConfiguration;
+import org.apache.nifi.util.NoOpProcessor;
+import org.apache.nifi.util.PropertyMigrationResult;
+import org.apache.nifi.util.TestRunner;
+import org.apache.nifi.util.TestRunners;
+import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.EnumSource;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.opentest4j.AssertionFailedError;
-import java.util.Collection;
-import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
public class TestAvroSchemaRegistry {
-
- @Test
- public void validateSchemaRegistrationFromrDynamicProperties() throws Exception {
- String schemaName = "fooSchema";
-
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
+ private static final String SCHEMA_NAME = "fooSchema";
+ private static final PropertyDescriptor SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR = new PropertyDescriptor.Builder()
+ .name(SCHEMA_NAME)
+ .required(false)
+ .addValidator(StandardValidators.NON_BLANK_VALIDATOR)
.dynamic(true)
- .build();
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"User\", "
- + "\"fields\": [ " + "{\"name\": \"name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
+ .expressionLanguageSupported(ExpressionLanguageScope.NONE)
.build();
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.onPropertyModified(fooSchema, null, fooSchemaText);
- delegate.onPropertyModified(barSchema, null, "");
+ private static final String NON_PERIOD_NAMESPACE_SEPARATOR = """
+ {"namespace": "example-avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
- SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
- RecordSchema locatedSchema = delegate.retrieveSchema(schemaIdentifier);
- assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
- assertThrows(SchemaNotFoundException.class, () -> delegate.retrieveSchema(SchemaIdentifier.builder().name("barSchema").build()));
+ private static final String ILLEGAL_CHARACTER_IN_RECORD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "$User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String ILLEGAL_CHARACTER_IN_FIELD_NAME = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "@name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": "int", "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private static final String NON_MATCHING_UNION_DEFAULT_TYPE = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"], "default": "NAN"},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ private TestRunner runner;
+ private AvroSchemaRegistry avroSchemaRegistry;
+
+ @BeforeEach
+ void setup() throws Exception {
+ runner = TestRunners.newTestRunner(NoOpProcessor.class);
+ avroSchemaRegistry = new AvroSchemaRegistry();
+ runner.addControllerService("avroSchemaRegistry", avroSchemaRegistry);
+ }
+
+ @Test
+ public void testRetrievalOfNonExistentSchema() {
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+ final SchemaIdentifier nonExistentSchemaIdentifier = SchemaIdentifier.builder().name("barSchema").build();
+
+ assertThrows(SchemaNotFoundException.class, () -> avroSchemaRegistry.retrieveSchema(nonExistentSchemaIdentifier));
}
@Test
- public void validateStrictAndNonStrictSchemaRegistrationFromDynamicProperties() {
+ public void validateSchemaRegistration() throws Exception {
String schemaName = "fooSchema";
- ConfigurationContext configContext = mock(ConfigurationContext.class);
- Map<PropertyDescriptor, String> properties = new HashMap<>();
- PropertyDescriptor fooSchema = new PropertyDescriptor.Builder()
- .name(schemaName)
- .dynamic(true)
- .build();
- // NOTE: name of record and name of first field are not Avro-compliant, verified below
- String fooSchemaText = "{\"namespace\": \"example.avro\", " + "\"type\": \"record\", " + "\"name\": \"$User\", "
- + "\"fields\": [ " + "{\"name\": \"@name\", \"type\": [\"string\", \"null\"]}, "
- + "{\"name\": \"favorite_number\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"foo\", \"type\": [\"int\", \"null\"]}, "
- + "{\"name\": \"favorite_color\", \"type\": [\"string\", \"null\"]} " + "]" + "}";
- PropertyDescriptor barSchema = new PropertyDescriptor.Builder()
- .name("barSchema")
- .dynamic(false)
- .build();
- properties.put(fooSchema, fooSchemaText);
- properties.put(barSchema, "");
- AvroSchemaRegistry delegate = new AvroSchemaRegistry();
- delegate.getSupportedPropertyDescriptors().forEach(prop -> properties.put(prop, prop.getDisplayName()));
- when(configContext.getProperties()).thenReturn(properties);
-
- ValidationContext validationContext = mock(ValidationContext.class);
- when(validationContext.getProperties()).thenReturn(properties);
- PropertyValue propertyValue = mock(PropertyValue.class);
- when(validationContext.getProperty(AvroSchemaRegistry.VALIDATE_FIELD_NAMES)).thenReturn(propertyValue);
-
- // Strict parsing
- when(propertyValue.asBoolean()).thenReturn(true);
- Collection<ValidationResult> results = delegate.customValidate(validationContext);
- assertTrue(results.stream().anyMatch(result -> !result.isValid()));
-
- // Non-strict parsing
- when(propertyValue.asBoolean()).thenReturn(false);
- results = delegate.customValidate(validationContext);
- results.forEach(result -> assertTrue(result.isValid()));
+ String fooSchemaText = """
+ {"namespace": "example.avro", "type": "record", "name": "User",
+ "fields": [ {"name": "name", "type": ["string", "null"]},
+ {"name": "favorite_number", "type": ["int", "null"]},
+ {"name": "foo", "type": ["int", "null"]},
+ {"name": "favorite_color", "type": ["string", "null"]} ]}""";
+
+ runner.setProperty(avroSchemaRegistry, SUPPORTED_DYNAMIC_PROPERTY_DESCRIPTOR, fooSchemaText);
+ runner.assertValid(avroSchemaRegistry);
+ runner.enableControllerService(avroSchemaRegistry);
+
+ final SchemaIdentifier schemaIdentifier = SchemaIdentifier.builder().name(schemaName).build();
+ final RecordSchema locatedSchema = avroSchemaRegistry.retrieveSchema(schemaIdentifier);
+ assertTrue(locatedSchema.getSchemaText().isPresent());
+ assertEquals(fooSchemaText, locatedSchema.getSchemaText().get());
+ }
+
+ @ParameterizedTest
+ @MethodSource("invalidSchemasForStrictValidation")
+ public void testStrictValidation(String schema, List<String> keyWordsInExceptionMessage) {
Review Comment:
Now that the enum values are `VALIDATE` and `NONE`, should the test method names and helper sources (such as `testStrictValidation`, `testWithRelaxedValidation`, `invalidSchemasForStrictValidation`, `invalidSchemasForRelaxedValidation`, and the `Strict` / `Lenient` argument-set labels) be renamed to use the same vocabulary, so the test code reads consistently with the production enum?
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -138,7 +137,22 @@ public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) thro
@Override
public void migrateProperties(PropertyConfiguration config) {
Review Comment:
Should the parameter `config` and the loop variable `obsoletePropertyName` be declared `final` to match the project's code style rule that every variable which can be `final` must be `final`?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] NIFI-15960 Replaced current property in AvroSchemaRegistry with a new one which utilizes a validation strategy where it details what Avro validations occur when choosing strict validation of Avro schemas. [nifi]
Posted by "dan-s1 (via GitHub)" <gi...@apache.org>.
dan-s1 commented on code in PR #11290:
URL: https://github.com/apache/nifi/pull/11290#discussion_r3336413336
##########
nifi-extension-bundles/nifi-registry-bundle/nifi-registry-service/src/main/java/org/apache/nifi/schemaregistry/services/AvroSchemaRegistry.java:
##########
@@ -138,7 +137,22 @@ public RecordSchema retrieveSchema(final SchemaIdentifier schemaIdentifier) thro
@Override
public void migrateProperties(PropertyConfiguration config) {
- config.renameProperty("avro-reg-validated-field-names", VALIDATE_FIELD_NAMES.getName());
+ // NOTE: Although there are multiple names for OBSOLETE_VALIDATE_FIELD_NAMES, the code in the if statement
+ // will execute at most once as the assumption is a configuration has one of the obsolete property names but not all.
+ for (String obsoletePropertyName : OBSOLETE_VALIDATE_FIELD_NAMES) {
+ if (config.hasProperty(obsoletePropertyName) && config.isPropertySet(obsoletePropertyName)) {
+ final String validateFieldNamesRawValue = config.getRawPropertyValue(obsoletePropertyName).orElse(Boolean.FALSE.toString());
+ final boolean validateFieldNames = Boolean.parseBoolean(validateFieldNamesRawValue);
+
+ if (validateFieldNames) {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.VALIDATE.getValue());
+ } else {
+ config.setProperty(VALIDATION_STRATEGY, ValidationStrategy.NONE.getValue());
+ }
+ }
+
+ config.removeProperty(obsoletePropertyName);
Review Comment:
Javadoc on remove is
`Removes the property with the given name, if it exists. If the property does not exist, this is a no-op.`
Why would it be necessary then to be guarded by `hasProperty(obsoletePropertyName)` (or the loop broken after the first match)?
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: issues-unsubscribe@nifi.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org