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
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
package tech.illuin.wombat.core.activity.commons;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;

@JsonClassDescription("ISO 3166-1 alpha-3 country code, XXX for the world")
public final class Country
{
private final Locale locale;
private final String alpha2;
private final String alpha3;
private final String name;

private static final Map<String, Country> indexAlpha2;
private static final Map<String, Country> indexAlpha3;
private static final List<Country> values;

static {
indexAlpha2 = new HashMap<>();
Expand All @@ -25,9 +33,13 @@ public final class Country
indexAlpha3.put(country.alpha3(), country);
}

var world = new Country(Locale.ROOT);
indexAlpha2.put("XX", world);
indexAlpha3.put("XXX", world);
var world = new Country(Locale.ROOT, "XX", "XXX", "World");
indexAlpha2.put(world.alpha2(), world);
indexAlpha3.put(world.alpha3(), world);

values = indexAlpha3.values().stream()
.sorted(Comparator.comparing(Country::alpha3))
.toList();
}

public static final Country WORLD = ofAlpha2("XX");
Expand Down Expand Up @@ -77,15 +89,31 @@ public static Country ofAlpha3(String alpha3)
return indexAlpha3.get(alpha3.toUpperCase());
}

/**
* @return every known country, ordered by alpha-3 code
*/
public static List<Country> values()
{
return values;
}

public static Optional<Country> ofCode(String code)
{
return Optional.ofNullable(ofAlpha2(code))
.or(() -> Optional.ofNullable(ofAlpha3(code)));
}

private Country(Locale locale)
private Country(Locale locale, String alpha2, String alpha3, String name)
{
this.locale = locale;
this.alpha2 = alpha2;
this.alpha3 = alpha3;
this.name = name;
}

private Country(Locale locale)
{
this(locale, locale.getCountry(), locale.getISO3Country(), null);
}

private Country(String alpha2Code)
Expand All @@ -95,22 +123,22 @@ private Country(String alpha2Code)

public String alpha2()
{
return this.locale.getCountry();
return this.alpha2;
}

@JsonValue
public String alpha3()
{
return this.locale.getISO3Country();
return this.alpha3;
}

public String displayName()
{
return this.locale.getDisplayCountry(Locale.ENGLISH);
return this.displayName(Locale.ENGLISH);
}

