From c0ec98b43e3cf4c2fa3e6fcf4a371dd43d6f4af3 Mon Sep 17 00:00:00 2001 From: Simone Primarosa Date: Wed, 30 Sep 2026 04:05:16 +0200 Subject: [PATCH] feat(ec2): return spot price history for known instance types (#4698) * feat(ec2): return spot price history for known instance types * fix(ec2): address review feedback on spot price history pagination and platforms * style(ec2): fix import ordering and inline qualified class names --- .../test/Ec2DescribeSpotPriceHistoryTest.java | 253 +++++++++++++++++- docs/services/ec2.md | 3 + .../floci/services/ec2/Ec2QueryHandler.java | 68 ++++- .../floci/services/ec2/Ec2Service.java | 186 ++++++++++++- .../floci/services/ec2/model/SpotPrice.java | 23 ++ .../ec2/model/SpotPriceHistoryResult.java | 15 ++ ...scribeSpotPriceHistoryIntegrationTest.java | 83 ++++++ 7 files changed, 616 insertions(+), 15 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPrice.java create mode 100644 src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPriceHistoryResult.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeSpotPriceHistoryIntegrationTest.java diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSpotPriceHistoryTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSpotPriceHistoryTest.java index b7bd49f9a8..14d73a6809 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSpotPriceHistoryTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/Ec2DescribeSpotPriceHistoryTest.java @@ -2,11 +2,17 @@ package com.floci.test; import org.junit.jupiter.api.Test; import software.amazon.awssdk.services.ec2.Ec2Client; -import software.amazon.awssdk.services.ec2.model.Ec2Exception; import software.amazon.awssdk.services.ec2.model.DescribeSpotPriceHistoryRequest; +import software.amazon.awssdk.services.ec2.model.DescribeSpotPriceHistoryResponse; +import software.amazon.awssdk.services.ec2.model.Ec2Exception; +import software.amazon.awssdk.services.ec2.model.Filter; import software.amazon.awssdk.services.ec2.model.InstanceType; +import software.amazon.awssdk.services.ec2.model.SpotPrice; +import java.nio.charset.StandardCharsets; import java.time.Instant; +import java.util.Base64; +import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -14,22 +20,249 @@ import static org.junit.jupiter.api.Assertions.assertThrows; class Ec2DescribeSpotPriceHistoryTest { @Test - void describeSpotPriceHistoryReturnsEmptyHistoryWhenNoSnapshotIsConfigured() { + void describeSpotPriceHistoryReturnsEntriesForKnownInstanceTypesWithoutFilters() { try (Ec2Client ec2 = TestFixtures.ec2Client()) { - var response = ec2.describeSpotPriceHistory(DescribeSpotPriceHistoryRequest.builder() - .instanceTypes(InstanceType.M5_LARGE, InstanceType.fromValue("t4g.medium")) - .productDescriptions("Linux/UNIX") - .availabilityZone("us-east-1a") - .startTime(Instant.parse("2026-01-01T00:00:00Z")) - .endTime(Instant.parse("2026-01-02T00:00:00Z")) - .maxResults(100) - .build()); + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder().build()); + + assertThat(response.spotPriceHistory()).isNotEmpty(); + SpotPrice first = response.spotPriceHistory().get(0); + assertThat(first.instanceTypeAsString()).isNotBlank(); + assertThat(first.productDescriptionAsString()).isNotBlank(); + assertThat(first.spotPrice()).isNotBlank(); + assertThat(first.timestamp()).isNotNull(); + assertThat(first.availabilityZone()).isNotBlank(); + } + } + + @Test + void describeSpotPriceHistoryFiltersByInstanceTypeAvailabilityZoneAndProductDescription() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .instanceTypes(InstanceType.M5_LARGE) + .productDescriptions("Linux/UNIX") + .availabilityZone("us-east-1a") + .build()); + + assertThat(response.spotPriceHistory()).hasSize(1); + SpotPrice entry = response.spotPriceHistory().get(0); + assertThat(entry.instanceType()).isEqualTo(InstanceType.M5_LARGE); + assertThat(entry.productDescriptionAsString()).isEqualTo("Linux/UNIX"); + assertThat(entry.availabilityZone()).isEqualTo("us-east-1a"); + assertThat(Double.parseDouble(entry.spotPrice())).isPositive(); + } + } + + @Test + void describeSpotPriceHistoryFiltersUsingGenericFilters() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .filters( + Filter.builder().name("instance-type").values("t3.micro").build(), + Filter.builder().name("availability-zone").values("us-east-1b").build(), + Filter.builder().name("product-description").values("Linux/UNIX*").build() + ) + .build()); + + assertThat(response.spotPriceHistory()).isNotEmpty(); + for (SpotPrice entry : response.spotPriceHistory()) { + assertThat(entry.instanceTypeAsString()).isEqualTo("t3.micro"); + assertThat(entry.availabilityZone()).isEqualTo("us-east-1b"); + assertThat(entry.productDescriptionAsString()).startsWith("Linux/UNIX"); + } + } + } + + @Test + void describeSpotPriceHistoryReturnsEmptyForUnknownInstanceType() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .instanceTypes(InstanceType.fromValue("z99.custom")) + .build()); assertThat(response.spotPriceHistory()).isEmpty(); assertThat(response.nextToken()).isEmpty(); } } + @Test + void describeSpotPriceHistoryReturnsStableIdenticalPrices() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryRequest request = DescribeSpotPriceHistoryRequest.builder() + .instanceTypes(InstanceType.M5_LARGE) + .productDescriptions("Linux/UNIX") + .availabilityZone("us-east-1a") + .build(); + + DescribeSpotPriceHistoryResponse firstResponse = ec2.describeSpotPriceHistory(request); + DescribeSpotPriceHistoryResponse secondResponse = ec2.describeSpotPriceHistory(request); + + assertThat(firstResponse.spotPriceHistory()).hasSize(1); + assertThat(secondResponse.spotPriceHistory()).hasSize(1); + assertThat(firstResponse.spotPriceHistory().get(0).spotPrice()) + .isEqualTo(secondResponse.spotPriceHistory().get(0).spotPrice()); + } + } + + @Test + void describeSpotPriceHistoryPriceIsBelowOnDemandAndMonotonicWithCapacity() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .instanceTypes(InstanceType.T3_MICRO, InstanceType.T3_SMALL, InstanceType.M5_LARGE) + .productDescriptions("Linux/UNIX") + .availabilityZone("us-east-1a") + .build()); + + List items = response.spotPriceHistory(); + assertThat(items).hasSize(3); + + SpotPrice t3Micro = items.stream() + .filter(i -> i.instanceType() == InstanceType.T3_MICRO) + .findFirst().orElseThrow(); + SpotPrice t3Small = items.stream() + .filter(i -> i.instanceType() == InstanceType.T3_SMALL) + .findFirst().orElseThrow(); + SpotPrice m5Large = items.stream() + .filter(i -> i.instanceType() == InstanceType.M5_LARGE) + .findFirst().orElseThrow(); + + double t3Price = Double.parseDouble(t3Micro.spotPrice()); + double t3SmallPrice = Double.parseDouble(t3Small.spotPrice()); + double m5Price = Double.parseDouble(m5Large.spotPrice()); + + // Known on-demand prices for us-east-1: + // t3.micro = $0.0104, m5.large = $0.0960 + assertThat(t3Price).isLessThan(0.0104); + assertThat(m5Price).isLessThan(0.0960); + + // Larger instances cost more + assertThat(t3Price).isLessThan(t3SmallPrice); + assertThat(t3SmallPrice).isLessThan(m5Price); + } + } + + @Test + void describeSpotPriceHistorySupportsPagination() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse page1 = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .maxResults(2) + .build()); + + assertThat(page1.spotPriceHistory()).hasSize(2); + assertThat(page1.nextToken()).isNotBlank(); + + DescribeSpotPriceHistoryResponse page2 = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .maxResults(2) + .nextToken(page1.nextToken()) + .build()); + + assertThat(page2.spotPriceHistory()).hasSize(2); + assertThat(page1.spotPriceHistory()).doesNotContainAnyElementsOf(page2.spotPriceHistory()); + } + } + + @Test + void describeSpotPriceHistorySupportsContinuationWithNextTokenOnly() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse page1 = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .maxResults(2) + .build()); + + assertThat(page1.spotPriceHistory()).hasSize(2); + assertThat(page1.nextToken()).isNotBlank(); + + DescribeSpotPriceHistoryResponse continuation = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .nextToken(page1.nextToken()) + .build()); + + assertThat(continuation.spotPriceHistory()).isNotEmpty(); + assertThat(page1.spotPriceHistory()).doesNotContainAnyElementsOf(continuation.spotPriceHistory()); + } + } + + @Test + void describeSpotPriceHistoryReturnsPricesForWindowsPlatform() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .instanceTypes(InstanceType.M5_LARGE) + .productDescriptions("Windows") + .availabilityZone("us-east-1a") + .build()); + + assertThat(response.spotPriceHistory()).hasSize(1); + SpotPrice entry = response.spotPriceHistory().get(0); + assertThat(entry.instanceType()).isEqualTo(InstanceType.M5_LARGE); + assertThat(entry.productDescriptionAsString()).isEqualTo("Windows"); + assertThat(entry.availabilityZone()).isEqualTo("us-east-1a"); + assertThat(Double.parseDouble(entry.spotPrice())).isPositive(); + } + } + + @Test + void describeSpotPriceHistoryReturnsEmptyForFutureStartTime() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + DescribeSpotPriceHistoryResponse response = ec2.describeSpotPriceHistory( + DescribeSpotPriceHistoryRequest.builder() + .startTime(Instant.now().plusSeconds(86400)) + .build()); + + assertThat(response.spotPriceHistory()).isEmpty(); + assertThat(response.nextToken()).isEmpty(); + } + } + + @Test + void describeSpotPriceHistoryRejectsInvalidNextToken() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + String invalidToken = Base64.getEncoder().encodeToString( + "{\"offset\":-1}".getBytes(StandardCharsets.UTF_8)); + Ec2Exception exception = assertThrows(Ec2Exception.class, + () -> ec2.describeSpotPriceHistory(DescribeSpotPriceHistoryRequest.builder() + .nextToken(invalidToken) + .build())); + + assertThat(exception.statusCode()).isEqualTo(400); + assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + } + } + + @Test + void describeSpotPriceHistoryRejectsInvalidProductDescription() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + Ec2Exception exception = assertThrows(Ec2Exception.class, + () -> ec2.describeSpotPriceHistory(DescribeSpotPriceHistoryRequest.builder() + .productDescriptions("InvalidOperatingSystem") + .build())); + + assertThat(exception.statusCode()).isEqualTo(400); + assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + } + } + + @Test + void describeSpotPriceHistoryRejectsStartTimeAfterEndTime() { + try (Ec2Client ec2 = TestFixtures.ec2Client()) { + Instant now = Instant.now(); + Ec2Exception exception = assertThrows(Ec2Exception.class, + () -> ec2.describeSpotPriceHistory(DescribeSpotPriceHistoryRequest.builder() + .startTime(now.plusSeconds(3600)) + .endTime(now) + .build())); + + assertThat(exception.statusCode()).isEqualTo(400); + assertThat(exception.awsErrorDetails().errorCode()).isEqualTo("InvalidParameterValue"); + } + } + @Test void describeSpotPriceHistoryHonorsDryRun() { try (Ec2Client ec2 = TestFixtures.ec2Client()) { diff --git a/docs/services/ec2.md b/docs/services/ec2.md index 9194f387b0..c797481169 100644 --- a/docs/services/ec2.md +++ b/docs/services/ec2.md @@ -733,6 +733,9 @@ Validation matches AWS behavior: | RequestSpotInstances | Requests spot instances from a launch specification; returns the created spot instance requests. | | DescribeSpotInstanceRequests | Lists spot instance requests, optionally filtered by id. | | CancelSpotInstanceRequests | Cancels the named spot instance requests, returning each id with its new state. | +| DescribeSpotPriceHistory | Returns synthetic spot price history for known instance types across modeled availability zones. | + +Spot prices returned by `DescribeSpotPriceHistory` are synthetic and derived deterministically from instance type specifications: `((vcpu * 0.0016) + (memoryGiB * 0.0012)) * (1.0 + (azOffset * 0.03))`, formatted to six decimal places. They bear no relation to real AWS spot prices and are intended for testing cost-aware schedulers rather than spend estimation. Supported filters are `availability-zone`, `availability-zone-id`, `instance-type`, `product-description`, `spot-price`, and `timestamp`. Pagination is supported via `MaxResults` and `NextToken`. ### VPN Gateways diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java index 802bd3cc89..e6edf5ecac 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java @@ -19,6 +19,7 @@ import org.jboss.logging.Logger; import java.io.ByteArrayInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; +import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.util.*; @@ -351,6 +352,17 @@ public class Ec2QueryHandler { return value != null && !value.isBlank() ? value : p.getFirst(second); } + private List getListOrSingle(MultivaluedMap p, String prefix) { + List result = getList(p, prefix); + if (result.isEmpty()) { + String single = p.getFirst(prefix); + if (single != null && !single.isBlank()) { + result.add(single); + } + } + return result; + } + private int parseIntParam(MultivaluedMap p, String name, int defaultValue) { String val = p.getFirst(name); if (val == null || val.isEmpty()) return defaultValue; @@ -6070,14 +6082,62 @@ public class Ec2QueryHandler { * clients such as Karpenter to distinguish an empty result from an unsupported action.

*/ private Response handleDescribeSpotPriceHistory(MultivaluedMap p, String region) { + List instanceTypes = getListOrSingle(p, "InstanceType"); + List productDescriptions = getListOrSingle(p, "ProductDescription"); + String availabilityZone = p.getFirst("AvailabilityZone"); + if (availabilityZone == null) { + availabilityZone = p.getFirst("AvailabilityZone.1"); + } + String availabilityZoneId = p.getFirst("AvailabilityZoneId"); + if (availabilityZoneId == null) { + availabilityZoneId = p.getFirst("AvailabilityZoneId.1"); + } + Instant startTime = instantOrNull(p, "StartTime"); + Instant endTime = instantOrNull(p, "EndTime"); + Map> filters = getFilters(p); + String nextToken = p.getFirst("NextToken"); + + int maxResults = 0; + String maxResultsStr = p.getFirst("MaxResults"); + if (maxResultsStr != null && !maxResultsStr.isEmpty()) { + try { + maxResults = Integer.parseInt(maxResultsStr); + if (maxResults < 1) { + throw new AwsException("InvalidParameterValue", + "The parameter MaxResults must be greater than or equal to 1", 400); + } + } catch (NumberFormatException e) { + throw new AwsException("InvalidParameterValue", + "The specified value for MaxResults is not valid.", 400); + } + } + + service.validateSpotPriceHistory(productDescriptions, availabilityZone, availabilityZoneId, startTime, endTime, filters); checkDryRun(p); + + SpotPriceHistoryResult result = service.describeSpotPriceHistory(region, + instanceTypes, productDescriptions, availabilityZone, availabilityZoneId, + startTime, endTime, filters, maxResults, nextToken); + XmlBuilder xml = new XmlBuilder() .start("DescribeSpotPriceHistoryResponse", AwsNamespaces.EC2) .elem("requestId", UUID.randomUUID().toString()) - .elem("nextToken", "") - .start("spotPriceHistorySet") - .end("spotPriceHistorySet") - .end("DescribeSpotPriceHistoryResponse"); + .start("spotPriceHistorySet"); + for (SpotPrice sp : result.spotPrices()) { + xml.start("item") + .elem("instanceType", sp.instanceType()) + .elem("productDescription", sp.productDescription()) + .elem("spotPrice", sp.spotPrice()) + .elem("timestamp", ISO_FMT.format(sp.timestamp())) + .elem("availabilityZone", sp.availabilityZone()); + if (sp.availabilityZoneId() != null) { + xml.elem("availabilityZoneId", sp.availabilityZoneId()); + } + xml.end("item"); + } + xml.end("spotPriceHistorySet"); + xml.elem("nextToken", result.nextToken() != null ? result.nextToken() : ""); + xml.end("DescribeSpotPriceHistoryResponse"); return xmlResponse(xml.build()); } diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java index fa266716bf..1150c96c7b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java @@ -17,6 +17,7 @@ import io.github.hectorvent.floci.core.storage.AccountAwareStorageBackend; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.core.storage.StorageBackend; import io.github.hectorvent.floci.core.storage.StorageFactory; +import io.github.hectorvent.floci.services.ec2.Ec2InstanceTypeCatalog.CatalogInstanceType; import io.github.hectorvent.floci.services.ec2.model.Address; import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping; import io.github.hectorvent.floci.services.ec2.model.CapacityReservation; @@ -62,6 +63,8 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroup; import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule; import io.github.hectorvent.floci.services.ec2.model.Snapshot; import io.github.hectorvent.floci.services.ec2.model.SpotInstanceRequest; +import io.github.hectorvent.floci.services.ec2.model.SpotPrice; +import io.github.hectorvent.floci.services.ec2.model.SpotPriceHistoryResult; import io.github.hectorvent.floci.services.ec2.model.Subnet; import io.github.hectorvent.floci.services.ec2.model.Tag; import io.github.hectorvent.floci.services.ec2.model.TransitGateway; @@ -100,6 +103,7 @@ import java.time.Duration; import java.time.Instant; import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Base64; import java.util.Collection; @@ -199,6 +203,16 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { private static final Set EGRESS_ONLY_INTERNET_GATEWAY_FILTERS = Set.of( "attachment.state", "attachment.vpc-id", "egress-only-internet-gateway-id", "tag-key", "tag-value"); + private static final Set SPOT_PRICE_HISTORY_FILTERS = Set.of( + "availability-zone", "availability-zone-id", + "instance-type", "product-description", + "spot-price", "timestamp"); + private static final List MODELLED_PRODUCT_DESCRIPTIONS = List.of( + "Linux/UNIX", "Linux/UNIX (Amazon VPC)", + "SUSE Linux", "SUSE Linux (Amazon VPC)", + "Red Hat Enterprise Linux", "Red Hat Enterprise Linux (Amazon VPC)", + "Windows", "Windows (Amazon VPC)"); + private static final Set VALID_PRODUCT_DESCRIPTIONS = new HashSet<>(MODELLED_PRODUCT_DESCRIPTIONS); private final String defaultAccountId; private final jakarta.enterprise.inject.Instance requestContextInstance; @@ -9773,7 +9787,14 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { String json = new String(Base64.getDecoder().decode(token), StandardCharsets.UTF_8); int start = json.indexOf("\"offset\":") + 9; int end = json.indexOf('}', start); - return Integer.parseInt(json.substring(start, end)); + int offset = Integer.parseInt(json.substring(start, end)); + if (offset < 0) { + throw new AwsException("InvalidParameterValue", + "Invalid NextToken", 400); + } + return offset; + } catch (AwsException e) { + throw e; } catch (Exception e) { throw new AwsException("InvalidParameterValue", "Invalid NextToken", 400); @@ -9889,6 +9910,169 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider { return result; } + public void validateSpotPriceHistory(List productDescriptions, + String availabilityZone, + String availabilityZoneId, + Instant startTime, + Instant endTime, + Map> filters) { + if (filters != null && !filters.isEmpty()) { + requireSupportedFilters(filters, SPOT_PRICE_HISTORY_FILTERS); + } + if (productDescriptions != null) { + for (String desc : productDescriptions) { + if (!VALID_PRODUCT_DESCRIPTIONS.contains(desc)) { + throw new AwsException("InvalidParameterValue", + "The parameter ProductDescription is not valid", 400); + } + } + } + if (availabilityZone != null && availabilityZoneId != null) { + throw new AwsException("InvalidParameterCombination", + "The parameter AvailabilityZone cannot be used with the parameter AvailabilityZoneId", 400); + } + if (startTime != null && endTime != null && startTime.isAfter(endTime)) { + throw new AwsException("InvalidParameterValue", + "StartTime must be before EndTime", 400); + } + } + + /** + * Synthesizes spot price history for known instance types across modeled availability zones. + * Prices are synthetic and derived deterministically from instance type vCPU and memory. + * They bear no relation to real AWS spot prices. + */ + public SpotPriceHistoryResult describeSpotPriceHistory(String region, + List instanceTypes, + List productDescriptions, + String availabilityZone, + String availabilityZoneId, + Instant startTime, + Instant endTime, + Map> filters, + int maxResults, + String nextToken) { + ensureDefaultResources(region); + validateSpotPriceHistory(productDescriptions, availabilityZone, availabilityZoneId, startTime, endTime, filters); + + Instant now = Instant.now(); + if (startTime != null && startTime.isAfter(now)) { + return new SpotPriceHistoryResult(List.of(), null); + } + + Instant effectiveTimestamp = startTime != null + ? startTime + : (endTime != null ? endTime : now.truncatedTo(ChronoUnit.HOURS)); + + if (endTime != null && effectiveTimestamp.isAfter(endTime)) { + return new SpotPriceHistoryResult(List.of(), null); + } + + List> zones = describeAvailabilityZones(region); + if (availabilityZone != null) { + zones = zones.stream() + .filter(z -> availabilityZone.equals(z.get("zoneName"))) + .toList(); + } + if (availabilityZoneId != null) { + zones = zones.stream() + .filter(z -> availabilityZoneId.equals(z.get("zoneId"))) + .toList(); + } + if (filters != null && filters.containsKey("availability-zone")) { + List azFilter = filters.get("availability-zone"); + zones = zones.stream() + .filter(z -> matchesValue(z.get("zoneName"), azFilter)) + .toList(); + } + if (filters != null && filters.containsKey("availability-zone-id")) { + List azIdFilter = filters.get("availability-zone-id"); + zones = zones.stream() + .filter(z -> matchesValue(z.get("zoneId"), azIdFilter)) + .toList(); + } + + List catalogTypes; + if (instanceTypes != null && !instanceTypes.isEmpty()) { + Set distinctTypes = new LinkedHashSet<>(instanceTypes); + catalogTypes = distinctTypes.stream() + .map(instanceTypeCatalog::find) + .flatMap(Optional::stream) + .filter(t -> t.supportedUsageClasses.contains("spot")) + .toList(); + } else { + catalogTypes = instanceTypeCatalog.instanceTypes().stream() + .filter(t -> t.supportedUsageClasses.contains("spot")) + .toList(); + } + if (filters != null && filters.containsKey("instance-type")) { + List itFilter = filters.get("instance-type"); + catalogTypes = catalogTypes.stream() + .filter(t -> matchesValue(t.instanceType, itFilter)) + .toList(); + } + + List targetProductDescs = MODELLED_PRODUCT_DESCRIPTIONS; + if (productDescriptions != null && !productDescriptions.isEmpty()) { + Set requested = new HashSet<>(productDescriptions); + targetProductDescs = targetProductDescs.stream() + .filter(requested::contains) + .toList(); + } + if (filters != null && filters.containsKey("product-description")) { + List pdFilter = filters.get("product-description"); + targetProductDescs = targetProductDescs.stream() + .filter(pd -> matchesValue(pd, pdFilter)) + .toList(); + } + + List priceFilter = filters != null ? filters.get("spot-price") : null; + List timestampFilter = filters != null ? filters.get("timestamp") : null; + String formattedTimestamp = ISO_FMT.format(effectiveTimestamp); + + if (timestampFilter != null && !matchesValue(formattedTimestamp, timestampFilter)) { + return new SpotPriceHistoryResult(List.of(), null); + } + + List allEntries = new ArrayList<>(); + for (CatalogInstanceType type : catalogTypes) { + for (Map zone : zones) { + String zoneName = zone.get("zoneName"); + String zoneId = zone.get("zoneId"); + int zoneOffset = Math.max(0, zoneName.charAt(zoneName.length() - 1) - 'a'); + double multiplier = 1.0 + (zoneOffset * 0.03); + double priceVal = ((type.vcpu * 0.0016) + ((type.memoryMib / 1024.0) * 0.0012)) * multiplier; + String formattedPrice = String.format(Locale.ROOT, "%.6f", priceVal); + + if (priceFilter != null && !matchesValue(formattedPrice, priceFilter)) { + continue; + } + + for (String pd : targetProductDescs) { + allEntries.add(new SpotPrice(zoneName, zoneId, type.instanceType, pd, formattedPrice, effectiveTimestamp)); + } + } + } + + allEntries.sort(Comparator + .comparing(SpotPrice::instanceType) + .thenComparing(SpotPrice::availabilityZone) + .thenComparing(SpotPrice::productDescription)); + + if (maxResults > 0 || (nextToken != null && !nextToken.isEmpty())) { + int offset = decodeToken(nextToken); + int total = allEntries.size(); + int fromIndex = Math.min(offset, total); + int pageSize = maxResults > 0 ? maxResults : 1000; + int toIndex = (int) Math.min((long) fromIndex + pageSize, total); + List paged = allEntries.subList(fromIndex, toIndex); + String newNextToken = toIndex < total ? encodeToken(toIndex) : null; + return new SpotPriceHistoryResult(paged, newNextToken); + } + + return new SpotPriceHistoryResult(allEntries, null); + } + // ─── Resource Explorer 2 ─────────────────────────────────────────────────── /** diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPrice.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPrice.java new file mode 100644 index 0000000000..ed35558daf --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPrice.java @@ -0,0 +1,23 @@ +package io.github.hectorvent.floci.services.ec2.model; + +import java.time.Instant; + +/** + * A spot price history entry. + * + * @param availabilityZone the availability zone name + * @param availabilityZoneId the availability zone id + * @param instanceType the instance type + * @param productDescription the product description + * @param spotPrice the synthetic spot price formatted to six decimal places + * @param timestamp the effective timestamp + * @see AWS EC2 SpotPrice + */ +public record SpotPrice( + String availabilityZone, + String availabilityZoneId, + String instanceType, + String productDescription, + String spotPrice, + Instant timestamp +) {} diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPriceHistoryResult.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPriceHistoryResult.java new file mode 100644 index 0000000000..2139f42f43 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/SpotPriceHistoryResult.java @@ -0,0 +1,15 @@ +package io.github.hectorvent.floci.services.ec2.model; + +import java.util.List; + +/** + * Result of a paginated DescribeSpotPriceHistory call. + * + * @param spotPrices the spot prices for this page + * @param nextToken token for the next page, or null when the page is the last + * @see AWS EC2 DescribeSpotPriceHistory + */ +public record SpotPriceHistoryResult( + List spotPrices, + String nextToken +) {} diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeSpotPriceHistoryIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeSpotPriceHistoryIntegrationTest.java new file mode 100644 index 0000000000..b8d608145f --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2DescribeSpotPriceHistoryIntegrationTest.java @@ -0,0 +1,83 @@ +package io.github.hectorvent.floci.services.ec2; + +import io.quarkus.test.junit.QuarkusTest; +import io.restassured.response.ValidatableResponse; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; + +import static io.restassured.RestAssured.given; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.not; + +@QuarkusTest +class Ec2DescribeSpotPriceHistoryIntegrationTest { + + private static final String AUTH_HEADER = + "AWS4-HMAC-SHA256 Credential=test/20260908/us-east-1/ec2/aws4_request"; + + private static ValidatableResponse describeSpotPriceHistory(String... params) { + RequestSpecification request = given() + .formParam("Action", "DescribeSpotPriceHistory") + .header("Authorization", AUTH_HEADER); + for (int i = 0; i < params.length; i += 2) { + request.formParam(params[i], params[i + 1]); + } + return request.when().post("/").then(); + } + + @Test + void anUnknownFilterNameIsRefused() { + describeSpotPriceHistory("Filter.1.Name", "not-a-filter", "Filter.1.Value.1", "anything") + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("not-a-filter")); + } + + @Test + void theDocumentedFilterNamesAreAccepted() { + for (String name : new String[]{"availability-zone", "availability-zone-id", + "instance-type", "product-description", "spot-price", "timestamp"}) { + describeSpotPriceHistory("Filter.1.Name", name, "Filter.1.Value.1", "whatever") + .statusCode(200); + } + } + + @Test + void invalidProductDescriptionIsRefused() { + describeSpotPriceHistory("ProductDescription.1", "InvalidPlatform") + .statusCode(400) + .body(containsString("InvalidParameterValue")) + .body(containsString("ProductDescription")); + } + + @Test + void conflictingAvailabilityZoneAndIdIsRefused() { + describeSpotPriceHistory("AvailabilityZone", "us-east-1a", "AvailabilityZoneId", "use1-az1") + .statusCode(400) + .body(containsString("InvalidParameterCombination")); + } + + @Test + void startTimeAfterEndTimeIsRefused() { + describeSpotPriceHistory("StartTime", "2026-02-01T00:00:00Z", "EndTime", "2026-01-01T00:00:00Z") + .statusCode(400) + .body(containsString("InvalidParameterValue")); + } + + @Test + void returnsSpotPricesForKnownInstanceType() { + describeSpotPriceHistory("InstanceType.1", "t3.micro", "AvailabilityZone", "us-east-1a") + .statusCode(200) + .body(containsString("t3.micro")) + .body(containsString("us-east-1a")) + .body(containsString("Linux/UNIX")) + .body(containsString("0.004400")); + } + + @Test + void unknownInstanceTypeReturnsEmptySet() { + describeSpotPriceHistory("InstanceType.1", "nonexistent.type") + .statusCode(200) + .body(not(containsString(""))); + } +}