diff --git a/dd-java-agent/appsec/src/main/java/com/datadog/appsec/config/AppSecConfigServiceImpl.java b/dd-java-agent/appsec/src/main/java/com/datadog/appsec/config/AppSecConfigServiceImpl.java index d76096deeca..4cdefeb85c2 100644 --- a/dd-java-agent/appsec/src/main/java/com/datadog/appsec/config/AppSecConfigServiceImpl.java +++ b/dd-java-agent/appsec/src/main/java/com/datadog/appsec/config/AppSecConfigServiceImpl.java @@ -50,7 +50,6 @@ import datadog.remoteconfig.state.ProductListener; import datadog.trace.api.Config; import datadog.trace.api.ConfigCollector; -import datadog.trace.api.ConfigOrigin; import datadog.trace.api.ProductActivation; import datadog.trace.api.UserIdCollectionMode; import datadog.trace.api.telemetry.LogCollector; @@ -589,7 +588,7 @@ private void setAppSecActivation(final AppSecFeatures.Asm asm) { } else { newState = asm.enabled; // Report AppSec activation change via telemetry when modified via remote config - ConfigCollector.get().put(APPSEC_ENABLED, asm.enabled, ConfigOrigin.REMOTE); + ConfigCollector.get().putRemote(APPSEC_ENABLED, asm.enabled); } if (AppSecSystem.isActive() != newState) { log.info("AppSec {} (runtime)", newState ? "enabled" : "disabled"); diff --git a/dd-smoke-tests/log-injection/src/main/java/datadog/smoketest/loginjection/BaseApplication.java b/dd-smoke-tests/log-injection/src/main/java/datadog/smoketest/loginjection/BaseApplication.java index a2edae29ac3..4e6b261d213 100644 --- a/dd-smoke-tests/log-injection/src/main/java/datadog/smoketest/loginjection/BaseApplication.java +++ b/dd-smoke-tests/log-injection/src/main/java/datadog/smoketest/loginjection/BaseApplication.java @@ -1,11 +1,11 @@ package datadog.smoketest.loginjection; -import static datadog.trace.api.config.TraceInstrumentationConfig.LOGS_INJECTION_ENABLED; - -import datadog.trace.api.ConfigCollector; -import datadog.trace.api.ConfigSetting; import datadog.trace.api.CorrelationIdentifier; +import datadog.trace.api.GlobalTracer; import datadog.trace.api.Trace; +import datadog.trace.api.TraceConfig; +import datadog.trace.api.Tracer; +import java.lang.reflect.Method; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; @@ -23,13 +23,13 @@ public void run() throws InterruptedException { secondTracedMethod(); - if (!waitForCondition(() -> Boolean.FALSE.equals(getLogInjectionEnabled()))) { + if (!waitForCondition(() -> !getLogInjectionEnabled())) { throw new RuntimeException("Logs injection config was never updated"); } thirdTracedMethod(); - if (!waitForCondition(() -> Boolean.TRUE.equals(getLogInjectionEnabled()))) { + if (!waitForCondition(() -> getLogInjectionEnabled())) { throw new RuntimeException("Logs injection config was never updated a second time"); } @@ -43,12 +43,14 @@ public void run() throws InterruptedException { Thread.sleep(400); } - private static Object getLogInjectionEnabled() { - ConfigSetting configSetting = ConfigCollector.get().collect().get(LOGS_INJECTION_ENABLED); - if (configSetting == null) { - return null; + private static boolean getLogInjectionEnabled() { + try { + Tracer tracer = GlobalTracer.get(); + Method captureTraceConfig = tracer.getClass().getMethod("captureTraceConfig"); + return ((TraceConfig) captureTraceConfig.invoke(tracer)).isLogsInjectionEnabled(); + } catch (ReflectiveOperationException e) { + throw new RuntimeException(e); } - return configSetting.value; } @Trace diff --git a/internal-api/src/main/java/datadog/trace/api/Config.java b/internal-api/src/main/java/datadog/trace/api/Config.java index 9903cdd92fd..aef84a8c58e 100644 --- a/internal-api/src/main/java/datadog/trace/api/Config.java +++ b/internal-api/src/main/java/datadog/trace/api/Config.java @@ -170,6 +170,7 @@ import static datadog.trace.api.ConfigDefaults.DEFAULT_WEBSOCKET_MESSAGES_SEPARATE_TRACES; import static datadog.trace.api.ConfigDefaults.DEFAULT_WEBSOCKET_TAG_SESSION_ID; import static datadog.trace.api.ConfigDefaults.DEFAULT_WRITER_BAGGAGE_INJECT; +import static datadog.trace.api.ConfigSetting.NON_DEFAULT_SEQ_ID; import static datadog.trace.api.DDTags.APM_ENABLED; import static datadog.trace.api.DDTags.HOST_TAG; import static datadog.trace.api.DDTags.INTERNAL_HOST_NAME; @@ -5300,7 +5301,8 @@ private static boolean isWindowsOS() { private static String getEnv(String name) { String value = EnvironmentVariables.get(name); if (value != null) { - ConfigCollector.get().put(name, value, ConfigOrigin.ENV); + // Report non-default sequence id for consistency + ConfigCollector.get().put(name, value, ConfigOrigin.ENV, NON_DEFAULT_SEQ_ID); } return value; } @@ -5323,7 +5325,8 @@ private static String getProp(String name) { private static String getProp(String name, String def) { String value = SystemProperties.getOrDefault(name, def); if (value != null) { - ConfigCollector.get().put(name, value, ConfigOrigin.JVM_PROP); + // Report non-default sequence id for consistency + ConfigCollector.get().put(name, value, ConfigOrigin.JVM_PROP, NON_DEFAULT_SEQ_ID); } return value; } diff --git a/internal-api/src/main/java/datadog/trace/api/DynamicConfig.java b/internal-api/src/main/java/datadog/trace/api/DynamicConfig.java index ce886edefc1..fb14e8370aa 100644 --- a/internal-api/src/main/java/datadog/trace/api/DynamicConfig.java +++ b/internal-api/src/main/java/datadog/trace/api/DynamicConfig.java @@ -294,7 +294,7 @@ static void reportConfigChange(Snapshot newSnapshot) { update.put(TRACE_SAMPLING_RULES, newSnapshot.traceSamplingRulesJson); maybePut(update, TRACE_SAMPLE_RATE, newSnapshot.traceSampleRate); - ConfigCollector.get().putAll(update, ConfigOrigin.REMOTE); + ConfigCollector.get().putRemote(update); } @SuppressWarnings("SameParameterValue") diff --git a/internal-api/src/test/groovy/datadog/trace/api/ConfigCollectorTest.groovy b/internal-api/src/test/groovy/datadog/trace/api/ConfigCollectorTest.groovy index 3927e1dbc2d..77b68ff9dd7 100644 --- a/internal-api/src/test/groovy/datadog/trace/api/ConfigCollectorTest.groovy +++ b/internal-api/src/test/groovy/datadog/trace/api/ConfigCollectorTest.groovy @@ -15,6 +15,7 @@ import datadog.trace.util.ConfigStrings import static datadog.trace.api.ConfigDefaults.DEFAULT_IAST_WEAK_HASH_ALGORITHMS import static datadog.trace.api.ConfigDefaults.DEFAULT_TELEMETRY_HEARTBEAT_INTERVAL +import static datadog.trace.api.ConfigSetting.ABSENT_SEQ_ID class ConfigCollectorTest extends DDSpecification { @@ -23,9 +24,10 @@ class ConfigCollectorTest extends DDSpecification { injectEnvConfig(ConfigStrings.toEnvVar(configKey), configValue) expect: - def setting = ConfigCollector.get().collect().get(configKey) - setting.stringValue() == configValue - setting.origin == ConfigOrigin.ENV + def envConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.ENV) + def config = envConfigByKey.get(configKey) + config.stringValue() == configValue + config.origin == ConfigOrigin.ENV where: configKey | configValue @@ -65,18 +67,31 @@ class ConfigCollectorTest extends DDSpecification { def "should collect merged data from multiple sources"() { setup: - injectEnvConfig(ConfigStrings.toEnvVar(configKey), envValue) - if (jvmValue != null) { - injectSysConfig(configKey, jvmValue) + injectEnvConfig(ConfigStrings.toEnvVar(configKey), envConfigValue) + if (jvmConfigValue != null) { + injectSysConfig(configKey, jvmConfigValue) + } + + when: + def collected = ConfigCollector.get().collect() + + then: + def envSetting = collected.get(ConfigOrigin.ENV) + def envConfig = envSetting.get(configKey) + envConfig.stringValue() == envConfigValue + envConfig.origin == ConfigOrigin.ENV + if (jvmConfigValue != null ) { + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP) + def jvmConfig = jvmSetting.get(configKey) + jvmConfig.stringValue().split(',') as Set == jvmConfigValue.split(',') as Set + jvmConfig.origin == ConfigOrigin.JVM_PROP } - expect: - def setting = ConfigCollector.get().collect().get(configKey) - setting.stringValue() == expectedValue - setting.origin == expectedOrigin + + // TODO: Add a check for which setting the collector recognizes as highest precedence where: - configKey | envValue | jvmValue | expectedValue | expectedOrigin + configKey | envConfigValue | jvmConfigValue | expectedValue | expectedOrigin // ConfigProvider.getMergedMap TracerConfig.TRACE_PEER_SERVICE_MAPPING | "service1:best_service,userService:my_service" | "service2:backup_service" | "service2:backup_service,service1:best_service,userService:my_service" | ConfigOrigin.CALCULATED // ConfigProvider.getOrderedMap @@ -89,7 +104,8 @@ class ConfigCollectorTest extends DDSpecification { def "default not-null config settings are collected"() { expect: - def setting = ConfigCollector.get().collect().get(configKey) + def defaultConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.DEFAULT) + def setting = defaultConfigByKey.get(configKey) setting.origin == ConfigOrigin.DEFAULT setting.stringValue() == defaultValue @@ -105,7 +121,8 @@ class ConfigCollectorTest extends DDSpecification { def "default null config settings are also collected"() { when: - ConfigSetting cs = ConfigCollector.get().collect().get(configKey) + def defaultConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.DEFAULT) + ConfigSetting cs = defaultConfigByKey.get(configKey) then: cs.key == configKey @@ -126,7 +143,8 @@ class ConfigCollectorTest extends DDSpecification { def "default empty maps and list config settings are collected as empty strings"() { when: - ConfigSetting cs = ConfigCollector.get().collect().get(configKey) + def defaultConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.DEFAULT) + ConfigSetting cs = defaultConfigByKey.get(configKey) then: cs.key == configKey @@ -146,17 +164,17 @@ class ConfigCollectorTest extends DDSpecification { ConfigCollector.get().collect() when: - ConfigCollector.get().put('key1', 'value1', ConfigOrigin.DEFAULT) - ConfigCollector.get().put('key2', 'value2', ConfigOrigin.ENV) - ConfigCollector.get().put('key1', 'replaced', ConfigOrigin.REMOTE) - ConfigCollector.get().put('key3', 'value3', ConfigOrigin.JVM_PROP) + ConfigCollector.get().put('key1', 'value1', ConfigOrigin.DEFAULT, ABSENT_SEQ_ID) + ConfigCollector.get().put('key2', 'value2', ConfigOrigin.ENV, ABSENT_SEQ_ID) + ConfigCollector.get().put('key1', 'value4', ConfigOrigin.REMOTE, ABSENT_SEQ_ID) + ConfigCollector.get().put('key3', 'value3', ConfigOrigin.JVM_PROP, ABSENT_SEQ_ID) then: - ConfigCollector.get().collect().values().toSet() == [ - ConfigSetting.of('key1', 'replaced', ConfigOrigin.REMOTE), - ConfigSetting.of('key2', 'value2', ConfigOrigin.ENV), - ConfigSetting.of('key3', 'value3', ConfigOrigin.JVM_PROP) - ] as Set + def collected = ConfigCollector.get().collect() + collected.get(ConfigOrigin.REMOTE).get('key1') == ConfigSetting.of('key1', 'value4', ConfigOrigin.REMOTE) + collected.get(ConfigOrigin.ENV).get('key2') == ConfigSetting.of('key2', 'value2', ConfigOrigin.ENV) + collected.get(ConfigOrigin.JVM_PROP).get('key3') == ConfigSetting.of('key3', 'value3', ConfigOrigin.JVM_PROP) + collected.get(ConfigOrigin.DEFAULT).get('key1') == ConfigSetting.of('key1', 'value1', ConfigOrigin.DEFAULT) } @@ -165,18 +183,19 @@ class ConfigCollectorTest extends DDSpecification { ConfigCollector.get().collect() when: - ConfigCollector.get().put('DD_API_KEY', 'sensitive data', ConfigOrigin.ENV) + ConfigCollector.get().put('DD_API_KEY', 'sensitive data', ConfigOrigin.ENV, ABSENT_SEQ_ID) then: - ConfigCollector.get().collect().get('DD_API_KEY').stringValue() == '' + def collected = ConfigCollector.get().collect() + collected.get(ConfigOrigin.ENV).get('DD_API_KEY').stringValue() == '' } def "collects common setting default values"() { when: - def settings = ConfigCollector.get().collect() + def defaultConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.DEFAULT) then: - def setting = settings.get(key) + def setting = defaultConfigByKey.get(key) setting.key == key setting.stringValue() == value @@ -207,10 +226,10 @@ class ConfigCollectorTest extends DDSpecification { injectEnvConfig("DD_TRACE_SAMPLE_RATE", "0.3") when: - def settings = ConfigCollector.get().collect() + def envConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.ENV) then: - def setting = settings.get(key) + def setting = envConfigByKey.get(key) setting.key == key setting.stringValue() == value @@ -230,6 +249,31 @@ class ConfigCollectorTest extends DDSpecification { "trace.sample.rate" | "0.3" } + def "config collector creates ConfigSettings with correct seqId"() { + setup: + ConfigCollector.get().collect() // clear previous state + + when: + // Simulate sources with increasing precedence and a default + ConfigCollector.get().put("test.key", "default", ConfigOrigin.DEFAULT, ConfigSetting.DEFAULT_SEQ_ID) + ConfigCollector.get().put("test.key", "env", ConfigOrigin.ENV, 2) + ConfigCollector.get().put("test.key", "jvm", ConfigOrigin.JVM_PROP, 3) + ConfigCollector.get().put("test.key", "remote", ConfigOrigin.REMOTE, 4) + + then: + def collected = ConfigCollector.get().collect() + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.key") + def envSetting = collected.get(ConfigOrigin.ENV).get("test.key") + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.key") + def remoteSetting = collected.get(ConfigOrigin.REMOTE).get("test.key") + + defaultSetting.seqId == ConfigSetting.DEFAULT_SEQ_ID + // Higher precedence = higher seqId + defaultSetting.seqId < envSetting.seqId + envSetting.seqId < jvmSetting.seqId + jvmSetting.seqId < remoteSetting.seqId + } + def "config id is null for non-StableConfigSource"() { setup: def key = "test.key" @@ -243,10 +287,32 @@ class ConfigCollectorTest extends DDSpecification { then: // Verify the config was collected but without a config ID - def setting = settings.get(key) + def setting = settings.get(ConfigOrigin.JVM_PROP).get(key) setting != null setting.configId == null setting.value == value setting.origin == ConfigOrigin.JVM_PROP } + + def "default sources cannot be overridden"() { + setup: + def key = "test.key" + def value = "test-value" + def overrideVal = "override-value" + def defaultConfigByKey + ConfigSetting cs + + when: + // Need to make 2 calls in a row because collect() will empty the map + ConfigCollector.get().putDefault(key, value) + ConfigCollector.get().putDefault(key, overrideVal) + defaultConfigByKey = ConfigCollector.get().collect().get(ConfigOrigin.DEFAULT) + cs = defaultConfigByKey.get(key) + + then: + cs.key == key + cs.stringValue() == value + cs.origin == ConfigOrigin.DEFAULT + cs.seqId == ConfigSetting.DEFAULT_SEQ_ID + } } diff --git a/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/ConfigProviderTest.groovy b/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/ConfigProviderTest.groovy index b9783ec59c1..060472be426 100644 --- a/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/ConfigProviderTest.groovy +++ b/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/ConfigProviderTest.groovy @@ -2,6 +2,9 @@ package datadog.trace.bootstrap.config.provider import datadog.trace.test.util.DDSpecification import spock.lang.Shared +import datadog.trace.api.ConfigCollector +import datadog.trace.api.ConfigOrigin +import datadog.trace.api.ConfigSetting import static datadog.trace.api.config.TracerConfig.TRACE_HTTP_SERVER_PATH_RESOURCE_NAME_MAPPING @@ -45,4 +48,529 @@ class ConfigProviderTest extends DDSpecification { "default" | null | "alias2" | "default" null | "alias1" | "alias2" | "alias1" } + + def "ConfigProvider assigns correct seqId, origin, and value for each source and default"() { + setup: + ConfigCollector.get().collect() // clear previous state + + injectEnvConfig("DD_TEST_KEY", "envValue") + injectSysConfig("test.key", "jvmValue") + // Default ConfigProvider includes ENV and JVM_PROP + def provider = ConfigProvider.createDefault() + + when: + def value = provider.getString("test.key", "defaultValue") + def collected = ConfigCollector.get().collect() + + then: + // Check the default + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.key") + defaultSetting.key == "test.key" + defaultSetting.stringValue() == "defaultValue" + defaultSetting.origin == ConfigOrigin.DEFAULT + defaultSetting.seqId == ConfigSetting.DEFAULT_SEQ_ID + + def envSetting = collected.get(ConfigOrigin.ENV).get("test.key") + envSetting.key == "test.key" + envSetting.stringValue() == "envValue" + envSetting.origin == ConfigOrigin.ENV + + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.key") + jvmSetting.key == "test.key" + jvmSetting.stringValue() == "jvmValue" + jvmSetting.origin == ConfigOrigin.JVM_PROP + + // It doesn't matter what the seqId values are, so long as they increase with source precedence + jvmSetting.seqId > envSetting.seqId + envSetting.seqId > defaultSetting.seqId + + // The value returned by ConfigProvider should be the highest precedence value + value == jvmSetting.stringValue() + } + + def "ConfigProvider reports highest seqId for chosen value and origin regardless of conversion errors for #methodType"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up: default, env (valid), jvm (invalid for the specific type) + injectEnvConfig(envKey, validValue) + injectSysConfig(configKey, invalidValue) + def provider = ConfigProvider.createDefault() + + when: + def value = methodCall(provider, configKey, defaultValue) + def collected = ConfigCollector.get().collect() + + then: + // Default + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get(configKey) + defaultSetting.key == configKey + defaultSetting.stringValue() == String.valueOf(defaultValue) + defaultSetting.origin == ConfigOrigin.DEFAULT + defaultSetting.seqId == ConfigSetting.DEFAULT_SEQ_ID + + // ENV (valid) + def envSetting = collected.get(ConfigOrigin.ENV).get(configKey) + envSetting.key == configKey + envSetting.stringValue() == validValue + envSetting.origin == ConfigOrigin.ENV + + // JVM_PROP (invalid, should still be reported) + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get(configKey) + jvmSetting.key == configKey + jvmSetting.stringValue() == invalidValue + jvmSetting.origin == ConfigOrigin.JVM_PROP + + // The chosen value (from ENV) should have been re-reported with the highest seqId + def maxSeqId = [defaultSetting.seqId, envSetting.seqId, jvmSetting.seqId].max() + def chosenSetting = [defaultSetting, envSetting, jvmSetting].find { it.seqId == maxSeqId } + chosenSetting.stringValue() == validValue + chosenSetting.origin == ConfigOrigin.ENV + + // The value returned by provider should be the valid one + value == expectedResult + + where: + // getBoolean is purposefully excluded; see getBoolean test below + methodType | configKey | envKey | validValue | invalidValue | defaultValue | expectedResult | methodCall + "getInteger" | "test.int" | "DD_TEST_INT" | "42" | "notAnInt" | 7 | 42 | { configProvider, key, defVal -> configProvider.getInteger(key, defVal) } + "getLong" | "test.long" | "DD_TEST_LONG" | "123" | "notALong" | 5L | 123L | { configProvider, key, defVal -> configProvider.getLong(key, defVal) } + "getFloat" | "test.float" | "DD_TEST_FLOAT" | "42.5" | "notAFloat" | 3.14f | 42.5f | { configProvider, key, defVal -> configProvider.getFloat(key, defVal) } + "getDouble" | "test.double" | "DD_TEST_DOUBLE"| "42.75" | "notADouble" | 2.71 | 42.75 | { configProvider, key, defVal -> configProvider.getDouble(key, defVal) } + } + + def "ConfigProvider transforms invalid values for getBoolean to false with CALCULATED origin"() { + // Booleans are a special case; we currently treat all invalid boolean configurations as false rather than falling back to a lower precedence setting. + setup: + ConfigCollector.get().collect() // clear previous state + + def envKey = "DD_TEST_BOOL" + def envValue = "true" + def configKey = "test.bool" + def propValue = "notABool" + def defaultValue = true + + injectEnvConfig(envKey, envValue) + injectSysConfig(configKey, propValue) + def provider = ConfigProvider.createDefault() + + when: + def value = provider.getBoolean(configKey, defaultValue) + def collected = ConfigCollector.get().collect() + + then: + // Default + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get(configKey) + defaultSetting.key == configKey + defaultSetting.stringValue() == String.valueOf(defaultValue) + defaultSetting.origin == ConfigOrigin.DEFAULT + defaultSetting.seqId == ConfigSetting.DEFAULT_SEQ_ID + + // ENV (valid) + def envSetting = collected.get(ConfigOrigin.ENV).get(configKey) + envSetting.key == configKey + envSetting.stringValue() == envValue + envSetting.origin == ConfigOrigin.ENV + + // JVM_PROP (invalid, should still be reported) + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get(configKey) + jvmSetting.key == configKey + jvmSetting.stringValue() == propValue + jvmSetting.origin == ConfigOrigin.JVM_PROP + + // Config was evaluated to false and reported with CALCULATED origin + def calcSetting = collected.get(ConfigOrigin.CALCULATED).get(configKey) + calcSetting.key == configKey + calcSetting.stringValue() == "false" + calcSetting.origin == ConfigOrigin.CALCULATED + + // The highest seqId should be the CALCULATED origin + def maxSeqId = [defaultSetting.seqId, envSetting.seqId, jvmSetting.seqId, calcSetting.seqId].max() + def chosenSetting = [defaultSetting, envSetting, jvmSetting, calcSetting].find { it.seqId == maxSeqId } + chosenSetting.origin == ConfigOrigin.CALCULATED + chosenSetting.stringValue() == "false" + + // The value returned by provider should be false + value == false + } + + def "ConfigProvider getEnum returns default when conversion fails"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up: only invalid enum values from all sources + injectEnvConfig("DD_TEST_ENUM2", "NOT_A_VALID_ENUM") + injectSysConfig("test.enum2", "ALSO_INVALID") + def provider = ConfigProvider.createDefault() + + when: + def value = provider.getEnum("test.enum2", ConfigOrigin, ConfigOrigin.CODE) + def collected = ConfigCollector.get().collect() + + then: + // Should have attempted to use the highest precedence value (JVM_PROP) + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.enum2") + jvmSetting.stringValue() == "ALSO_INVALID" + + // But since conversion failed, should return the default + value == ConfigOrigin.CODE + } + + def "ConfigProvider getString reports all sources and respects precedence"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up: default, env, jvm (all valid strings) + injectEnvConfig("DD_TEST_STRING", "envValue") + injectSysConfig("test.string", "jvmValue") + def provider = ConfigProvider.createDefault() + + when: + def value = provider.getString("test.string", "defaultValue") + def collected = ConfigCollector.get().collect() + + then: + // Default + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.string") + defaultSetting.key == "test.string" + defaultSetting.stringValue() == "defaultValue" + defaultSetting.origin == ConfigOrigin.DEFAULT + defaultSetting.seqId == ConfigSetting.DEFAULT_SEQ_ID + + // ENV + def envSetting = collected.get(ConfigOrigin.ENV).get("test.string") + envSetting.key == "test.string" + envSetting.stringValue() == "envValue" + envSetting.origin == ConfigOrigin.ENV + + // JVM_PROP (highest precedence) + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.string") + jvmSetting.key == "test.string" + jvmSetting.stringValue() == "jvmValue" + jvmSetting.origin == ConfigOrigin.JVM_PROP + + // JVM should have highest seqId and be the returned value + jvmSetting.seqId > envSetting.seqId + envSetting.seqId > defaultSetting.seqId + value == "jvmValue" + } + + def "ConfigProvider getStringNotEmpty reports all values even if they are empty, but returns the non-empty value"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up: env (empty/blank), jvm (valid but with whitespace) + injectEnvConfig("DD_TEST_STRING_NOT_EMPTY", " ") // blank string + injectSysConfig("test.string.not.empty", " jvmValue ") // valid but with whitespace + def provider = ConfigProvider.createDefault() + + when: + def value = provider.getStringNotEmpty("test.string.not.empty", "defaultValue") + def collected = ConfigCollector.get().collect() + + then: + // Default + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.string.not.empty") + defaultSetting.stringValue() == "defaultValue" + + // ENV (blank, should be skipped for return value but still reported) + def envSetting = collected.get(ConfigOrigin.ENV).get("test.string.not.empty") + envSetting.stringValue() == " " + envSetting.origin == ConfigOrigin.ENV + + // JVM_PROP setting - should have highest seqId + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.string.not.empty") + jvmSetting.stringValue() == " jvmValue " + jvmSetting.origin == ConfigOrigin.JVM_PROP + + def maxSeqId = [defaultSetting.seqId, envSetting.seqId, jvmSetting.seqId].max() + jvmSetting.seqId == maxSeqId + + value == " jvmValue " + } + + def "ConfigProvider getStringExcludingSource excludes specified source type"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up: env, jvm (both valid) + injectEnvConfig("DD_TEST_STRING_EXCLUDE", "envValue") + injectSysConfig("test.string.exclude", "jvmValue") + def provider = ConfigProvider.createDefault() + + when: + // Exclude JVM_PROP source, should fall back to ENV + def value = provider.getStringExcludingSource("test.string.exclude", "defaultValue", + SystemPropertiesConfigSource) + def collected = ConfigCollector.get().collect() + + then: + // Default + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.string.exclude") + defaultSetting.stringValue() == "defaultValue" + + // ENV (should be used since JVM is excluded) + def envSetting = collected.get(ConfigOrigin.ENV).get("test.string.exclude") + envSetting.stringValue() == "envValue" + envSetting.origin == ConfigOrigin.ENV + + // Should return ENV value since JVM source was excluded + value == "envValue" + } + + def "ConfigProvider getMergedMap merges maps from multiple sources with correct precedence"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up: env (partial map), jvm (partial map with overlap) + injectEnvConfig("DD_TEST_MAP", "env_key:env_value,shared:from_env") + injectSysConfig("test.map", "jvm_key:jvm_value,shared:from_jvm") + def provider = ConfigProvider.createDefault() + + when: + def result = provider.getMergedMap("test.map") + def collected = ConfigCollector.get().collect() + + then: + // Result should be merged with JVM taking precedence + result == [ + "env_key": "env_value", // from ENV + "jvm_key": "jvm_value", // from JVM + "shared": "from_jvm" // JVM overrides ENV + ] + + // Default should be reported as empty + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.map") + defaultSetting.value == [:] + defaultSetting.origin == ConfigOrigin.DEFAULT + + // ENV map should be reported + def envSetting = collected.get(ConfigOrigin.ENV).get("test.map") + envSetting.value == ["env_key": "env_value", "shared": "from_env"] + envSetting.origin == ConfigOrigin.ENV + + // JVM map should be reported + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.map") + jvmSetting.value == ["jvm_key": "jvm_value", "shared": "from_jvm"] + jvmSetting.origin == ConfigOrigin.JVM_PROP + + // Final calculated result should be reported with highest seqId + def calculatedSetting = collected.get(ConfigOrigin.CALCULATED).get("test.map") + calculatedSetting.value == result + calculatedSetting.origin == ConfigOrigin.CALCULATED + + // Calculated should have highest seqId + def maxSeqId = [defaultSetting.seqId, envSetting.seqId, jvmSetting.seqId, calculatedSetting.seqId].max() + calculatedSetting.seqId == maxSeqId + } + + def "ConfigProvider getMergedTagsMap handles trace tags format"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up trace tags format (can use comma or space separators) + injectEnvConfig("DD_TEST_TAGS", "service:web,version:1.0") + injectSysConfig("test.tags", "env:prod team:backend") + def provider = ConfigProvider.createDefault() + + when: + def result = provider.getMergedTagsMap("test.tags") + def collected = ConfigCollector.get().collect() + + then: + // Should merge both tag formats + result == [ + "service": "web", // from ENV + "version": "1.0", // from ENV + "env": "prod", // from JVM + "team": "backend" // from JVM + ] + + // Should report individual sources and calculated result + def envSetting = collected.get(ConfigOrigin.ENV).get("test.tags") + envSetting.value == ["service": "web", "version": "1.0"] + + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.tags") + jvmSetting.value == ["env": "prod", "team": "backend"] + + def calculatedSetting = collected.get(ConfigOrigin.CALCULATED).get("test.tags") + calculatedSetting.value == result + } + + def "ConfigProvider getMergedMapWithOptionalMappings handles multiple keys and transformations"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up multiple keys with optional mappings + injectEnvConfig("DD_HEADER_1", "X-Custom-Header:custom.tag") + injectSysConfig("header.1", "X-Auth:auth.tag") + injectEnvConfig("DD_HEADER_2", "X-Request-ID") // key only, should get prefix + def provider = ConfigProvider.createDefault() + + when: + def result = provider.getMergedMapWithOptionalMappings("trace.http", true, "header.1", "header.2") + def collected = ConfigCollector.get().collect() + + then: + // Should merge with transformations + result.size() >= 2 + result["x-custom-header"] == "custom.tag" // from ENV header.1 + result["x-auth"] == "auth.tag" // from JVM header.1 + result["x-request-id"] != null // from ENV header.2, should get prefix + + // Should report sources and calculated result + def calculatedSetting = collected.get(ConfigOrigin.CALCULATED).get("header.2") // Last key processed + calculatedSetting != null + calculatedSetting.origin == ConfigOrigin.CALCULATED + } + + def "ConfigProvider getOrderedMap preserves insertion order and merges sources"() { + setup: + ConfigCollector.get().collect() // clear previous state + + // Set up ordered maps from multiple sources + injectEnvConfig("DD_TEST_ORDERED_MAP", "first:env_first,second:env_second,third:env_third") + injectSysConfig("test.ordered.map", "second:jvm_second,fourth:jvm_fourth,first:jvm_first") + def provider = ConfigProvider.createDefault() + + when: + def result = provider.getOrderedMap("test.ordered.map") + def collected = ConfigCollector.get().collect() + + then: + // Result should be a LinkedHashMap with preserved order and JVM precedence + result instanceof LinkedHashMap + result == [ + "first": "jvm_first", // JVM overrides ENV, appears first due to ENV order + "second": "jvm_second", // JVM overrides ENV, appears second due to ENV order + "third": "env_third", // only in ENV, appears third due to ENV order + "fourth": "jvm_fourth" // only in JVM, appears last due to JVM addition + ] + + // Verify order is preserved (LinkedHashMap maintains insertion order) + def keys = result.keySet() as List + keys == ["first", "second", "third", "fourth"] + + // Default should be reported as empty + def defaultSetting = collected.get(ConfigOrigin.DEFAULT).get("test.ordered.map") + defaultSetting.value == [:] + defaultSetting.origin == ConfigOrigin.DEFAULT + + // ENV ordered map should be reported + def envSetting = collected.get(ConfigOrigin.ENV).get("test.ordered.map") + envSetting.value == ["first": "env_first", "second": "env_second", "third": "env_third"] + envSetting.origin == ConfigOrigin.ENV + + // JVM ordered map should be reported + def jvmSetting = collected.get(ConfigOrigin.JVM_PROP).get("test.ordered.map") + jvmSetting.value == ["second": "jvm_second", "fourth": "jvm_fourth", "first": "jvm_first"] + jvmSetting.origin == ConfigOrigin.JVM_PROP + + // Final calculated result should be reported with highest seqId + def calculatedSetting = collected.get(ConfigOrigin.CALCULATED).get("test.ordered.map") + calculatedSetting.value == result + calculatedSetting.origin == ConfigOrigin.CALCULATED + + // Calculated should have highest seqId + def maxSeqId = [defaultSetting.seqId, envSetting.seqId, jvmSetting.seqId, calculatedSetting.seqId].max() + calculatedSetting.seqId == maxSeqId + } + + def "ConfigProvider methods that call getString internally report their own defaults before getString's null default"() { + setup: + ConfigCollector.get().collect() // clear previous state + // No environment or system property values set, so methods should fall back to their defaults + def provider = ConfigProvider.createDefault() + + when: + def enumResult = provider.getEnum("test.enum", ConfigOrigin, ConfigOrigin.CODE) + def listResult = provider.getList("test.list", ["default", "list"]) + def setResult = provider.getSet("test.set", ["default", "set"] as Set) + def rangeResult = provider.getIntegerRange("test.range", new BitSet()) + def collected = ConfigCollector.get().collect() + + then: + // Each method should have reported its own default, not getString's null default + + def enumDefault = collected.get(ConfigOrigin.DEFAULT).get("test.enum") + enumDefault.stringValue() == "CODE" // ConfigOrigin.CODE.name() + enumDefault.origin == ConfigOrigin.DEFAULT + enumDefault.seqId == ConfigSetting.DEFAULT_SEQ_ID + + def listDefault = collected.get(ConfigOrigin.DEFAULT).get("test.list") + listDefault.value == ["default", "list"] + listDefault.origin == ConfigOrigin.DEFAULT + listDefault.seqId == ConfigSetting.DEFAULT_SEQ_ID + + def setDefault = collected.get(ConfigOrigin.DEFAULT).get("test.set") + setDefault.value == ["default", "set"] as Set + setDefault.origin == ConfigOrigin.DEFAULT + setDefault.seqId == ConfigSetting.DEFAULT_SEQ_ID + + def rangeDefault = collected.get(ConfigOrigin.DEFAULT).get("test.range") + rangeDefault.value == new BitSet() + rangeDefault.origin == ConfigOrigin.DEFAULT + rangeDefault.seqId == ConfigSetting.DEFAULT_SEQ_ID + + // Verify the methods returned their default values (not null) + enumResult == ConfigOrigin.CODE + listResult == ["default", "list"] + setResult == ["default", "set"] as Set + rangeResult == new BitSet() + } + + // NOTE: This is a case that SHOULD never occur. #reReportToCollector(String, int) should only be called with valid origins + def "ConfigValueResolver reReportToCollector handles null origin gracefully"() { + setup: + ConfigCollector.get().collect() // clear previous state + ConfigProvider.ConfigValueResolver resolver = ConfigProvider.ConfigValueResolver.of("1") + + when: + resolver.reReportToCollector("test.key", 5) + + then: + 0 * ConfigCollector.get().put(_, _, _, _, _) + } + + def "ConfigMergeResolver reports correct origin for single vs multiple source contributions"() { + setup: + ConfigCollector.get().collect() // clear previous state + def provider = ConfigProvider.createDefault() + + when: "Only ENV source contributes to merged map" + injectEnvConfig("DD_SINGLE_SOURCE_MAP", "key1:value1,key2:value2") + // No JVM prop set, so only ENV contributes + def singleSourceResult = provider.getMergedMap("single.source.map") + def singleSourceCollected = ConfigCollector.get().collect() + + then: "Should report with ENV origin, not CALCULATED" + singleSourceResult == ["key1": "value1", "key2": "value2"] + + // Should have DEFAULT for default value + def singleDefault = singleSourceCollected.get(ConfigOrigin.DEFAULT)?.get("single.source.map") + singleDefault?.value == [:] + + // Should have ENV for the actual value (not CALCULATED) + def singleEnv = singleSourceCollected.get(ConfigOrigin.ENV)?.get("single.source.map") + singleEnv?.value == ["key1": "value1", "key2": "value2"] + singleEnv?.origin == ConfigOrigin.ENV + + // Should NOT have CALCULATED entry since only one source contributed + singleSourceCollected.get(ConfigOrigin.CALCULATED)?.get("single.source.map") == null + + when: "Multiple sources contribute to merged map" + ConfigCollector.get().collect() // clear for next test + injectEnvConfig("DD_MULTI_SOURCE_MAP", "env_key:env_value,shared:from_env") + injectSysConfig("multi.source.map", "jvm_key:jvm_value,shared:from_jvm") + def multiSourceResult = provider.getMergedMap("multi.source.map") + def multiSourceCollected = ConfigCollector.get().collect() + + then: "Should report with CALCULATED origin when multiple sources contribute" + multiSourceResult == ["env_key": "env_value", "jvm_key": "jvm_value", "shared": "from_jvm"] + + // Should have CALCULATED for the final merged result + def multiCalculated = multiSourceCollected.get(ConfigOrigin.CALCULATED)?.get("multi.source.map") + multiCalculated?.value == multiSourceResult + multiCalculated?.origin == ConfigOrigin.CALCULATED + } } diff --git a/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/StableConfigSourceTest.groovy b/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/StableConfigSourceTest.groovy index 08352da0dcc..84aeda8ebb0 100644 --- a/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/StableConfigSourceTest.groovy +++ b/internal-api/src/test/groovy/datadog/trace/bootstrap/config/provider/StableConfigSourceTest.groovy @@ -305,7 +305,7 @@ apm_configuration_default: then: def collectedConfigs = ConfigCollector.get().collect() - def serviceSetting = collectedConfigs.get("SERVICE") + def serviceSetting = collectedConfigs.get(ConfigOrigin.LOCAL_STABLE_CONFIG).("SERVICE") serviceSetting.configId == expectedConfigId serviceSetting.value == "test-service" serviceSetting.origin == ConfigOrigin.LOCAL_STABLE_CONFIG diff --git a/telemetry/src/main/java/datadog/telemetry/TelemetryRequestBody.java b/telemetry/src/main/java/datadog/telemetry/TelemetryRequestBody.java index f84a4331fd7..b242b7d365e 100644 --- a/telemetry/src/main/java/datadog/telemetry/TelemetryRequestBody.java +++ b/telemetry/src/main/java/datadog/telemetry/TelemetryRequestBody.java @@ -230,6 +230,7 @@ public void writeConfiguration(ConfigSetting configSetting) throws IOException { bodyWriter.name("value").value(configSetting.stringValue()); bodyWriter.setSerializeNulls(false); bodyWriter.name("origin").value(configSetting.origin.value); + bodyWriter.name("seq_id").value(configSetting.seqId); if (configSetting.configId != null) { bodyWriter.name("config_id").value(configSetting.configId); } diff --git a/telemetry/src/main/java/datadog/telemetry/TelemetryRunnable.java b/telemetry/src/main/java/datadog/telemetry/TelemetryRunnable.java index e807bc0cd82..e991ee5ee52 100644 --- a/telemetry/src/main/java/datadog/telemetry/TelemetryRunnable.java +++ b/telemetry/src/main/java/datadog/telemetry/TelemetryRunnable.java @@ -3,6 +3,7 @@ import datadog.telemetry.metric.MetricPeriodicAction; import datadog.trace.api.Config; import datadog.trace.api.ConfigCollector; +import datadog.trace.api.ConfigOrigin; import datadog.trace.api.ConfigSetting; import datadog.trace.api.time.SystemTimeSource; import datadog.trace.api.time.TimeSource; @@ -141,7 +142,7 @@ private void mainLoopIteration() throws InterruptedException { } private void collectConfigChanges() { - Map collectedConfig = ConfigCollector.get().collect(); + Map> collectedConfig = ConfigCollector.get().collect(); if (!collectedConfig.isEmpty()) { telemetryService.addConfiguration(collectedConfig); } diff --git a/telemetry/src/main/java/datadog/telemetry/TelemetryService.java b/telemetry/src/main/java/datadog/telemetry/TelemetryService.java index 1160c27223a..e017dcbe676 100644 --- a/telemetry/src/main/java/datadog/telemetry/TelemetryService.java +++ b/telemetry/src/main/java/datadog/telemetry/TelemetryService.java @@ -7,6 +7,7 @@ import datadog.telemetry.api.Metric; import datadog.telemetry.api.RequestType; import datadog.telemetry.dependency.Dependency; +import datadog.trace.api.ConfigOrigin; import datadog.trace.api.ConfigSetting; import datadog.trace.api.telemetry.Endpoint; import datadog.trace.api.telemetry.ProductChange; @@ -84,11 +85,13 @@ public static TelemetryService build( this.debug = debug; } - public boolean addConfiguration(Map configuration) { - for (ConfigSetting cs : configuration.values()) { - extendedHeartbeatData.pushConfigSetting(cs); - if (!this.configurations.offer(cs)) { - return false; + public boolean addConfiguration(Map> configuration) { + for (Map settings : configuration.values()) { + for (ConfigSetting cs : settings.values()) { + extendedHeartbeatData.pushConfigSetting(cs); + if (!this.configurations.offer(cs)) { + return false; + } } } return true; diff --git a/telemetry/src/test/groovy/datadog/telemetry/TelemetryRequestBodySpecification.groovy b/telemetry/src/test/groovy/datadog/telemetry/TelemetryRequestBodySpecification.groovy index d0f7832da20..25341c82e4b 100644 --- a/telemetry/src/test/groovy/datadog/telemetry/TelemetryRequestBodySpecification.groovy +++ b/telemetry/src/test/groovy/datadog/telemetry/TelemetryRequestBodySpecification.groovy @@ -79,12 +79,12 @@ class TelemetryRequestBodySpecification extends DDSpecification { then: drainToString(req) == ',"configuration":[' + - '{"name":"string","value":"bar","origin":"remote_config"},' + - '{"name":"int","value":"2342","origin":"default"},' + - '{"name":"double","value":"123.456","origin":"env_var"},' + - '{"name":"map","value":"key1:value1,key2:432.32,key3:324","origin":"jvm_prop"},' + - '{"name":"list","value":"1,2,3","origin":"default"},' + - '{"name":"null","value":null,"origin":"default"}]' + '{"name":"string","value":"bar","origin":"remote_config","seq_id":0},' + + '{"name":"int","value":"2342","origin":"default","seq_id":0},' + + '{"name":"double","value":"123.456","origin":"env_var","seq_id":0},' + + '{"name":"map","value":"key1:value1,key2:432.32,key3:324","origin":"jvm_prop","seq_id":0},' + + '{"name":"list","value":"1,2,3","origin":"default","seq_id":0},' + + '{"name":"null","value":null,"origin":"default","seq_id":0}]' } def 'use snake_case for setting keys'() { @@ -102,7 +102,7 @@ class TelemetryRequestBodySpecification extends DDSpecification { req.endConfiguration() then: - drainToString(req) == ',"configuration":[{"name":"this_is_a_key","value":"value","origin":"remote_config"}]' + drainToString(req) == ',"configuration":[{"name":"this_is_a_key","value":"value","origin":"remote_config","seq_id":0}]' } def 'add debug flag'() { diff --git a/telemetry/src/test/groovy/datadog/telemetry/TelemetryServiceSpecification.groovy b/telemetry/src/test/groovy/datadog/telemetry/TelemetryServiceSpecification.groovy index 556d22eba83..c9addb6a253 100644 --- a/telemetry/src/test/groovy/datadog/telemetry/TelemetryServiceSpecification.groovy +++ b/telemetry/src/test/groovy/datadog/telemetry/TelemetryServiceSpecification.groovy @@ -18,8 +18,9 @@ import datadog.trace.test.util.DDSpecification import datadog.trace.util.ConfigStrings class TelemetryServiceSpecification extends DDSpecification { - def confKeyValue = ConfigSetting.of("confkey", "confvalue", ConfigOrigin.DEFAULT) - def configuration = [confkey: confKeyValue] + def confKeyOrigin = ConfigOrigin.DEFAULT + def confKeyValue = ConfigSetting.of("confkey", "confvalue", confKeyOrigin) + def configuration = [confKeyOrigin: [confkey: confKeyValue]] def integration = new Integration("integration", true) def dependency = new Dependency("dependency", "1.0.0", "src", "hash") def metric = new Metric().namespace("tracers").metric("metric").points([[1, 2]]).tags(["tag1", "tag2"]) @@ -317,7 +318,7 @@ class TelemetryServiceSpecification extends DDSpecification { bodySize > 0 when: 'sending first part of data' - telemetryService = new TelemetryService(testHttpClient, bodySize + 500, false) + telemetryService = new TelemetryService(testHttpClient, bodySize + 510, false) telemetryService.addConfiguration(configuration) telemetryService.addIntegration(integration) @@ -437,7 +438,8 @@ class TelemetryServiceSpecification extends DDSpecification { String instrKey = 'instrumentation_config_id' TestTelemetryRouter testHttpClient = new TestTelemetryRouter() TelemetryService telemetryService = new TelemetryService(testHttpClient, 10000, false) - telemetryService.addConfiguration(['${instrKey}': ConfigSetting.of(instrKey, id, ConfigOrigin.ENV)]) + def configMap = [(instrKey): ConfigSetting.of(instrKey, id, ConfigOrigin.ENV)] + telemetryService.addConfiguration([(ConfigOrigin.ENV): configMap]) when: 'first iteration' testHttpClient.expectRequest(TelemetryClient.Result.SUCCESS) diff --git a/telemetry/src/test/groovy/datadog/telemetry/TestTelemetryRouter.groovy b/telemetry/src/test/groovy/datadog/telemetry/TestTelemetryRouter.groovy index d1b29549bf1..0729b44a121 100644 --- a/telemetry/src/test/groovy/datadog/telemetry/TestTelemetryRouter.groovy +++ b/telemetry/src/test/groovy/datadog/telemetry/TestTelemetryRouter.groovy @@ -237,7 +237,8 @@ class TestTelemetryRouter extends TelemetryRouter { def expected = configuration == null ? null : [] if (configuration != null) { for (ConfigSetting cs : configuration) { - expected.add([name: cs.normalizedKey(), value: cs.stringValue(), origin: cs.origin.value]) + def item = [name: cs.normalizedKey(), value: cs.stringValue(), origin: cs.origin.value, 'seq_id': cs.seqId] + expected.add(item) } } assert this.payload['configuration'] == expected diff --git a/utils/config-utils/src/main/java/datadog/trace/api/ConfigCollector.java b/utils/config-utils/src/main/java/datadog/trace/api/ConfigCollector.java index 6e4ebc0969c..4cbaf5acf6b 100644 --- a/utils/config-utils/src/main/java/datadog/trace/api/ConfigCollector.java +++ b/utils/config-utils/src/main/java/datadog/trace/api/ConfigCollector.java @@ -1,9 +1,15 @@ package datadog.trace.api; +import static datadog.trace.api.ConfigOrigin.DEFAULT; +import static datadog.trace.api.ConfigOrigin.REMOTE; +import static datadog.trace.api.ConfigSetting.ABSENT_SEQ_ID; +import static datadog.trace.api.ConfigSetting.DEFAULT_SEQ_ID; + import java.util.Collections; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; +import java.util.function.Function; /** * Collects system properties and environment variables set by the user and used by the tracer. Puts @@ -16,43 +22,78 @@ public class ConfigCollector { private static final AtomicReferenceFieldUpdater COLLECTED_UPDATER = AtomicReferenceFieldUpdater.newUpdater(ConfigCollector.class, Map.class, "collected"); - private volatile Map collected = new ConcurrentHashMap<>(); + private static final Function> NEW_SUB_MAP = + k -> new ConcurrentHashMap<>(); + + private volatile Map> collected = + new ConcurrentHashMap<>(); public static ConfigCollector get() { return INSTANCE; } - public void put(String key, Object value, ConfigOrigin origin) { - ConfigSetting setting = ConfigSetting.of(key, value, origin); - collected.put(key, setting); + public void put(String key, Object value, ConfigOrigin origin, int seqId) { + put(key, value, origin, seqId, null); } - public void put(String key, Object value, ConfigOrigin origin, String configId) { - ConfigSetting setting = ConfigSetting.of(key, value, origin, configId); - collected.put(key, setting); + public void put(String key, Object value, ConfigOrigin origin, int seqId, String configId) { + ConfigSetting setting = ConfigSetting.of(key, value, origin, seqId, configId); + Map configMap = collected.computeIfAbsent(origin, NEW_SUB_MAP); + configMap.put(key, setting); // replaces any previous value for this key at origin } - public void putAll(Map keysAndValues, ConfigOrigin origin) { + // put method specifically for DEFAULT origins. We don't allow overrides for configs from DEFAULT + // origins + public void putDefault(String key, Object value) { + ConfigSetting setting = ConfigSetting.of(key, value, DEFAULT, DEFAULT_SEQ_ID); + Map configMap = collected.computeIfAbsent(DEFAULT, NEW_SUB_MAP); + configMap.putIfAbsent(key, setting); // don't replace previous default for this key + } + + /** + * Report single configuration setting with REMOTE origin. + * + * @param key configuration key to report + * @param value configuration value to report + */ + public void putRemote(String key, Object value) { + put(key, value, REMOTE, ABSENT_SEQ_ID); + } + + /** + * Report multiple configuration settings with REMOTE origin. + * + * @param configMap map of configuration key-value pairs to report + */ + public void putRemote(Map configMap) { // attempt merge+replace to avoid collector seeing partial update - Map merged = - new ConcurrentHashMap<>(keysAndValues.size() + collected.size()); - for (Map.Entry entry : keysAndValues.entrySet()) { - ConfigSetting setting = ConfigSetting.of(entry.getKey(), entry.getValue(), origin); + Map merged = new ConcurrentHashMap<>(); + + // prepare update + for (Map.Entry entry : configMap.entrySet()) { + ConfigSetting setting = + ConfigSetting.of(entry.getKey(), entry.getValue(), REMOTE, ABSENT_SEQ_ID); merged.put(entry.getKey(), setting); } + while (true) { - Map current = collected; + // first try adding our update to the map + Map current = collected.putIfAbsent(REMOTE, merged); + if (current == null) { + break; // success, no merging required + } + // merge existing entries with updated entries current.forEach(merged::putIfAbsent); - if (COLLECTED_UPDATER.compareAndSet(this, current, merged)) { - break; // success + if (collected.replace(REMOTE, current, merged)) { + break; // success, atomically swapped in merged map } // roll back to original update before next attempt - merged.keySet().retainAll(keysAndValues.keySet()); + merged.keySet().retainAll(configMap.keySet()); } } @SuppressWarnings("unchecked") - public Map collect() { + public Map> collect() { if (!collected.isEmpty()) { return COLLECTED_UPDATER.getAndSet(this, new ConcurrentHashMap<>()); } else { diff --git a/utils/config-utils/src/main/java/datadog/trace/api/ConfigSetting.java b/utils/config-utils/src/main/java/datadog/trace/api/ConfigSetting.java index 9b94b444a02..45e434751b5 100644 --- a/utils/config-utils/src/main/java/datadog/trace/api/ConfigSetting.java +++ b/utils/config-utils/src/main/java/datadog/trace/api/ConfigSetting.java @@ -8,9 +8,15 @@ import java.util.Set; public final class ConfigSetting { + public static final int DEFAULT_SEQ_ID = 1; + public static final int NON_DEFAULT_SEQ_ID = DEFAULT_SEQ_ID + 1; + public static final int ABSENT_SEQ_ID = 0; + public final String key; public final Object value; public final ConfigOrigin origin; + public final int seqId; + /** The config ID associated with this setting, or {@code null} if not applicable. */ public final String configId; @@ -19,17 +25,28 @@ public final class ConfigSetting { Arrays.asList("DD_API_KEY", "dd.api-key", "dd.profiling.api-key", "dd.profiling.apikey")); public static ConfigSetting of(String key, Object value, ConfigOrigin origin) { - return new ConfigSetting(key, value, origin, null); + return new ConfigSetting(key, value, origin, ABSENT_SEQ_ID, null); + } + + public static ConfigSetting of(String key, Object value, ConfigOrigin origin, int seqId) { + return new ConfigSetting(key, value, origin, seqId, null); } + // No usages of this function public static ConfigSetting of(String key, Object value, ConfigOrigin origin, String configId) { - return new ConfigSetting(key, value, origin, configId); + return new ConfigSetting(key, value, origin, ABSENT_SEQ_ID, configId); + } + + public static ConfigSetting of( + String key, Object value, ConfigOrigin origin, int seqId, String configId) { + return new ConfigSetting(key, value, origin, seqId, configId); } - private ConfigSetting(String key, Object value, ConfigOrigin origin, String configId) { + private ConfigSetting(String key, Object value, ConfigOrigin origin, int seqId, String configId) { this.key = key; this.value = CONFIG_FILTER_LIST.contains(key) ? "" : value; this.origin = origin; + this.seqId = seqId; this.configId = configId; } @@ -109,12 +126,13 @@ public boolean equals(Object o) { return key.equals(that.key) && Objects.equals(value, that.value) && origin == that.origin + && seqId == that.seqId && Objects.equals(configId, that.configId); } @Override public int hashCode() { - return Objects.hash(key, value, origin, configId); + return Objects.hash(key, value, origin, seqId, configId); } @Override @@ -127,6 +145,8 @@ public String toString() { + stringValue() + ", origin=" + origin + + ", seqId=" + + seqId + ", configId=" + configId + '}'; diff --git a/utils/config-utils/src/main/java/datadog/trace/bootstrap/config/provider/ConfigProvider.java b/utils/config-utils/src/main/java/datadog/trace/bootstrap/config/provider/ConfigProvider.java index 173d717fa43..ade045011db 100644 --- a/utils/config-utils/src/main/java/datadog/trace/bootstrap/config/provider/ConfigProvider.java +++ b/utils/config-utils/src/main/java/datadog/trace/bootstrap/config/provider/ConfigProvider.java @@ -1,5 +1,7 @@ package datadog.trace.bootstrap.config.provider; +import static datadog.trace.api.ConfigSetting.ABSENT_SEQ_ID; +import static datadog.trace.api.ConfigSetting.NON_DEFAULT_SEQ_ID; import static datadog.trace.api.config.GeneralConfig.CONFIGURATION_FILE; import datadog.environment.SystemProperties; @@ -12,6 +14,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.BitSet; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; @@ -54,38 +57,61 @@ public String getConfigFileStatus() { return "no config file present"; } + // Gets a string value when there is no default value. public String getString(String key) { return getString(key, null); } - public > T getEnum(String key, Class enumType, T defaultValue) { - String value = getString(key); - if (null != value) { - try { - return Enum.valueOf(enumType, value); - } catch (Exception ignoreAndUseDefault) { - log.debug("failed to parse {} for {}, defaulting to {}", value, key, defaultValue); - } - } + /** + * Gets a string value with a default fallback and optional aliases. Use for configs with + * meaningful defaults. Reports default to telemetry. + */ + public String getString(String key, String defaultValue, String... aliases) { if (collectConfig) { - String valueStr = defaultValue == null ? null : defaultValue.name(); - ConfigCollector.get().put(key, valueStr, ConfigOrigin.DEFAULT); + reportDefault(key, defaultValue); } - return defaultValue; + String value = getStringInternal(key, aliases); + + return value != null ? value : defaultValue; } - public String getString(String key, String defaultValue, String... aliases) { - for (ConfigProvider.Source source : sources) { - String value = source.get(key, aliases); - if (value != null) { + // Internal helper that performs configuration source lookup and reports values from non-default + // sources to telemetry. + private String getStringInternal(String key, String... aliases) { + ConfigValueResolver resolver = null; + int seqId = NON_DEFAULT_SEQ_ID; + + for (int i = sources.length - 1; i >= 0; i--) { + ConfigProvider.Source source = sources[i]; + String candidate = source.get(key, aliases); + // Create resolver if we have a valid candidate + if (candidate != null) { + resolver = ConfigValueResolver.of(candidate); + // And report to telemetry if (collectConfig) { - ConfigCollector.get().put(key, value, source.origin(), getConfigIdFromSource(source)); + ConfigCollector.get() + .put(key, candidate, source.origin(), seqId, getConfigIdFromSource(source)); } - return value; } + + seqId++; } + + return resolver != null ? resolver.value : null; + } + + public > T getEnum(String key, Class enumType, T defaultValue) { if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); + String defaultValueString = defaultValue == null ? null : defaultValue.name(); + reportDefault(key, defaultValueString); + } + String value = getStringInternal(key); + if (null != value) { + try { + return Enum.valueOf(enumType, value); + } catch (Exception ignoreAndUseDefault) { + log.debug("failed to parse {} for {}, defaulting to {}", value, key, defaultValue); + } } return defaultValue; } @@ -95,19 +121,40 @@ public String getString(String key, String defaultValue, String... aliases) { * an empty or blank string. */ public String getStringNotEmpty(String key, String defaultValue, String... aliases) { - for (ConfigProvider.Source source : sources) { - String value = source.get(key, aliases); - if (value != null && !value.trim().isEmpty()) { + if (collectConfig) { + reportDefault(key, defaultValue); + } + + ConfigValueResolver resolver = null; + int seqId = NON_DEFAULT_SEQ_ID; + + for (int i = sources.length - 1; i >= 0; i--) { + ConfigProvider.Source source = sources[i]; + String candidateValue = source.get(key, aliases); + + // Report any non-null values to telemetry + if (candidateValue != null) { if (collectConfig) { - ConfigCollector.get().put(key, value, source.origin()); + ConfigCollector.get() + .put(key, candidateValue, source.origin(), seqId, getConfigIdFromSource(source)); + } + // Create resolver only if candidate is not empty or blank + if (!candidateValue.trim().isEmpty()) { + resolver = + ConfigValueResolver.of( + candidateValue, source.origin(), seqId, getConfigIdFromSource(source)); } - return value; } + + seqId++; } - if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); + + // Re-report the chosen value with the highest seqId + if (resolver != null && collectConfig) { + resolver.reReportToCollector(key, seqId + 1); } - return defaultValue; + + return resolver != null ? resolver.value : defaultValue; } public String getStringExcludingSource( @@ -115,23 +162,30 @@ public String getStringExcludingSource( String defaultValue, Class excludedSource, String... aliases) { - for (ConfigProvider.Source source : sources) { + if (collectConfig) { + reportDefault(key, defaultValue); + } + ConfigValueResolver resolver = null; + int seqId = NON_DEFAULT_SEQ_ID; + for (int i = sources.length - 1; i >= 0; i--) { + ConfigProvider.Source source = sources[i]; + String candidate = source.get(key, aliases); + + // Skip excluded source types if (excludedSource.isAssignableFrom(source.getClass())) { + seqId++; continue; } - - String value = source.get(key, aliases); - if (value != null) { + if (candidate != null) { + resolver = ConfigValueResolver.of(candidate); if (collectConfig) { - ConfigCollector.get().put(key, value, source.origin()); + ConfigCollector.get() + .put(key, candidate, source.origin(), seqId, getConfigIdFromSource(source)); } - return value; } + seqId++; } - if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); - } - return defaultValue; + return resolver != null ? resolver.value : defaultValue; } public boolean isSet(String key) { @@ -192,35 +246,48 @@ public double getDouble(String key, double defaultValue) { } private T get(String key, T defaultValue, Class type, String... aliases) { - for (ConfigProvider.Source source : sources) { - String sourceValue = source.get(key, aliases); + if (collectConfig) { + reportDefault(key, defaultValue); + } + + ConfigValueResolver resolver = null; + int seqId = NON_DEFAULT_SEQ_ID; + + for (int i = sources.length - 1; i >= 0; i--) { + String sourceValue = sources[i].get(key, aliases); + String configId = getConfigIdFromSource(sources[i]); + + // Always report raw value to telemetry + if (sourceValue != null && collectConfig) { + ConfigCollector.get().put(key, sourceValue, sources[i].origin(), seqId, configId); + } + try { - T value = ConfigConverter.valueOf(sourceValue, type); - if (value != null) { - if (collectConfig) { - ConfigCollector.get() - .put(key, sourceValue, source.origin(), getConfigIdFromSource(source)); - } - return value; + T candidate = ConfigConverter.valueOf(sourceValue, type); + if (candidate != null) { + resolver = ConfigValueResolver.of(candidate, sources[i].origin(), seqId, configId); } } catch (ConfigConverter.InvalidBooleanValueException ex) { // For backward compatibility: invalid boolean values should return false, not default - // Store the invalid sourceValue for telemetry, but return false for the application + // Store the invalid sourceValue for telemetry, but return false if (Boolean.class.equals(type)) { - if (collectConfig) { - ConfigCollector.get().put(key, sourceValue, source.origin()); - } - return (T) Boolean.FALSE; + resolver = + ConfigValueResolver.of((T) Boolean.FALSE, ConfigOrigin.CALCULATED, seqId, configId); } // For non-boolean types, continue to next source } catch (IllegalArgumentException ex) { // continue - covers both NumberFormatException and other IllegalArgumentException } + + seqId++; } - if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); + + // Re-report the chosen value and origin to ensure its seqId is higher than any error configs + if (resolver != null && collectConfig) { + resolver.reReportToCollector(key, seqId + 1); } - return defaultValue; + + return resolver != null ? resolver.value : defaultValue; } public List getList(String key) { @@ -228,11 +295,12 @@ public List getList(String key) { } public List getList(String key, List defaultValue) { - String list = getString(key); + // Ensure the first item at DEFAULT is the accurate one + if (collectConfig) { + reportDefault(key, defaultValue); + } + String list = getStringInternal(key); if (null == list) { - if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); - } return defaultValue; } else { return ConfigConverter.parseList(list); @@ -240,11 +308,12 @@ public List getList(String key, List defaultValue) { } public Set getSet(String key, Set defaultValue) { - String list = getString(key); + // Ensure the first item at DEFAULT is the most accurate one + if (collectConfig) { + reportDefault(key, defaultValue); + } + String list = getStringInternal(key); if (null == list) { - if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); - } return defaultValue; } else { return new HashSet(ConfigConverter.parseList(list)); @@ -256,9 +325,9 @@ public List getSpacedList(String key) { } public Map getMergedMap(String key, String... aliases) { - Map merged = new HashMap<>(); - ConfigOrigin origin = ConfigOrigin.DEFAULT; - String configId = null; + ConfigMergeResolver mergeResolver = new ConfigMergeResolver(new HashMap<>()); + int seqId = NON_DEFAULT_SEQ_ID; + // System properties take precedence over env // prior art: // https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html @@ -266,27 +335,29 @@ public Map getMergedMap(String key, String... aliases) { for (int i = sources.length - 1; 0 <= i; i--) { String value = sources[i].get(key, aliases); Map parsedMap = ConfigConverter.parseMap(value, key); + if (!parsedMap.isEmpty()) { - configId = getConfigIdFromSource(sources[i]); - if (origin != ConfigOrigin.DEFAULT) { - // if we already have a non-default origin, the value is calculated from multiple sources - origin = ConfigOrigin.CALCULATED; - } else { - origin = sources[i].origin(); + if (collectConfig) { + seqId++; + ConfigCollector.get() + .put(key, parsedMap, sources[i].origin(), seqId, getConfigIdFromSource(sources[i])); } + mergeResolver.addContribution(parsedMap, sources[i].origin()); } - merged.putAll(parsedMap); } + if (collectConfig) { - ConfigCollector.get().put(key, merged, origin, configId); + reportDefault(key, Collections.emptyMap()); + mergeResolver.reReportFinalResult(key, seqId); } - return merged; + + return mergeResolver.getMergedValue(); } public Map getMergedTagsMap(String key, String... aliases) { - Map merged = new HashMap<>(); - ConfigOrigin origin = ConfigOrigin.DEFAULT; - String configId = null; + ConfigMergeResolver mergeResolver = new ConfigMergeResolver(new HashMap<>()); + int seqId = NON_DEFAULT_SEQ_ID; + // System properties take precedence over env // prior art: // https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html @@ -295,27 +366,30 @@ public Map getMergedTagsMap(String key, String... aliases) { String value = sources[i].get(key, aliases); Map parsedMap = ConfigConverter.parseTraceTagsMap(value, ':', Arrays.asList(',', ' ')); + if (!parsedMap.isEmpty()) { - configId = getConfigIdFromSource(sources[i]); - if (origin != ConfigOrigin.DEFAULT) { - // if we already have a non-default origin, the value is calculated from multiple sources - origin = ConfigOrigin.CALCULATED; - } else { - origin = sources[i].origin(); + if (collectConfig) { + seqId++; + ConfigCollector.get() + .put(key, parsedMap, sources[i].origin(), seqId, getConfigIdFromSource(sources[i])); } + mergeResolver.addContribution(parsedMap, sources[i].origin()); } - merged.putAll(parsedMap); } + if (collectConfig) { - ConfigCollector.get().put(key, merged, origin, configId); + reportDefault(key, Collections.emptyMap()); + mergeResolver.reReportFinalResult(key, seqId); } - return merged; + + return mergeResolver.getMergedValue(); } public Map getOrderedMap(String key) { - LinkedHashMap merged = new LinkedHashMap<>(); - ConfigOrigin origin = ConfigOrigin.DEFAULT; - String configId = null; + // Use LinkedHashMap to preserve insertion order of map entries + ConfigMergeResolver mergeResolver = new ConfigMergeResolver(new LinkedHashMap<>()); + int seqId = NON_DEFAULT_SEQ_ID; + // System properties take precedence over env // prior art: // https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html @@ -323,28 +397,30 @@ public Map getOrderedMap(String key) { for (int i = sources.length - 1; 0 <= i; i--) { String value = sources[i].get(key); Map parsedMap = ConfigConverter.parseOrderedMap(value, key); + if (!parsedMap.isEmpty()) { - configId = getConfigIdFromSource(sources[i]); - if (origin != ConfigOrigin.DEFAULT) { - // if we already have a non-default origin, the value is calculated from multiple sources - origin = ConfigOrigin.CALCULATED; - } else { - origin = sources[i].origin(); + if (collectConfig) { + seqId++; + ConfigCollector.get() + .put(key, parsedMap, sources[i].origin(), seqId, getConfigIdFromSource(sources[i])); } + mergeResolver.addContribution(parsedMap, sources[i].origin()); } - merged.putAll(parsedMap); } + if (collectConfig) { - ConfigCollector.get().put(key, merged, origin, configId); + reportDefault(key, Collections.emptyMap()); + mergeResolver.reReportFinalResult(key, seqId); } - return merged; + + return mergeResolver.getMergedValue(); } public Map getMergedMapWithOptionalMappings( String defaultPrefix, boolean lowercaseKeys, String... keys) { - Map merged = new HashMap<>(); - ConfigOrigin origin = ConfigOrigin.DEFAULT; - String configId = null; + ConfigMergeResolver mergeResolver = new ConfigMergeResolver(new HashMap<>()); + int seqId = NON_DEFAULT_SEQ_ID; + // System properties take precedence over env // prior art: // https://docs.spring.io/spring-boot/docs/1.5.6.RELEASE/reference/html/boot-features-external-config.html @@ -354,27 +430,32 @@ public Map getMergedMapWithOptionalMappings( String value = sources[i].get(key); Map parsedMap = ConfigConverter.parseMapWithOptionalMappings(value, key, defaultPrefix, lowercaseKeys); + if (!parsedMap.isEmpty()) { - configId = getConfigIdFromSource(sources[i]); - if (origin != ConfigOrigin.DEFAULT) { - // if we already have a non-default origin, the value is calculated from multiple - // sources - origin = ConfigOrigin.CALCULATED; - } else { - origin = sources[i].origin(); + if (collectConfig) { + seqId++; + ConfigCollector.get() + .put(key, parsedMap, sources[i].origin(), seqId, getConfigIdFromSource(sources[i])); } + mergeResolver.addContribution(parsedMap, sources[i].origin()); } - merged.putAll(parsedMap); } + if (collectConfig) { - ConfigCollector.get().put(key, merged, origin, configId); + reportDefault(key, Collections.emptyMap()); + mergeResolver.reReportFinalResult(key, seqId); } } - return merged; + + return mergeResolver.getMergedValue(); } public BitSet getIntegerRange(final String key, final BitSet defaultValue, String... aliases) { - final String value = getString(key, null, aliases); + // Ensure the first item at DEFAULT is the most accurate one + if (collectConfig) { + reportDefault(key, defaultValue); + } + final String value = getStringInternal(key, aliases); try { if (value != null) { return ConfigConverter.parseIntegerRangeSet(value, key); @@ -382,9 +463,6 @@ public BitSet getIntegerRange(final String key, final BitSet defaultValue, Strin } catch (final NumberFormatException e) { log.warn("Invalid configuration for {}", key, e); } - if (collectConfig) { - ConfigCollector.get().put(key, defaultValue, ConfigOrigin.DEFAULT); - } return defaultValue; } @@ -546,6 +624,83 @@ private static String getConfigIdFromSource(Source source) { return null; } + private static void reportDefault(String key, T defaultValue) { + ConfigCollector.get().putDefault(key, defaultValue); + } + + /** Helper class to store resolved configuration values with their metadata */ + static final class ConfigValueResolver { + final T value; + final ConfigOrigin origin; + final int seqId; + final String configId; + + // Single constructor that takes all fields + private ConfigValueResolver(T value, ConfigOrigin origin, int seqId, String configId) { + this.value = value; + this.origin = origin; + this.seqId = seqId; + this.configId = configId; + } + + // Factory method for cases where we only care about the value (e.g., getString) + static ConfigValueResolver of(T value) { + return new ConfigValueResolver<>(value, null, ABSENT_SEQ_ID, null); + } + + // Factory method for cases where we need to re-report (e.g., getStringNotEmpty, get) + static ConfigValueResolver of(T value, ConfigOrigin origin, int seqId, String configId) { + return new ConfigValueResolver<>(value, origin, seqId, configId); + } + + /** Re-reports this resolved value to ConfigCollector with the specified seqId */ + void reReportToCollector(String key, int finalSeqId) { + // Value should never be null if there is an initialized ConfigValueResolver + if (origin != null) { + ConfigCollector.get().put(key, value, origin, finalSeqId, configId); + } + } + } + + /** Helper class for methods that merge map values from multiple sources (e.g., getMergedMap) */ + private static final class ConfigMergeResolver { + private final Map mergedValue; + private ConfigOrigin currentOrigin; + + ConfigMergeResolver(Map initialValue) { + this.mergedValue = initialValue; + this.currentOrigin = ConfigOrigin.DEFAULT; + } + + /** Adds a contribution from a source and updates the origin tracking */ + void addContribution(Map contribution, ConfigOrigin sourceOrigin) { + mergedValue.putAll(contribution); + + // Update origin: DEFAULT -> source origin -> CALCULATED if multiple sources + if (currentOrigin != ConfigOrigin.DEFAULT) { + // if we already have a non-default origin, the value is calculated from multiple sources + currentOrigin = ConfigOrigin.CALCULATED; + } else { + currentOrigin = sourceOrigin; + } + } + + /** + * Re-reports the final merged result to ConfigCollector if it has actual contributions. Does + * NOT re-report when no contributions were made since defaults are reported separately. + */ + void reReportFinalResult(String key, int finalSeqId) { + if (currentOrigin != ConfigOrigin.DEFAULT && !mergedValue.isEmpty()) { + ConfigCollector.get().put(key, mergedValue, currentOrigin, finalSeqId); + } + } + + /** Gets the final merged value */ + Map getMergedValue() { + return mergedValue; + } + } + public abstract static class Source { public final String get(String key, String... aliases) { String value = get(key);