fix(s3): paginate multipart upload listings (#6981)

* fix(s3): paginate multipart upload listings

Preserve multipart pagination after an upload is aborted or completed. Share listing grouping and limit parsing, and cover marker removal in integration and storage tests.

Closes #6917

* fix(s3): bound multipart marker history

Cap retained marker positions and recover initiation ordering from opaque upload IDs after eviction. Cover history growth and newly initiated uploads after the marked key is drained.
This commit is contained in:
Rashen Anupama authored and GitHub committed 2026-10-30 08:01:13 -04:00
1 parent 382218204b
commit 6e9ac904c8
4 files changed
+445 -49

No files matched your search

@@ -609,7 +609,7 @@ public class S3Controller {
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
if (hasQueryParam(uriInfo, "uploads")) {
s3Service.authorizeBucketRead(bucket, "s3:ListBucketMultipartUploads", authorization);
return handleListMultipartUploads(bucket);
return handleListMultipartUploads(bucket, uriInfo);
}
if (hasQueryParam(uriInfo, "notification")) {
s3Service.authorizeBucketRead(bucket, "s3:GetBucketNotification", authorization);
@@ -2010,15 +2010,43 @@ public class S3Controller {
return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build();
}
private Response handleListMultipartUploads(String bucket) {
List<MultipartUpload> uploads = s3Service.listMultipartUploads(bucket);
private Response handleListMultipartUploads(String bucket, UriInfo uriInfo) {
MultivaluedMap<String, String> params = uriInfo.getQueryParameters();
String prefix = params.getFirst("prefix");
String delimiter = params.getFirst("delimiter");
String keyMarker = params.getFirst("key-marker");
String uploadIdMarker = params.getFirst("upload-id-marker");
String encodingType = params.getFirst("encoding-type");
String maxUploads = params.getFirst("max-uploads");
int max = resolveMaxUploads(maxUploads);
S3Service.ListMultipartUploadsResult result =
s3Service.listMultipartUploads(bucket, prefix, delimiter, keyMarker, uploadIdMarker, max);
XmlBuilder xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("ListMultipartUploadsResult", AwsNamespaces.S3)
.elem("Bucket", bucket);
for (MultipartUpload upload : uploads) {
.elem("Bucket", bucket)
.elem("KeyMarker", maybeEncode(keyMarker == null ? "" : keyMarker, encodingType))
.elem("UploadIdMarker", uploadIdMarker == null ? "" : uploadIdMarker)
.elem("Prefix", maybeEncode(prefix, encodingType))
.elem("Delimiter", maybeEncode(delimiter, encodingType))
.elem("MaxUploads", max)
.elem("IsTruncated", result.isTruncated());
if (encodingType != null) {
xml.elem("EncodingType", encodingType);
}
if (result.isTruncated()) {
xml.elem("NextKeyMarker", maybeEncode(result.nextKeyMarker(), encodingType))
.elem("NextUploadIdMarker", result.nextUploadIdMarker());
}
for (S3Service.MultipartListingEntry entry : result.entries()) {
MultipartUpload upload = entry.upload();
if (upload == null) {
xml.start("CommonPrefixes").elem("Prefix", maybeEncode(entry.key(), encodingType))
.end("CommonPrefixes");
continue;
}
xml.start("Upload")
.elem("Key", upload.getKey())
.elem("Key", maybeEncode(upload.getKey(), encodingType))
.elem("UploadId", upload.getUploadId())
.elem("Initiated", ISO_FORMAT.format(upload.getInitiated()))
.end("Upload");
@@ -2027,6 +2055,11 @@ public class S3Controller {
return Response.ok(xml.build()).build();
}
private static int resolveMaxUploads(String value) {
return resolveListingLimit(value, "max-uploads", 1000,
"Argument max-uploads must be a non-negative integer");
}
private record CompletedPart(int partNumber, String eTag, S3Checksum checksum) {}
private List<CompletedPart> parseCompleteMultipartBody(String xml) {
@@ -4430,18 +4463,22 @@ public class S3Controller {
* a missing parameter as 1000. Zero is a valid request for an empty page. Anything else,
* negative, non-numeric or overflowing, is rejected with the same InvalidArgument response.
*/
private static int resolveMaxKeys(String maxKeys) {
if (maxKeys == null) {
private static int resolveMaxKeys(String value) {
return resolveListingLimit(value, "maxKeys", Integer.MAX_VALUE,
"Argument maxKeys must be an integer between 0 and 2147483647");
}
private static int resolveListingLimit(String value, String argumentName, int cap, String message) {
if (value == null) {
return 1000;
}
if (maxKeys.matches("\\d{1,10}") && Long.parseLong(maxKeys) <= Integer.MAX_VALUE) {
return Integer.parseInt(maxKeys);
if (value.matches("\\d{1,10}") && Long.parseLong(value) <= Integer.MAX_VALUE) {
return Math.min(cap, Integer.parseInt(value));
}
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("ArgumentName", "maxKeys");
detail.put("ArgumentValue", maxKeys);
throw new AwsException("InvalidArgument",
"Argument maxKeys must be an integer between 0 and 2147483647", 400, detail);
detail.put("ArgumentName", argumentName);
detail.put("ArgumentValue", value);
throw new AwsException("InvalidArgument", message, 400, detail);
}
private Response handlePutBucketWebsite(String bucket, byte[] body) {
@@ -244,6 +244,16 @@ public class S3Service implements Resettable, ResourceProvider {
private static final String INCOMING_BODIES = ".incoming";
// Upload ID to part bytes, keyed by each part's storage ID.
private final ConcurrentHashMap<String, Map<String, byte[]>> memoryMultipartStore = new ConcurrentHashMap<>();
private record MultipartPosition(String bucket, String key, String ownerAccountId, Instant initiated) {}
private static final int REMOVED_MULTIPART_POSITION_LIMIT = 1000;
private final Map<String, MultipartPosition> removedMultipartPositions = Collections.synchronizedMap(
new LinkedHashMap<>(64, 0.75f, true) {
@Override
protected boolean removeEldestEntry(Map.Entry<String, MultipartPosition> eldest) {
return size() > REMOVED_MULTIPART_POSITION_LIMIT;
}
});
private final ConcurrentHashMap<String, MultipartUpload> multipartUploads = new ConcurrentHashMap<>();
// Account-level (S3 Control) Block Public Access config, one entry per AWS account.
// Distinct from the bucket-level configuration held on each Bucket. Block Public Access is a
@@ -422,6 +432,7 @@ public class S3Service implements Resettable, ResourceProvider {
memoryAnnotationStore.clear();
memoryMultipartStore.clear();
multipartUploads.clear();
removedMultipartPositions.clear();
if (!inMemory) {
// The reset above erases the annotation metadata through storageFactory.clearAll(),
// so detached .s3ann payload files become unreachable: sweep the annotation payload
@@ -2572,23 +2583,9 @@ public class S3Service implements Resettable, ResourceProvider {
List<String> commonPrefixes = List.of();
if (delimiter != null && !delimiter.isEmpty()) {
Set<String> prefixSet = new LinkedHashSet<>();
List<S3Object> directObjects = new ArrayList<>();
for (S3Object obj : allObjects) {
String remainder = obj.getKey().substring(prefix != null ? prefix.length() : 0);
int delimIdx = remainder.indexOf(delimiter);
if (delimIdx >= 0) {
String cp = (prefix != null ? prefix : "") + remainder.substring(0, delimIdx + delimiter.length());
prefixSet.add(cp);
} else {
directObjects.add(obj);
}
}
allObjects = directObjects;
commonPrefixes = new ArrayList<>(prefixSet);
Collections.sort(commonPrefixes);
DelimiterGroups<S3Object> groups = groupByDelimiter(allObjects, prefix, delimiter, S3Object::getKey);
allObjects = groups.direct();
commonPrefixes = groups.commonPrefixes();
}
allObjects.sort(Comparator.comparing(S3Object::getKey));
@@ -2646,6 +2643,27 @@ public class S3Service implements Resettable, ResourceProvider {
return new ListObjectsResult(allObjects, commonPrefixes, isTruncated, nextContinuationToken);
}
private record DelimiterGroups<T>(List<T> direct, List<String> commonPrefixes) {}
private static <T> DelimiterGroups<T> groupByDelimiter(List<T> items, String prefix, String delimiter,
Function<T, String> keyExtractor) {
List<T> direct = new ArrayList<>();
Set<String> prefixes = new LinkedHashSet<>();
for (T item : items) {
String key = keyExtractor.apply(item);
int index = delimiter == null || delimiter.isEmpty() ? -1
: key.indexOf(delimiter, prefix == null ? 0 : prefix.length());
if (index < 0) {
direct.add(item);
} else {
prefixes.add(key.substring(0, index + delimiter.length()));
}
}
List<String> commonPrefixes = new ArrayList<>(prefixes);
Collections.sort(commonPrefixes);
return new DelimiterGroups<>(direct, commonPrefixes);
}
public S3Object copyObject(String sourceBucket, String sourceKey,
String destBucket, String destKey) {
return copyObject(sourceBucket, sourceKey, destBucket, destKey, new CopyObjectOptions());
@@ -3089,23 +3107,9 @@ public class S3Service implements Resettable, ResourceProvider {
List<String> commonPrefixes = List.of();
if (delimiter != null && !delimiter.isEmpty()) {
Set<String> prefixSet = new LinkedHashSet<>();
List<S3Object> directVersions = new ArrayList<>();
for (S3Object obj : versions) {
String remainder = obj.getKey().substring(prefix != null ? prefix.length() : 0);
int delimIdx = remainder.indexOf(delimiter);
if (delimIdx >= 0) {
String cp = (prefix != null ? prefix : "") + remainder.substring(0, delimIdx + delimiter.length());
prefixSet.add(cp);
} else {
directVersions.add(obj);
}
}
versions = directVersions;
commonPrefixes = new ArrayList<>(prefixSet);
Collections.sort(commonPrefixes);
DelimiterGroups<S3Object> groups = groupByDelimiter(versions, prefix, delimiter, S3Object::getKey);
versions = groups.direct();
commonPrefixes = groups.commonPrefixes();
}
// Sort by key, then newest first
@@ -4632,6 +4636,7 @@ public class S3Service implements Resettable, ResourceProvider {
SseCustomerKey customerKey = validateSseCustomerKey(sseCustomerAlgorithm, sseCustomerKey, sseCustomerKeyMd5);
rejectConflictingServerSideEncryption(normalizedServerSideEncryption, customerKey);
MultipartUpload upload = new MultipartUpload(bucket, key, contentType);
upload.setUploadId(orderedMultipartUploadId(upload.getInitiated(), upload.getUploadId()));
upload.setOwnerAccountId(getBucketOwnerAccountId(bucket));
upload.setInitiatorAccountId(ownerId());
if (metadata != null) {
@@ -5290,6 +5295,89 @@ public class S3Service implements Resettable, ResourceProvider {
.toList();
}
public record MultipartListingEntry(String key, MultipartUpload upload) {}
public record ListMultipartUploadsResult(List<MultipartListingEntry> entries, boolean isTruncated,
String nextKeyMarker, String nextUploadIdMarker) {}
public ListMultipartUploadsResult listMultipartUploads(String bucket, String prefix, String delimiter,
String keyMarker, String uploadIdMarker, int max) {
List<MultipartUpload> uploads = listMultipartUploads(bucket).stream()
.filter(upload -> prefix == null || upload.getKey().startsWith(prefix)).toList();
DelimiterGroups<MultipartUpload> groups = groupByDelimiter(uploads, prefix, delimiter, MultipartUpload::getKey);
List<MultipartListingEntry> entries = new ArrayList<>();
groups.direct().forEach(upload -> entries.add(new MultipartListingEntry(upload.getKey(), upload)));
groups.commonPrefixes().forEach(key -> entries.add(new MultipartListingEntry(key, null)));
Comparator<MultipartListingEntry> order = Comparator
.comparing(MultipartListingEntry::key, S3Service::compareMultipartKeys)
.thenComparing(entry -> entry.upload() == null ? Instant.MIN : entry.upload().getInitiated())
.thenComparing(entry -> entry.upload() == null ? "" : entry.upload().getUploadId());
entries.sort(order);
MultipartListingEntry markedUpload = entries.stream()
.filter(entry -> entry.upload() != null && entry.key().equals(keyMarker)
&& entry.upload().getUploadId().equals(uploadIdMarker))
.findFirst().orElse(null);
MultipartPosition removedMarker = uploadIdMarker == null ? null : removedMultipartPositions.get(uploadIdMarker);
if (removedMarker != null && (!removedMarker.bucket().equals(bucket)
|| !removedMarker.key().equals(keyMarker)
|| !Objects.equals(removedMarker.ownerAccountId(), getBucketOwnerAccountId(bucket)))) {
removedMarker = null;
}
Instant markerInitiated = markedUpload != null ? markedUpload.upload().getInitiated()
: removedMarker != null ? removedMarker.initiated() : multipartMarkerInitiated(uploadIdMarker);
List<MultipartListingEntry> remaining = entries.stream().filter(entry -> {
if (keyMarker == null) {
return true;
}
int comparison = compareMultipartKeys(entry.key(), keyMarker);
return comparison > 0 || (comparison == 0 && uploadIdMarker != null && entry.upload() != null
&& (markerInitiated != null
? entry.upload().getInitiated().isAfter(markerInitiated)
|| (entry.upload().getInitiated().equals(markerInitiated)
&& entry.upload().getUploadId().compareTo(uploadIdMarker) > 0)
: entry.upload().getUploadId().compareTo(uploadIdMarker) > 0));
}).toList();
boolean truncated = max > 0 && remaining.size() > max;
List<MultipartListingEntry> page = remaining.subList(0, Math.min(max, remaining.size()));
MultipartListingEntry last = truncated ? page.getLast() : null;
return new ListMultipartUploadsResult(page, truncated, last == null ? null : last.key(),
last == null ? null : last.upload() == null ? "" : last.upload().getUploadId());
}
// UUIDv8 custom fields retain the exact initiation time without changing the opaque UUID wire shape.
// This lets pagination survive history eviction. The remaining 54 bits are random.
private static String orderedMultipartUploadId(Instant initiated, String randomId) {
int subMillisecondNanos = initiated.getNano() % 1_000_000;
long most = (initiated.toEpochMilli() << 16) | 0x8000L | (subMillisecondNanos >>> 8);
long least = 0x8000_0000_0000_0000L | ((long) (subMillisecondNanos & 0xff) << 54)
| (UUID.fromString(randomId).getLeastSignificantBits() & 0x003f_ffff_ffff_ffffL);
return new UUID(most, least).toString();
}
private static Instant multipartMarkerInitiated(String uploadId) {
if (uploadId == null) {
return null;
}
try {
UUID id = UUID.fromString(uploadId);
if (id.version() != 8 || id.variant() != 2) {
return null;
}
int subMillisecondNanos = (int) (((id.getMostSignificantBits() & 0xfff) << 8)
| ((id.getLeastSignificantBits() >>> 54) & 0xff));
if (subMillisecondNanos >= 1_000_000) {
return null;
}
return Instant.ofEpochMilli(id.getMostSignificantBits() >>> 16).plusNanos(subMillisecondNanos);
} catch (IllegalArgumentException ignored) {
return null;
}
}
private static int compareMultipartKeys(String left, String right) {
return Arrays.compareUnsigned(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8));
}
public MultipartUpload listParts(String bucket, String key, String uploadId) {
return getMultipartUpload(bucket, key, uploadId);
}
@@ -7159,7 +7247,20 @@ public class S3Service implements Resettable, ResourceProvider {
}
private void cleanupMultipart(String uploadId) {
multipartUploads.remove(uploadId);
MultipartUpload removed = multipartUploads.remove(uploadId);
if (removed != null) {
MultipartPosition position = new MultipartPosition(removed.getBucket(), removed.getKey(),
removed.getOwnerAccountId(), removed.getInitiated());
removedMultipartPositions.put(uploadId, position);
boolean hasRemaining = multipartUploads.values().stream().anyMatch(upload ->
upload.getBucket().equals(position.bucket()) && upload.getKey().equals(position.key())
&& Objects.equals(upload.getOwnerAccountId(), position.ownerAccountId()));
if (!hasRemaining) {
removedMultipartPositions.values().removeIf(previous -> previous.bucket().equals(position.bucket())
&& previous.key().equals(position.key())
&& Objects.equals(previous.ownerAccountId(), position.ownerAccountId()));
}
}
if (inMemory) {
memoryMultipartStore.remove(uploadId);
} else {