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
Expand Up @@ -30,7 +30,8 @@ public enum Parameter {
USAGE_CONSTRAINTS("usage_constraints"),
KEY("key"),
OUTPUT_FORMAT("output_format"),
SHARE_IDENTIFIER("share_identifier");
SHARE_IDENTIFIER("share_identifier"),
ESTIMATED_SIZE_BYTES("estimated_size_bytes");

private final String value;

Expand All @@ -43,16 +44,24 @@ public String getStringInput(Execute input) {
return value == null ? null : value.toString();
}

// Null when the input is missing or is not a whole number.
public Long getLongInput(Execute input) {
Object value = input.getInputs().get(getValue());
if (value instanceof Number number && number.doubleValue() == number.longValue()) {
return number.longValue();
}
return null;
}

public Object getObjectInput(Execute input) {
return input.getInputs().get(getValue());
}

public List<String> getListInput(Execute input) {
Object value = input.getInputs().get(getValue());
if(value instanceof List<?> list) {
if (value instanceof List<?> list) {
return list.stream().map(String::valueOf).toList();
}
else {
} else {
return null;
}
}
Expand All @@ -63,6 +72,7 @@ public enum Type {
SUB_SETTING("sub-setting"),
;
private final String value;

Type(String value) {
this.value = value;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,12 @@ public String submit(DownloadRequest request) throws JsonProcessingException {
* @return the estimate, or empty when DAS could not give one
*/
private OptionalLong rejectIfTooLarge(DownloadRequest request) {
long estimatedBytes;
try {
estimatedBytes = restServices.estimateDownloadBytes(request);
} catch (Exception e) {
// Let it through, as the portal does when its own estimate fails. Blocking every
// download because DAS cannot estimate would be worse than one job running out of disk.
log.warn("Size estimate failed for uuid {}, submitting without the size check", request.uuid(), e);
return OptionalLong.empty();
OptionalLong estimate = estimateBytes(request);
if (estimate.isEmpty()) {
return estimate;
}

long estimatedBytes = estimate.getAsLong();
long maxBytes = sizeLimit.maxSize().toBytes();
if (estimatedBytes >= maxBytes) {
log.info("Rejected download for uuid {}: estimated {} bytes, limit {} bytes",
Expand All @@ -124,6 +120,30 @@ private OptionalLong rejectIfTooLarge(DownloadRequest request) {
return OptionalLong.of(estimatedBytes);
}

/**
* The estimated size of a download. Two sources, in this order:
* 1. The size carried in the request. The portal has already estimated it, so asking DAS
* again only makes the user wait.
* 2. A DAS estimate, only when the request carries no size.
*
* @return the estimate, or empty when there is none
*/
private OptionalLong estimateBytes(DownloadRequest request) {
Long fromRequest = request.estimatedSizeBytes();
if (fromRequest != null) {
return OptionalLong.of(fromRequest);
}

try {
return OptionalLong.of(restServices.estimateDownloadBytes(request));
} catch (Exception e) {
// Let it through, as the portal does when its own estimate fails. Blocking every
// download because DAS cannot estimate would be worse than one job running out of disk.
log.warn("Size estimate failed for uuid {}, submitting without the size check", request.uuid(), e);
return OptionalLong.empty();
}
}

/**
* The fair-share tag for a download: small only when it is estimated under the threshold.
* No estimate counts as large, so a download we know nothing about cannot take the slots
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,23 @@ public record DownloadRequest(
String fullMetadataLink,
String suggestedCitation,
List<String> usageConstraints,
String outputFormat
String outputFormat,
// Size the portal already estimated, null when the request did not carry one
Long estimatedSizeBytes
) {
public DownloadRequest {
// A missing input means no constraints to show
usageConstraints = usageConstraints == null ? List.of() : usageConstraints;
// A negative size is not a real estimate, treat it as missing
estimatedSizeBytes = estimatedSizeBytes != null && estimatedSizeBytes < 0 ? null : estimatedSizeBytes;
}

// A request that carries no estimated size
public DownloadRequest(String uuid, String key, String startDate, String endDate, Object multiPolygon,
String recipient, String collectionTitle, String fullMetadataLink,
String suggestedCitation, List<String> usageConstraints, String outputFormat) {
this(uuid, key, startDate, endDate, multiPolygon, recipient, collectionTitle, fullMetadataLink,
suggestedCitation, usageConstraints, outputFormat, null);
}

// True for the original NetCDF files list download
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,11 @@ public ResponseEntity<InlineResponse200> execute(
List<String> usageConstraints = DatasetDownloadEnums.Parameter.USAGE_CONSTRAINTS.getListInput(body);
String outputFormat = DatasetDownloadEnums.Parameter.OUTPUT_FORMAT.getStringInput(body);
Object multiPolygon = DatasetDownloadEnums.Parameter.MULTI_POLYGON.getObjectInput(body);
Long estimatedSizeBytes = DatasetDownloadEnums.Parameter.ESTIMATED_SIZE_BYTES.getLongInput(body);

DownloadRequest request = new DownloadRequest(uuid, key, startDate, endDate, multiPolygon,
recipient, collectionTitle, fullMetadataLink, suggestedCitation, usageConstraints,
outputFormat);
outputFormat, estimatedSizeBytes);

// The size limit and the per-user limit are applied here: a download that is too
// large, or a recipient already at their limit, is rejected outright, before
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ public class RestServices {
// Same field the portal reads to block a download that is too large.
private static final String ESTIMATED_OUTPUT_BYTES = "estimated_output_bytes";

// DAS gives no size estimate for Excel yet, so an Excel download is estimated as CSV.
private static final String EXCEL_FORMAT = "excel";
private static final String CSV_FORMAT = "csv";

// Submitted in place of a missing suggested citation, since AWS Batch rejects empty values.
static final String SUGGESTED_CITATION_NOT_AVAILABLE = "Suggested Citation not available";

Expand Down Expand Up @@ -92,11 +96,16 @@ public Map<String, String> buildDownloadParameters(DownloadRequest request) thro
* Estimate how many bytes a download will produce. Uses the same uuid and subset parameters
* as the cloud-optimised estimate, so a subset the portal has just estimated comes from the
* cache instead of calling DAS again.
* An Excel download uses the CSV estimate, the same as the portal does for now. Only the
* estimate changes, the download itself still asks for Excel.
*/
public long estimateDownloadBytes(DownloadRequest request) throws JsonProcessingException {
String estimateFormat = EXCEL_FORMAT.equalsIgnoreCase(request.outputFormat())
? CSV_FORMAT
: request.outputFormat();
Map<String, String> parameters = SubsetParametersUtils.buildSubsetParameters(
objectMapper, request.uuid(), request.key(), request.startDate(), request.endDate(),
request.multiPolygon(), request.outputFormat());
request.multiPolygon(), estimateFormat);

// No client of our own to keep alive, so heartbeats are ignored.
String estimateJson = dasService.estimateCloudOptimisedDownloadSize(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,39 @@ void aFailedEstimateStillSubmits() throws Exception {
verify(restServices).submitDownloadJob(eq(RECIPIENT_JOB_NAME), any(), any());
}

private DownloadRequest requestWithSize(Long estimatedSizeBytes) {
return new DownloadRequest("collection-id", "key.parquet", "2023-01-01", "2023-01-31",
"non-specified", RECIPIENT, "Test Collection",
"https://portal.example.test/details/collection-id", "Cite as", null, "excel",
estimatedSizeBytes);
}

@Test
void aSizeCarriedInTheRequestSkipsTheEstimate() throws Exception {
assertNotNull(service.submit(requestWithSize(DataSize.ofMegabytes(50).toBytes() - 1)));

verify(restServices, never()).estimateDownloadBytes(any());
assertEquals("small", submittedShare());
}

@Test
void aSizeCarriedInTheRequestAtTheLimitIsRejected() throws Exception {
assertThrows(DownloadSizeExceededException.class, () -> service.submit(requestWithSize(MAX_BYTES)));

verify(restServices, never()).estimateDownloadBytes(any());
verify(restServices, never()).submitDownloadJob(anyString(), any(), any());
}

@Test
void aNegativeSizeInTheRequestFallsBackToTheEstimate() throws Exception {
when(restServices.estimateDownloadBytes(any())).thenReturn(DataSize.ofMegabytes(50).toBytes());

service.submit(requestWithSize(-1L));

verify(restServices).estimateDownloadBytes(any());
assertEquals("large", submittedShare());
}

@Test
void theSizeLimitCanBeTurnedOff() throws Exception {
DownloadAdmissionService disabled = build(limits(true, 10), sizeLimit(false));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
Expand Down Expand Up @@ -102,6 +103,27 @@ public void testExecutePassesUsageConstraintsToAdmission() throws JsonProcessing
assertEquals(List.of("Credit CSIRO", "Use with care"), captor.getValue().usageConstraints());
}

@Test
public void testExecutePassesEstimatedSizeToAdmission() throws JsonProcessingException {
// JSON numbers arrive as Integer or Long, depending on the size
executeRequest.getInputs().put(DatasetDownloadEnums.Parameter.ESTIMATED_SIZE_BYTES.getValue(), 1048576);

restApi.execute(ProcessIdEnum.DOWNLOAD_DATASET.getValue(), executeRequest);

ArgumentCaptor<DownloadRequest> captor = ArgumentCaptor.forClass(DownloadRequest.class);
verify(downloadAdmissionService).submit(captor.capture());
assertEquals(1048576L, captor.getValue().estimatedSizeBytes());
}

@Test
public void testExecuteWithoutEstimatedSizePassesNull() throws JsonProcessingException {
restApi.execute(ProcessIdEnum.DOWNLOAD_DATASET.getValue(), executeRequest);

ArgumentCaptor<DownloadRequest> captor = ArgumentCaptor.forClass(DownloadRequest.class);
verify(downloadAdmissionService).submit(captor.capture());
assertNull(captor.getValue().estimatedSizeBytes());
}

@Test
public void testExecuteWithoutUsageConstraintsPassesEmptyList() throws JsonProcessingException {
restApi.execute(ProcessIdEnum.DOWNLOAD_DATASET.getValue(), executeRequest);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,47 @@ public void estimateDownloadBytesWithoutTheOutputSizeThrows() {
assertThrows(IllegalStateException.class, () -> services.estimateDownloadBytes(estimateRequest()));
}

// The output format the estimate sends to DAS for a download in the given format
@SuppressWarnings("unchecked")
private String estimateFormatFor(String outputFormat) throws JsonProcessingException {
DasService dasService = mock(DasService.class);
when(dasService.estimateCloudOptimisedDownloadSize(any(), anyMap(), any()))
.thenReturn("{\"estimated_output_bytes\":1024}");
RestServices services = new RestServices(batchClient, new ObjectMapper(), "test-job-definition", "test-job-queue");
ReflectionTestUtils.setField(services, "dasService", dasService);

services.estimateDownloadBytes(new DownloadRequest("test-uuid", "test.parquet", "2023-01-01", "2023-01-31",
"non-specified", "test@example.com", "Test Ocean Data Collection",
"https://portal.example.test/details/test-uuid", "Cite as", null, outputFormat));

ArgumentCaptor<Map<String, String>> captor = ArgumentCaptor.forClass(Map.class);
verify(dasService).estimateCloudOptimisedDownloadSize(eq("test-uuid"), captor.capture(), any());
return captor.getValue().get(DatasetDownloadEnums.Parameter.OUTPUT_FORMAT.getValue());
}

@Test
public void estimateDownloadBytesUsesTheCsvEstimateForExcel() throws JsonProcessingException {
// DAS gives no size for Excel, so ask for CSV, as the portal does
assertEquals("csv", estimateFormatFor("excel"));
}

@Test
public void estimateDownloadBytesKeepsOtherFormats() throws JsonProcessingException {
assertEquals("csv", estimateFormatFor("csv"));
assertEquals("netcdf", estimateFormatFor("netcdf"));
}

@Test
public void downloadParametersKeepExcel() throws JsonProcessingException {
// Only the estimate uses CSV, the download itself still asks for Excel
RestServices services = new RestServices(batchClient, new ObjectMapper(), "definition", "queue");
Map<String, String> parameters = services.buildDownloadParameters(new DownloadRequest("test-uuid",
"test.parquet", "2023-01-01", "2023-01-31", "non-specified", "test@example.com", "Title",
"https://example.com/metadata", "Cite as", null, "excel"));

assertEquals("excel", parameters.get(DatasetDownloadEnums.Parameter.OUTPUT_FORMAT.getValue()));
}

private Map<String, String> downloadParameters(List<String> usageConstraints) throws JsonProcessingException {
RestServices services = new RestServices(batchClient, new ObjectMapper(), "definition", "queue");
return services.buildDownloadParameters(new DownloadRequest("test-uuid", "test.zarr", "2023-01-01",
Expand Down
Loading