public String displayName(Locale locale)
{
return this.locale.getDisplayCountry(locale);
return this.name != null ? this.name : this.locale.getDisplayCountry(locale);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package tech.illuin.wombat.core.activity.commons;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import tech.illuin.wombat.core.activity.commons.validation.ValidTimeRange;

import java.time.Duration;
Expand All @@ -15,9 +14,9 @@

@ValidTimeRange
public record TimeRange(
@JsonProperty("start") Instant start,
@JsonProperty("end") Instant end,
@JsonProperty("resolution") Duration resolution
Instant start,
Instant end,
Duration resolution
) {
public TimeRange
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import jakarta.validation.constraints.NotBlank;
import tech.illuin.wombat.core.asset.type.AssetType;

Expand All @@ -14,9 +15,10 @@
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public record AssetIdentity(
@NotBlank @JsonProperty("id") String id,
@NotBlank @JsonProperty("environmentId") @JsonAlias("environment-id") String environmentId,
@NotBlank @JsonProperty("type") String assetType
@NotBlank @JsonPropertyDescription("Unique identifier of the asset") String id,
// The kebab-case @JsonAlias read assets persisted before 0.15, when properties were named that way
@NotBlank @JsonPropertyDescription("Identifier of the asset's environment") @JsonAlias("environment-id") String environmentId,
@NotBlank @JsonPropertyDescription("Name of the asset-type") @JsonProperty("type") String assetType
) {
public AssetIdentity
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package tech.illuin.wombat.core.asset.profile;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import java.time.Duration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@JsonClassDescription("Duration as an amount and a unit suffix: h (hours), d (days), m (months), y (years), e.g. 5y; a bare amount is in hours")
public record Lifetime(
long value,
Unit unit
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@

@JsonIgnoreProperties(ignoreUnknown = true)
public record AssetType(
@NotBlank @JsonProperty("namespace") String namespace,
@NotBlank @JsonProperty("localName") String localName,
@NotNull @JsonProperty("regime") ActivityRegime regime,
@NotNull @JsonProperty("family") ServiceFamily family
@NotBlank String namespace,
@NotBlank String localName,
@NotNull ActivityRegime regime,
@NotNull ServiceFamily family
) {
public AssetType
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import tech.illuin.wombat.core.activity.commons.ActivityData;
import tech.illuin.wombat.core.activity.commons.Country;
import tech.illuin.wombat.core.activity.commons.TimeRange;
import tech.illuin.wombat.core.asset.Asset;
import tech.illuin.wombat.core.asset.profile.ServerProvider;
Expand Down Expand Up @@ -31,6 +32,8 @@ public class BoaviztaEvaluationResolver implements WombatEvaluationResolver

private static final double NANOCORES_PER_CORE = 1_000_000_000.0;
private static final double FULL_LOAD = 100.0;
/** Boavizta's world average, ISO 3166 having no code for the world. */
private static final String WORLD_LOCATION = "WOR";
private static final String rebalanceWarning = "This usage has been rebalanced by the Wombat service, it does not come from the Boavizta API";
private static final String timeProrationWarning = "This impact has been prorated to the requested time range by the Wombat service";

Expand Down Expand Up @@ -178,7 +181,7 @@ private BoaviztaImpactResponse requestImpactFromPercentage(ServerProfile profile
new BoaviztaInstanceImpactRequest(
getProvider(profile.provider()),
profile.instanceType(),
new BoaviztaInstanceImpactRequest.Usage(profile.location().alpha3(), List.of(new BoaviztaInstanceImpactRequest.Usage.LoadSegment(100, loadPercentage)))
new BoaviztaInstanceImpactRequest.Usage(getLocation(profile.location()), List.of(new BoaviztaInstanceImpactRequest.Usage.LoadSegment(100, loadPercentage)))
),
(int) profile.lifespan().asHours()
);
Expand Down Expand Up @@ -301,5 +304,10 @@ private static BoaviztaServerProvider getProvider(ServerProvider provider)
.orElseThrow(() -> new IllegalArgumentException("Unsupported Server provider: " + provider));
}

private static String getLocation(Country location)
{
return location == Country.WORLD ? WORLD_LOCATION : location.alpha3();
}

private record Share(String serviceId, double share) {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ public class EcologitsEvaluationResolver implements WombatEvaluationResolver
{
private final EcologitsClient client;

/** Ecologits' world electricity mix, ISO 3166 having no code for the world. */
private static final String WORLD_ZONE = "WOR";
private static final Logger logger = LoggerFactory.getLogger(EcologitsEvaluationResolver.class);

public EcologitsEvaluationResolver(EcologitsClient client)
Expand Down Expand Up @@ -127,11 +129,16 @@ private EcologitsEstimationResponse estimate(LLMProvider provider, String model,
ecologitsProvider,
model,
outputTokenCount,
location.alpha3()
electricityMixZone(location)
);
return this.client.estimate(request);
}

private static String electricityMixZone(Country location)
{
return location == Country.WORLD ? WORLD_ZONE : location.alpha3();
}

private static boolean validate(EcologitsEstimationResponse response)
{
if (response == null || response.impacts() == null)
Expand Down
35 changes: 35 additions & 0 deletions core/src/main/java/tech/illuin/wombat/core/secret/SecretKey.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package tech.illuin.wombat.core.secret;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import java.util.Objects;

/**
* The name under which a secret is bound in a {@link SecretResolver}, never its value: it is safe to store, log and
* review. Assets declare their credentials with this type rather than a plain string, so tools reading their shape
* (e.g. a JSON schema) can tell a secret reference apart from any other text.
*/
@JsonClassDescription("Name of a secret, resolved by the configured secret resolver")
public record SecretKey(@JsonValue String value)
{
public SecretKey
{
Objects.requireNonNull(value, "value cannot be null");
if (value.isBlank())
throw new IllegalArgumentException("value cannot be null or blank");
}

/**
* @return the key named {@code value}, {@code null} when it is null or blank: such a value names no secret, which
* lets a templated configuration leave an optional key empty
*/
@JsonCreator(mode = JsonCreator.Mode.DELEGATING)
public static SecretKey of(String value)
{
if (value == null || value.isBlank())
return null;
return new SecretKey(value);
}
}
2 changes: 2 additions & 0 deletions core/src/main/java/tech/illuin/wombat/core/source/Period.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package tech.illuin.wombat.core.source;

import com.fasterxml.jackson.annotation.JsonClassDescription;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

Expand All @@ -13,6 +14,7 @@
* @param value
* @param unit
*/
@JsonClassDescription("Duration as an amount and a unit suffix: s (seconds), m (minutes), h (hours), e.g. 5m")
public record Period(
long value,
Unit unit
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package tech.illuin.wombat.core.activity.commons;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.List;
import java.util.Locale;

import static org.junit.jupiter.api.Assertions.*;
Expand Down Expand Up @@ -121,4 +124,37 @@ void testAllISOCountriesIndexed()
assertSame(country, fromAlpha3);
}
}

@Test
void testValuesListsEveryCountryOnceByAlpha3()
{
List<Country> values = Country.values();

assertEquals(Locale.getISOCountries().length + 1, values.size());
assertTrue(values.contains(Country.FRANCE));
assertTrue(values.contains(Country.WORLD));
assertEquals(values.stream().map(Country::alpha3).sorted().toList(), values.stream().map(Country::alpha3).toList());
assertThrows(UnsupportedOperationException.class, () -> values.add(Country.FRANCE));
}

@Test
void testWorldHasItsOwnCodesAndName()
{
assertEquals("XX", Country.WORLD.alpha2());
assertEquals("XXX", Country.WORLD.alpha3());
assertEquals("World", Country.WORLD.displayName());
assertEquals("World", Country.WORLD.displayName(Locale.FRENCH));
assertSame(Country.WORLD, Country.ofAlpha3("XXX"));
assertSame(Country.WORLD, Country.ofCode("XX").orElseThrow());
}

@Test
void testJsonRoundTripIncludingWorld() throws Exception
{
ObjectMapper mapper = JsonMapper.builder().build();

assertEquals("\"XXX\"", mapper.writeValueAsString(Country.WORLD));
for (Country country : Country.values())
assertSame(country, mapper.readValue(mapper.writeValueAsString(country), Country.class));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,26 @@ void resolve_relativeUsage_scalesSingleNodeEmissionsByNodeCount() throws Excepti
assertEquals(3, k8sImpact.nodeCount());
}

/** ISO 3166 has no code for the world, Boavizta names it WOR. */
@Test
void resolve_worldLocation_requestsTheWorldAverage() throws Exception
{
BoaviztaClient client = mock(BoaviztaClient.class);
BoaviztaEvaluationResolver evalResolver = new BoaviztaEvaluationResolver(client);

when(client.getInstanceConfig(eq(BoaviztaServerProvider.aws), eq("c5a.4xlarge")))
.thenReturn(new BoaviztaInstanceConfigResponse(new BoaviztaInstanceConfigResponse.IntConfigItem(16), null, null, null, null, null));
when(client.getInstanceImpact(eq(true), anyInt(), anySet(), any(BoaviztaInstanceImpactRequest.class)))
.thenReturn(new BoaviztaImpactResponse(Map.of(), 0));

TestAsset asset = new TestAsset(K8S_TYPE, new TestServerProfile(ServerProvider.aws, "c5a.4xlarge", Country.WORLD, Lifetime.ofHours(1000), 1));
TimeRange range = new TimeRange(Instant.parse("2026-11-01T00:00:00Z"), Instant.parse("2026-11-01T01:00:00Z"), Duration.ofHours(1));
evalResolver.resolve(asset, new KubernetesActivityData(ActivityRegime.MODELED, Set.of("srv-1"), range, CPUUsage.relative(0.50), Map.of("srv-1", 1.0), Map.of()));

verify(client, atLeastOnce()).getInstanceImpact(eq(true), anyInt(), anySet(), argThat(request -> "WOR".equals(request.usage().usageLocation())));
verify(client, never()).getInstanceImpact(eq(true), anyInt(), anySet(), argThat(request -> !"WOR".equals(request.usage().usageLocation())));
}

private record TestServerProfile(
ServerProvider provider,
String instanceType,
Expand Down
Loading
Loading