Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,19 @@ Before merging this dependent PR, merge networknt/light-aws-lambda#168, then net
Fetch each sibling repository’s master and verify the selected commit is its ancestor with `git merge-base --is-ancestor <merge-sha> origin/master`. Replace the corresponding values in `ci/jackson3-source-refs.json` with those full 40-character merge SHAs in a reviewed dependent change. Keep the remaining closure pins and the qualified core/policy SHAs unchanged. Run fresh source-build CI on that dependent commit and review its resolved-source artifact before merging. A squash or merge commit must be qualified even when its runtime tree matches the earlier pin.

For later sibling updates after this PR merges, use the same manifest-update PR and fresh dependent CI procedure. Never silently advance pins or infer qualification from the sibling’s own green build.

### Kafka schema registration migration

Kafka templates use `auto.register.schemas` and the corresponding
`kafka-producer.auto.register.schemas`, `kafka-consumer.auto.register.schemas`,
and `kafka-streams.auto.register.schemas` overrides in `values.yml`.
**Before regenerating or upgrading configuration**, rename existing
`kafka-*.schema.registry.auto.register.schemas` overrides. The old override names
are unused: an old `false` override alone leaves the canonical default `true`.
Generated `values.yml` repeats this warning next to the canonical settings.
Confluent ignored the old `schema.registry.auto.register.schemas` property, so
renaming an old `false` setting makes lookup-only behavior effective. Register
schemas before selecting canonical `false`; `true` allows automatic registration.
Light's own Avro serializer retains its legacy fallback for handwritten old-key
configurations, with the canonical key taking precedence. Users relying on that
fallback must also migrate their values overrides to retain a `false` setting.
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,40 @@
import org.snakeyaml.engine.v2.events.ScalarEvent;
import org.snakeyaml.engine.v2.exceptions.YamlEngineException;
import org.snakeyaml.engine.v2.nodes.Tag;
import org.snakeyaml.engine.v2.resolver.CoreScalarResolver;
import org.snakeyaml.engine.v2.resolver.JsonScalarResolver;
import tools.jackson.core.exc.JacksonIOException;
import tools.jackson.core.exc.StreamConstraintsException;
import tools.jackson.core.StreamReadConstraints;
import tools.jackson.databind.JsonNode;
import tools.jackson.dataformat.yaml.YAMLFactory;
import tools.jackson.dataformat.yaml.YAMLMapper;
import tools.jackson.dataformat.yaml.YAMLReadFeature;
import tools.jackson.dataformat.yaml.YAMLSchema;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayDeque;
import java.util.Set;
import java.util.Locale;
import java.util.regex.Pattern;

/** Configuration-only legacy boolean compatibility using public YAML event APIs. */
/** Configuration-only Core scalar and legacy boolean compatibility on Jackson 3.1. */
public final class GeneratorConfigYaml {
private static final Set<String> TRUE = Set.of("yes", "Yes", "YES", "on", "On", "ON");
private static final Set<String> FALSE = Set.of("no", "No", "NO", "off", "Off", "OFF");
static final int MAX_CONFIG_CODE_POINTS = 20_000_000;
private static final Pattern LEGACY_CANDIDATE = Pattern.compile(
"(?<![\\w-])(?:yes|Yes|YES|on|On|ON|no|No|NO|off|Off|OFF)(?![\\w-])");
private static final CoreScalarResolver CORE_SCALARS = new CoreScalarResolver(true);
private static final JsonScalarResolver JSON_SCALARS = new JsonScalarResolver();
// Conservative lexical filter: ordinary JSON scalars need no event pass.
private static final Pattern COMPATIBILITY_CANDIDATE = Pattern.compile(
"(?<![\\w-])(?:(?:yes|Yes|YES|on|On|ON|no|No|NO|off|Off|OFF|True|TRUE|False|FALSE|Null|NULL|~)(?![\\w-])"
+ "|[-+]?(?:0[0-9ox]|\\.[0-9iInN])|\\+[0-9])");
private static final Pattern NON_FINITE = Pattern.compile("[-+]?\\.(?i:inf|nan)");
private static final LoadSettings EVENTS = LoadSettings.builder()
.setCodePointLimit(MAX_CONFIG_CODE_POINTS).setUseMarks(true).build();
private static final YAMLMapper MAPPER = JacksonDefaults.configure(YAMLMapper.builder(
JacksonDefaults.configure(YAMLFactory.builder()).yamlSchema(YAMLSchema.CORE)
.enable(YAMLReadFeature.PARSE_OCTAL_NUMBERS).build())).build();
JacksonDefaults.configure(YAMLFactory.builder()).enable(YAMLReadFeature.EMPTY_STRING_AS_NULL).build())).build();
private static final StreamReadConstraints CONSTRAINTS = MAPPER.tokenStreamFactory().streamReadConstraints();

private GeneratorConfigYaml() { }
Expand All @@ -44,8 +50,9 @@ public static JsonNode readTree(String input) {
if (input.codePointCount(0, input.length()) > MAX_CONFIG_CODE_POINTS)
throw new StreamConstraintsException("Generator config exceeds " + MAX_CONFIG_CODE_POINTS + " code points");
CONSTRAINTS.validateDocumentLength(input.length());
// Most current configs use true/false and need only one YAML parse.
return MAPPER.readTree(LEGACY_CANDIDATE.matcher(input).find() ? normalizeBooleans(input) : input);
// Jackson 3.1 uses JSON scalar resolution. Preserve the config-only Core
// schema and legacy booleans through public events instead of 3.2 APIs.
return MAPPER.readTree(COMPATIBILITY_CANDIDATE.matcher(input).find() ? normalizeScalars(input) : input);
}

public static JsonNode readTree(byte[] input) {
Expand All @@ -62,9 +69,9 @@ public static JsonNode readTree(byte[] input) {
}

/** Rewrite values only; Jackson still owns keys, numeric nodes, aliases and stream limits. */
private static String normalizeBooleans(String input) {
private static String normalizeScalars(String input) {
var containers = new ArrayDeque<Container>();
var output = new StringBuilder(input.length());
StringBuilder output = null;
int previousCharacter = 0;
int previousCodePoint = 0;
try {
Expand All @@ -84,17 +91,17 @@ private static String normalizeBooleans(String input) {
String value = scalar.getValue();
if (key) CONSTRAINTS.validateNameLength(value.length());
else CONSTRAINTS.validateStringLength(value.length());
// Jackson retains numeric limits and its radix/separator length rules.
boolean legacy = TRUE.contains(value) || FALSE.contains(value);
boolean explicitBoolean = scalar.getTag().filter(Tag.BOOL.getValue()::equals).isPresent();
if (!key && legacy && (explicitBoolean || scalar.isPlain() && scalar.getTag().isEmpty())) {
String replacement = key ? null : scalarReplacement(scalar);
if (replacement != null) {
int startPoint = scalar.getStartMark().orElseThrow().getIndex();
int endPoint = scalar.getEndMark().orElseThrow().getIndex();
int start = input.offsetByCodePoints(previousCharacter, startPoint - previousCodePoint);
int end = input.offsetByCodePoints(start, endPoint - startPoint);
if (output == null) output = new StringBuilder(input.length());
output.append(input, previousCharacter, start);
scalar.getAnchor().ifPresent(anchor -> output.append('&').append(anchor.getValue()).append(' '));
output.append(TRUE.contains(value) ? "true" : "false");
if (scalar.getAnchor().isPresent())
output.append('&').append(scalar.getAnchor().orElseThrow().getValue()).append(' ');
output.append(replacement);
previousCharacter = end;
previousCodePoint = endPoint;
}
Expand All @@ -103,8 +110,7 @@ private static String normalizeBooleans(String input) {
case Alias -> completeNode(containers);
// readTree consumes one document; preserve its trailing-document policy.
case DocumentEnd -> {
output.append(input, previousCharacter, input.length());
return output.toString();
return output == null ? input : output.append(input, previousCharacter, input.length()).toString();
}
default -> { }
}
Expand All @@ -113,7 +119,39 @@ private static String normalizeBooleans(String input) {
// Keep Jackson's normal exception type and diagnostics for malformed YAML.
return input;
}
return output.append(input, previousCharacter, input.length()).toString();
return output == null ? input : output.append(input, previousCharacter, input.length()).toString();
}

/** Return a changed scalar spelling, or null when Jackson can consume it unchanged. */
private static String scalarReplacement(ScalarEvent scalar) {
String value = scalar.getValue();
// Empty nodes have context-dependent marks. Let EMPTY_STRING_AS_NULL handle them.
if (value.isEmpty()) return null;
boolean legacy = TRUE.contains(value) || FALSE.contains(value);
boolean explicitBoolean = scalar.getTag().filter(Tag.BOOL.getValue()::equals).isPresent();
if (legacy && (explicitBoolean || scalar.isPlain() && scalar.getTag().isEmpty()))
return TRUE.contains(value) ? "true" : "false";
boolean implicit = scalar.isPlain() && scalar.getTag().isEmpty();
boolean explicitFloat = scalar.getTag().filter(Tag.FLOAT.getValue()::equals).isPresent();
if ((implicit || explicitFloat) && NON_FINITE.matcher(value).matches()) {
// Jackson 3.1 can parse Java non-finite spellings through an explicit float tag.
String number = value.toLowerCase(Locale.ROOT).endsWith("nan") ? "NaN"
: value.startsWith("-") ? "-Infinity" : "Infinity";
return "!!float " + number;
}
if (!implicit) return null;

Tag core = CORE_SCALARS.resolve(value, true);
if (Tag.BOOL.equals(core)) {
String canonical = value.toLowerCase(Locale.ROOT);
return canonical.equals(value) ? null : canonical;
}
if (Tag.NULL.equals(core)) return "null".equals(value) ? null : "null";
if (core.equals(JSON_SCALARS.resolve(value, true))) return null;
// Explicit tags preserve Jackson's numeric radix parsing and stream limits.
if (Tag.INT.equals(core)) return "!!int " + value;
if (Tag.FLOAT.equals(core)) return "!!float " + value;
return null;
}

private static void completeNode(ArrayDeque<Container> containers) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package com.networknt.codegen;

import org.junit.jupiter.api.Test;
import tools.jackson.core.exc.StreamConstraintsException;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class GeneratorConfigScalarCompatibilityTest {
@Test
void coreScalarsWorkWithoutALegacyBooleanTrigger() {
String yaml = """
True: True
nulls: [~, Null, NULL, null]
integers: [+12, 010, -010, 0o10, 0x10]
floats: [.5, 1e3]
quoted: ['True', '~', '010']
tagged: !!str ~
anchored: &octal 010
alias: *octal
""";
var input = GeneratorConfigYaml.readTree(yaml);
assertTrue(input.get("True").booleanValue());
for (var value : input.get("nulls")) assertTrue(value.isNull());
for (int i = 0; i < 5; i++)
assertEquals(List.of(12, 8, -8, 8, 16).get(i), input.get("integers").get(i).intValue());
assertEquals(0.5, input.get("floats").get(0).doubleValue());
assertEquals(1000.0, input.get("floats").get(1).doubleValue());
assertEquals("True", input.get("quoted").get(0).asString());
assertEquals("~", input.get("quoted").get(1).asString());
assertEquals("010", input.get("quoted").get(2).asString());
assertEquals("~", input.get("tagged").asString());
assertEquals(8, input.get("anchored").intValue());
assertEquals("octal", input.get("alias").asString());
assertEquals(input, GeneratorConfigYaml.readTree(yaml.getBytes(StandardCharsets.UTF_16)));
assertTrue(Generator.yamlMapper.readTree("value: True").get("value").isString());
}

@Test
void emptyAndBlockScalarsKeepTheirMeaning() {
var input = GeneratorConfigYaml.readTree("empty:\nnext: True\nblock: |\n True ~ 010\n");
assertTrue(input.get("empty").isNull());
assertTrue(input.get("next").booleanValue());
assertEquals("True ~ 010\n", input.get("block").asString());
assertTrue(GeneratorConfigYaml.readTree("[~, NULL]").get(0).isNull());
}

@Test
void explicitNumericTagsStillEnforceJacksonLimits() {
assertThrows(StreamConstraintsException.class,
() -> GeneratorConfigYaml.readTree("octal: 0" + "1".repeat(1001)));
assertThrows(StreamConstraintsException.class,
() -> GeneratorConfigYaml.readTree("decimal: +" + "1".repeat(1001)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.networknt.codegen;

import org.junit.jupiter.api.Test;

import java.nio.charset.StandardCharsets;
import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

class GeneratorConfigYamlReviewRegressionTest {
@Test
void valuelessKeysAndEmptyDocumentsRetainTheirStructure() {
for (String yaml : List.of("{a, b: 1}", "? a\n? b\n", "empty:\nnext: 1\n",
"items: [one, two]\nmissing:\n", "mapping: {a, b: 1}\n")) {
var expected = Generator.jsonMapper.readTree(switch (yaml) {
case "{a, b: 1}" -> "{\"a\":null,\"b\":1}";
case "? a\n? b\n" -> "{\"a\":null,\"b\":null}";
case "empty:\nnext: 1\n" -> "{\"empty\":null,\"next\":1}";
case "items: [one, two]\nmissing:\n" -> "{\"items\":[\"one\",\"two\"],\"missing\":null}";
default -> "{\"mapping\":{\"a\":null,\"b\":1}}";
});
assertEquals(expected, GeneratorConfigYaml.readTree(yaml), yaml);
assertEquals(expected, GeneratorConfigYaml.readTree(yaml.getBytes(StandardCharsets.UTF_16)), yaml);
}
for (String yaml : List.of("---\n---\na: 1", "---\n", "---\n# empty\n...\n---\na: 1", "---\n---\nlegacy: yes")) {
var result = GeneratorConfigYaml.readTree(yaml);
assertTrue(result == null || result.isNull(), yaml + " -> " + result);
}
}

@Test
void valuelessKeysAlsoWorkWhenOtherScalarsNeedNormalization() {
assertEquals(Generator.jsonMapper.readTree("{\"a\":null,\"b\":1,\"legacy\":true}"),
GeneratorConfigYaml.readTree("{a, b: 1, legacy: yes}"));
assertEquals(Generator.jsonMapper.readTree("{\"a\":null,\"b\":null,\"legacy\":true}"),
GeneratorConfigYaml.readTree("? a\n? b\nlegacy: yes"));
assertEquals("", GeneratorConfigYaml.readTree("empty: ''\nlegacy: yes").get("empty").asString());
}

@Test
void implicitNonFiniteFloatsMatchTheCoreBaseline() {
for (String value : List.of(".inf", "-.inf", "+.inf", ".nan", ".INF", ".Inf", ".NaN", ".NAN")) {
for (String prefix : List.of("", "legacy: yes\n")) {
String yaml = prefix + "value: " + value;
double expected = value.toLowerCase(java.util.Locale.ROOT).endsWith("nan") ? Double.NaN
: value.startsWith("-") ? Double.NEGATIVE_INFINITY : Double.POSITIVE_INFINITY;
var result = GeneratorConfigYaml.readTree(yaml).get("value");
assertTrue(result.isNumber(), yaml);
assertEquals(expected, result.doubleValue(), yaml);
assertEquals(result, GeneratorConfigYaml.readTree(yaml.getBytes(StandardCharsets.UTF_16))
.get("value"), yaml);
assertEquals(value, GeneratorConfigYaml.readTree(prefix + "value: '" + value + "'")
.get("value").asString());
assertEquals(result, GeneratorConfigYaml.readTree(prefix + "value: !!float " + value).get("value"));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,8 @@ public void generate(String targetPath, Object model, JsonNode config) throws IO
// added with #471
transfer(targetPath, ("src.main.resources.config").replace(".", separator), "app-status.yml", templates.hybrid.appStatusYml.template());
// values.yml file, transfer to suppress the warning message during start startup and encourage usage.
transfer(targetPath, ("src.main.resources.config").replace(".", separator), "values.yml", templates.hybrid.values.template(config, handlerPackage, jsonPath, serviceId, enableHttp, httpPort, enableHttps, httpsPort, enableHttp2, enableRegistry, version));
transfer(targetPath, ("src.test.resources.config").replace(".", separator), "values.yml", templates.hybrid.values.template(config, handlerPackage, jsonPath, serviceId, enableHttp, "49587", enableHttps, "49588", enableHttp2, enableRegistry, version));
transfer(targetPath, ("src.main.resources.config").replace(".", separator), "values.yml", templates.hybrid.values.template(config, handlerPackage, jsonPath, serviceId, enableHttp, httpPort, enableHttps, httpsPort, enableHttp2, enableRegistry, version, false, kafkaConsumer));
transfer(targetPath, ("src.test.resources.config").replace(".", separator), "values.yml", templates.hybrid.values.template(config, handlerPackage, jsonPath, serviceId, enableHttp, "49587", enableHttps, "49588", enableHttp2, enableRegistry, version, false, kafkaConsumer));

// transfer binary files without touching them.
try (InputStream is = HybridServerGenerator.class.getResourceAsStream("/binaries/server.keystore")) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public void generate(String targetPath, Object model, JsonNode config) throws IO
// added with #471
transfer(targetPath, ("src.test.resources.config").replace(".", separator), "app-status.yml", templates.hybrid.appStatusYml.template());
// values.yml file, transfer to suppress the warning message during start startup and encourage usage.
transfer(targetPath, ("src.test.resources.config").replace(".", separator), "values.yml", templates.hybrid.values.template(config, handlerPackage, jsonPath, serviceId, enableHttp, "49587", enableHttps, "49588", enableHttp2, enableRegistry, version));
transfer(targetPath, ("src.test.resources.config").replace(".", separator), "values.yml", templates.hybrid.values.template(config, handlerPackage, jsonPath, serviceId, enableHttp, "49587", enableHttps, "49588", enableHttp2, enableRegistry, version, kafkaConsumer, kafkaStreams));

// handler
JsonNode anyModel = (JsonNode)model;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ properties:
group.id: ${kafka-consumer.group.id:group1}
# Schema registry url
schema.registry.url: ${kafka-consumer.schema.registry.url:http://localhost:8081}
# Schema registry auto register schema indicator for streams application. If true, the first request will register the schema auto automatically.
schema.registry.auto.register.schemas: ${kafka-consumer.schema.registry.auto.register.schemas:true}
# Automatically register schemas during serialization. False requires pre-registered schemas.
auto.register.schemas: ${kafka-consumer.auto.register.schemas:true}
# Schema registry client truststore location, use the following two properties only if schema registry url is https.
# schema.registry.ssl.truststore.location: ${kafka-consumer.schema.registry.ssl.truststore.location:/config/client.truststore}
# Schema registry client truststore password
Expand Down
Loading
Loading