mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(s3): apply lifecycle expiration rules (#5158)
A bucket's lifecycle configuration was stored and returned but never evaluated. A background sweep now applies its expiration actions: - Expiration (Days, Date) deletes the current version of a matching object, or adds a delete marker in a versioning-enabled bucket. Day counts run from the last-modified time and round up to the next midnight UTC, as on S3. - ExpiredObjectDeleteMarker, and a Days or Date expiration once the marker is old enough, remove a delete marker with no other versions. - NoncurrentVersionExpiration (NoncurrentDays, NewerNoncurrentVersions) permanently deletes noncurrent versions, counting from when the next newer version was written. - AbortIncompleteMultipartUpload (DaysAfterInitiation) aborts uploads under a prefix-only filter. Filters are Prefix, Tag, ObjectSizeGreaterThan, ObjectSizeLessThan, an And of them, or the older rule-level Prefix. Disabled rules are skipped, versions under Object Lock retention or a legal hold are never deleted, and each bucket is swept in its owning account. Lifecycle deletions are notified as s3:LifecycleExpiration:* rather than s3:ObjectRemoved:*, with S3 itself as the requester, and their EventBridge reason is "Lifecycle Expiration". A rule S3 would have refused on put, such as Days 0, a size bound that is not a number or a Tag without a Value, is skipped as a whole, so a bad value never widens what a rule deletes. A body that is not one well-formed LifecycleConfiguration document has no rules. Each key is planned from one pass over its account's objects, then read again by its known store keys and applied under the bucket monitor. Lifecycle configuration changes and tagging now change under that monitor too, and a multipart upload is aborted only while its bucket and the rules are still the ones the sweep started on. Versions written in the same millisecond keep the order they were written in, for ListObjectVersions as well as for lifecycle. PutObject, GetObject and HeadObject on a current version that an Expiration rule matches return x-amz-expiration with the expiry date and the URL-encoded rule id. The sweep runs every 60 seconds by default, configured with floci.services.s3.lifecycle-sweep-enabled and floci.services.s3.lifecycle-sweep-interval-seconds. Transition actions are still not applied. Closes #5137
This commit is contained in:
1 parent
fea7d7b0b1
commit
cbd2f61dc4
18 files changed
+1846
-33
No files matched your search
@@ -201,6 +201,34 @@ class XmlParserTest {
|
||||
assertNull(XmlParser.extractElementTree(null, "Target"));
|
||||
}
|
||||
|
||||
// --- parseDocumentElementTree: the whole document or nothing ---
|
||||
|
||||
@Test
|
||||
void parseDocumentElementTreeReturnsTheDocumentElement() {
|
||||
XmlParser.XmlElement root = XmlParser.parseDocumentElementTree("""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Root xmlns="urn:test"><Item><Name>a</Name></Item></Root>
|
||||
<!-- a trailing comment is well-formed -->
|
||||
""");
|
||||
|
||||
assertEquals("Root", root.name());
|
||||
assertEquals("a", root.child("Item").child("Name").text());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parseDocumentElementTreeRejectsMalformedContentAfterTheDocumentElement() {
|
||||
// extractElementTree stops at the end of the element it found; this keeps reading.
|
||||
String trailingElement = "<Root><Item>a</Item></Root><Item>b</Item>";
|
||||
String trailingText = "<Root><Item>a</Item></Root>junk";
|
||||
|
||||
assertNotNull(XmlParser.extractElementTree(trailingElement, "Root"));
|
||||
assertNull(XmlParser.parseDocumentElementTree(trailingElement));
|
||||
assertNull(XmlParser.parseDocumentElementTree(trailingText));
|
||||
assertNull(XmlParser.parseDocumentElementTree("<Root><Item></Root>"));
|
||||
assertNull(XmlParser.parseDocumentElementTree(""));
|
||||
assertNull(XmlParser.parseDocumentElementTree(null));
|
||||
}
|
||||
|
||||
// --- extractDeleteObjectEntries: batch delete Key/VersionId pairing ---
|
||||
|
||||
@Test
|
||||
|
||||
+53
@@ -2,6 +2,7 @@ package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
@@ -22,6 +23,9 @@ class S3EventBridgeIntegrationTest {
|
||||
private static String ruleArn;
|
||||
private static String queueUrl;
|
||||
|
||||
@Inject
|
||||
S3LifecycleSweeper lifecycleSweeper;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
@@ -317,6 +321,55 @@ class S3EventBridgeIntegrationTest {
|
||||
containsString("\"deletion-type\":\"Delete Marker Created\"")));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(11)
|
||||
void lifecycleExpiration_eventBridgeDetailSaysLifecycleExpirationFromS3Itself() {
|
||||
given().contentType("text/plain").body("short-lived").when().put("/" + VERSIONED_BUCKET + "/expiring.txt")
|
||||
.then().statusCode(200);
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ReceiveMessage")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.formParam("MaxNumberOfMessages", "1")
|
||||
.formParam("WaitTimeSeconds", "0")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body", containsString("Object Created"));
|
||||
given()
|
||||
.contentType("application/xml")
|
||||
.body("<LifecycleConfiguration><Rule><ID>past</ID><Filter><Prefix>expiring</Prefix></Filter>"
|
||||
+ "<Status>Enabled</Status><Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"
|
||||
+ "</Rule></LifecycleConfiguration>")
|
||||
.when()
|
||||
.put("/" + VERSIONED_BUCKET + "?lifecycle")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
lifecycleSweeper.sweep();
|
||||
|
||||
// The user guide's lifecycle event: reason "Lifecycle Expiration", requester s3.amazonaws.com,
|
||||
// and no source-ip-address, which is "Only present for events triggered by an S3 request".
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
.formParam("Action", "ReceiveMessage")
|
||||
.formParam("QueueUrl", queueUrl)
|
||||
.formParam("MaxNumberOfMessages", "1")
|
||||
.formParam("WaitTimeSeconds", "0")
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("ReceiveMessageResponse.ReceiveMessageResult.Message.Body", allOf(
|
||||
containsString("expiring.txt"),
|
||||
containsString("\"reason\":\"Lifecycle Expiration\""),
|
||||
containsString("\"deletion-type\":\"Delete Marker Created\""),
|
||||
containsString("\"requester\":\"s3.amazonaws.com\""),
|
||||
not(containsString("source-ip-address"))));
|
||||
given().when().delete("/" + VERSIONED_BUCKET + "?lifecycle").then().statusCode(204);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(100)
|
||||
void cleanup() {
|
||||
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.hamcrest.Matchers.hasSize;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class S3LifecycleConfigurationTest {
|
||||
|
||||
private static final Instant NOW = Instant.parse("2026-10-06T12:00:00Z");
|
||||
|
||||
@Test
|
||||
void dayCountsRoundUpToTheNextMidnightUtc() {
|
||||
// The user guide's examples: created 1/15/2014 10:30 UTC plus 3 days is 1/19/2014 00:00 UTC.
|
||||
assertEquals(Instant.parse("2014-01-19T00:00:00Z"),
|
||||
S3LifecycleConfiguration.afterDays(Instant.parse("2014-01-15T10:30:00Z"), 3));
|
||||
assertEquals(Instant.parse("2014-01-17T00:00:00Z"),
|
||||
S3LifecycleConfiguration.afterDays(Instant.parse("2014-01-15T23:59:59.999Z"), 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void disabledRulesAndMalformedBodiesHaveNoRules() {
|
||||
assertThat(parse(rule("off", "Disabled", "<Filter><Prefix></Prefix></Filter>",
|
||||
"<Expiration><Days>1</Days></Expiration>")).rules(), empty());
|
||||
assertThat(S3LifecycleConfiguration.parse("<LifecycleConfiguration><Rule>").rules(), empty());
|
||||
assertThat(S3LifecycleConfiguration.parse("not xml").rules(), empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void theLegacyRulePrefixIsTheFilterWhenNoFilterIsGiven() {
|
||||
S3LifecycleConfiguration config = S3LifecycleConfiguration.parse("<LifecycleConfiguration><Rule>"
|
||||
+ "<ID>legacy</ID><Prefix>logs/</Prefix><Status>Enabled</Status>"
|
||||
+ "<Expiration><Days>1</Days></Expiration></Rule></LifecycleConfiguration>");
|
||||
|
||||
assertTrue(config.rules().getFirst().filter().matches("logs/a", Map.of(), 1));
|
||||
assertFalse(config.rules().getFirst().filter().matches("other/a", Map.of(), 1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anAndFilterNeedsThePrefixEveryTagAndTheExclusiveSizeRange() {
|
||||
S3LifecycleConfiguration.Filter filter = parse(rule("and", "Enabled", "<Filter><And>"
|
||||
+ "<Prefix>tmp/</Prefix>"
|
||||
+ "<Tag><Key>env</Key><Value>dev</Value></Tag>"
|
||||
+ "<Tag><Key>flag</Key><Value></Value></Tag>"
|
||||
+ "<ObjectSizeGreaterThan>10</ObjectSizeGreaterThan>"
|
||||
+ "<ObjectSizeLessThan>20</ObjectSizeLessThan>"
|
||||
+ "</And></Filter>", "<Expiration><Days>1</Days></Expiration>")).rules().getFirst().filter();
|
||||
Map<String, String> tags = Map.of("env", "dev", "flag", "", "extra", "x");
|
||||
|
||||
assertTrue(filter.matches("tmp/a", tags, 15));
|
||||
assertFalse(filter.matches("keep/a", tags, 15));
|
||||
assertFalse(filter.matches("tmp/a", Map.of("env", "dev", "flag", ""), 10));
|
||||
assertFalse(filter.matches("tmp/a", Map.of("env", "dev", "flag", ""), 20));
|
||||
assertFalse(filter.matches("tmp/a", Map.of("env", "prod", "flag", ""), 15));
|
||||
assertFalse(filter.matches("tmp/a", Map.of("env", "dev"), 15));
|
||||
assertFalse(filter.matches("tmp/a", Map.of("env", "dev", "flag", "set"), 15));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anObjectGetsTheEarliestExpiryOfTheRulesThatMatchIt() {
|
||||
S3LifecycleConfiguration config = parse(
|
||||
rule("ten days", "Enabled", "<Filter><Prefix></Prefix></Filter>",
|
||||
"<Expiration><Days>10</Days></Expiration>")
|
||||
+ rule("by date", "Enabled", "<Filter><Prefix>tmp/</Prefix></Filter>",
|
||||
"<Expiration><Date>2026-10-08T00:00:00.000Z</Date></Expiration>")
|
||||
+ rule("transition only", "Enabled", "<Filter><Prefix></Prefix></Filter>",
|
||||
"<Transition><Days>1</Days><StorageClass>GLACIER</StorageClass></Transition>"));
|
||||
|
||||
S3LifecycleConfiguration.Expiry tmp = config.currentVersionExpiry("tmp/a", Map.of(), 1, NOW);
|
||||
assertEquals(Instant.parse("2026-10-08T00:00:00Z"), tmp.date());
|
||||
assertEquals("expiry-date=\"Thu, 08 Oct 2026 00:00:00 GMT\", rule-id=\"by%20date\"", tmp.header());
|
||||
|
||||
S3LifecycleConfiguration.Expiry other = config.currentVersionExpiry("other/a", Map.of(), 1, NOW);
|
||||
assertEquals(Instant.parse("2026-10-17T00:00:00Z"), other.date());
|
||||
assertEquals("ten days", other.ruleId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpirationDateMayBeWrittenAsAPlainDate() {
|
||||
S3LifecycleConfiguration config = parse(rule("plain", "Enabled", "<Filter></Filter>",
|
||||
"<Expiration><Date>2020-01-01</Date></Expiration>"));
|
||||
|
||||
assertEquals(Instant.parse("2020-01-01T00:00:00Z"),
|
||||
config.currentVersionExpiry("a", Map.of(), 1, NOW).date());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleS3WouldRefuseIsDroppedWholeAndTheOtherRulesStillApply() {
|
||||
String good = rule("good", "Enabled", "<Filter></Filter>", "<Expiration><Days>1</Days></Expiration>");
|
||||
List<String> refused = List.of(
|
||||
rule("days soon", "Enabled", "<Filter></Filter>", "<Expiration><Days>soon</Days></Expiration>"),
|
||||
rule("days zero", "Enabled", "<Filter></Filter>", "<Expiration><Days>0</Days></Expiration>"),
|
||||
rule("bad date", "Enabled", "<Filter></Filter>", "<Expiration><Date>someday</Date></Expiration>"),
|
||||
rule("marker and days", "Enabled", "<Filter></Filter>", "<Expiration><Days>1</Days>"
|
||||
+ "<ExpiredObjectDeleteMarker>true</ExpiredObjectDeleteMarker></Expiration>"),
|
||||
rule("marker maybe", "Enabled", "<Filter></Filter>",
|
||||
"<Expiration><ExpiredObjectDeleteMarker>maybe</ExpiredObjectDeleteMarker></Expiration>"),
|
||||
rule("size word", "Enabled", "<Filter><ObjectSizeGreaterThan>big</ObjectSizeGreaterThan></Filter>",
|
||||
"<Expiration><Days>1</Days></Expiration>"),
|
||||
rule("size negative", "Enabled", "<Filter><ObjectSizeLessThan>-1</ObjectSizeLessThan></Filter>",
|
||||
"<Expiration><Days>1</Days></Expiration>"),
|
||||
rule("tag without value", "Enabled", "<Filter><Tag><Key>env</Key></Tag></Filter>",
|
||||
"<Expiration><Days>1</Days></Expiration>"),
|
||||
rule("tag twice", "Enabled", "<Filter><And><Tag><Key>env</Key><Value>a</Value></Tag>"
|
||||
+ "<Tag><Key>env</Key><Value>b</Value></Tag></And></Filter>",
|
||||
"<Expiration><Days>1</Days></Expiration>"),
|
||||
"<Rule><ID>no filter</ID><Status>Enabled</Status><Expiration><Days>1</Days></Expiration></Rule>",
|
||||
rule("noncurrent zero", "Enabled", "<Filter></Filter>",
|
||||
"<NoncurrentVersionExpiration><NoncurrentDays>0</NoncurrentDays></NoncurrentVersionExpiration>"),
|
||||
rule("retain too many", "Enabled", "<Filter></Filter>", "<NoncurrentVersionExpiration>"
|
||||
+ "<NoncurrentDays>1</NoncurrentDays><NewerNoncurrentVersions>101</NewerNoncurrentVersions>"
|
||||
+ "</NoncurrentVersionExpiration>"),
|
||||
"<Rule><ID>retain without filter</ID><Prefix></Prefix><Status>Enabled</Status>"
|
||||
+ "<NoncurrentVersionExpiration><NoncurrentDays>1</NoncurrentDays>"
|
||||
+ "<NewerNoncurrentVersions>1</NewerNoncurrentVersions></NoncurrentVersionExpiration></Rule>",
|
||||
rule("abort negative", "Enabled", "<Filter></Filter>", "<AbortIncompleteMultipartUpload>"
|
||||
+ "<DaysAfterInitiation>-1</DaysAfterInitiation></AbortIncompleteMultipartUpload>"),
|
||||
rule("status typo", "enabled", "<Filter></Filter>", "<Expiration><Days>1</Days></Expiration>"));
|
||||
|
||||
for (String bad : refused) {
|
||||
List<S3LifecycleConfiguration.Rule> rules = parse(bad + good).rules();
|
||||
assertEquals(List.of("good"), rules.stream().map(S3LifecycleConfiguration.Rule::id).toList(), bad);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBodyWithMalformedContentAfterTheConfigurationHasNoRules() {
|
||||
String rules = rule("past", "Enabled", "<Filter></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>");
|
||||
|
||||
assertThat(S3LifecycleConfiguration.parse(
|
||||
"<LifecycleConfiguration>" + rules + "</LifecycleConfiguration><Rule>").rules(), empty());
|
||||
assertThat(S3LifecycleConfiguration.parse(
|
||||
"<LifecycleConfiguration>" + rules + "</LifecycleConfiguration>trailing").rules(), empty());
|
||||
assertThat(S3LifecycleConfiguration.parse("<Other>" + rules + "</Other>").rules(), empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredObjectDeleteMarkerGoesAtOnceOrOnceOldEnoughForADaysRule() {
|
||||
S3LifecycleConfiguration explicit = parse(rule("markers", "Enabled", "<Filter></Filter>",
|
||||
"<Expiration><ExpiredObjectDeleteMarker>true</ExpiredObjectDeleteMarker></Expiration>"));
|
||||
S3LifecycleConfiguration days = parse(rule("days", "Enabled", "<Filter></Filter>",
|
||||
"<Expiration><Days>2</Days></Expiration>"));
|
||||
|
||||
assertTrue(explicit.removesExpiredObjectDeleteMarker("a", NOW, NOW));
|
||||
assertNull(explicit.currentVersionExpiry("a", Map.of(), 1, NOW));
|
||||
assertFalse(days.removesExpiredObjectDeleteMarker("a", NOW, Instant.parse("2026-10-08T23:59:59Z")));
|
||||
assertTrue(days.removesExpiredObjectDeleteMarker("a", NOW, Instant.parse("2026-10-09T00:00:00Z")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNoncurrentVersionNeedsBothItsAgeAndEnoughNewerVersionsRetained() {
|
||||
S3LifecycleConfiguration config = parse(rule("noncurrent", "Enabled", "<Filter></Filter>",
|
||||
"<NoncurrentVersionExpiration><NoncurrentDays>3</NoncurrentDays>"
|
||||
+ "<NewerNoncurrentVersions>2</NewerNoncurrentVersions></NoncurrentVersionExpiration>"));
|
||||
Instant becameNoncurrent = Instant.parse("2014-01-15T10:30:00Z");
|
||||
Instant due = Instant.parse("2014-01-19T00:00:00Z");
|
||||
|
||||
assertTrue(config.expiresNoncurrentVersion("a", Map.of(), 1, becameNoncurrent, 2, due));
|
||||
assertFalse(config.expiresNoncurrentVersion("a", Map.of(), 1, becameNoncurrent, 1, due));
|
||||
assertFalse(config.expiresNoncurrentVersion("a", Map.of(), 1, becameNoncurrent, 2,
|
||||
due.minusMillis(1)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void onlyAPrefixFilterSelectsMultipartUploadsToAbort() {
|
||||
S3LifecycleConfiguration prefix = parse(rule("abort", "Enabled", "<Filter><Prefix>big/</Prefix></Filter>",
|
||||
"<AbortIncompleteMultipartUpload><DaysAfterInitiation>1</DaysAfterInitiation>"
|
||||
+ "</AbortIncompleteMultipartUpload>"));
|
||||
S3LifecycleConfiguration tagged = parse(rule("abort", "Enabled",
|
||||
"<Filter><Tag><Key>k</Key><Value>v</Value></Tag></Filter>",
|
||||
"<AbortIncompleteMultipartUpload><DaysAfterInitiation>1</DaysAfterInitiation>"
|
||||
+ "</AbortIncompleteMultipartUpload>"));
|
||||
Instant due = Instant.parse("2026-10-08T00:00:00Z");
|
||||
|
||||
assertTrue(prefix.abortsUpload("big/a", NOW, due));
|
||||
assertFalse(prefix.abortsUpload("big/a", NOW, due.minusMillis(1)));
|
||||
assertFalse(prefix.abortsUpload("small/a", NOW, due));
|
||||
assertFalse(tagged.abortsUpload("big/a", NOW, due));
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyEnabledRuleIsRead() {
|
||||
assertThat(parse(rule("a", "Enabled", "<Filter></Filter>", "<Expiration><Days>1</Days></Expiration>")
|
||||
+ rule("b", "Enabled", "<Filter></Filter>", "<Expiration><Days>2</Days></Expiration>")
|
||||
+ rule("c", "Disabled", "<Filter></Filter>", "<Expiration><Days>3</Days></Expiration>")).rules(),
|
||||
hasSize(2));
|
||||
}
|
||||
|
||||
private static S3LifecycleConfiguration parse(String rules) {
|
||||
return S3LifecycleConfiguration.parse(
|
||||
"<LifecycleConfiguration xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\">"
|
||||
+ rules + "</LifecycleConfiguration>");
|
||||
}
|
||||
|
||||
private static String rule(String id, String status, String filter, String actions) {
|
||||
return "<Rule><ID>" + id + "</ID>" + filter + "<Status>" + status + "</Status>" + actions + "</Rule>";
|
||||
}
|
||||
}
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.containsString;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.not;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
|
||||
/**
|
||||
* Lifecycle expiration as a client sees it: the {@code x-amz-expiration} header on objects a rule
|
||||
* matches, and the sweep removing what has expired. The test profile does not schedule the sweep,
|
||||
* so each test runs it once, at the point it expects the rules applied.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class S3LifecycleExpirationIntegrationTest {
|
||||
|
||||
@Inject
|
||||
S3LifecycleSweeper sweeper;
|
||||
|
||||
@Test
|
||||
void objectsMatchedByADaysRuleCarryTheRoundedExpiryDateAndRuleId() {
|
||||
String bucket = "lc-expiration-header";
|
||||
given().put("/" + bucket).then().statusCode(200);
|
||||
putLifecycle(bucket, rule("three days", "<Filter><Prefix>tmp/</Prefix></Filter>",
|
||||
"<Expiration><Days>3</Days></Expiration>"));
|
||||
|
||||
Response put = given().body("hi").put("/" + bucket + "/tmp/a.txt");
|
||||
put.then().statusCode(200);
|
||||
Response head = given().head("/" + bucket + "/tmp/a.txt");
|
||||
head.then().statusCode(200);
|
||||
|
||||
// Creation time plus three days, rounded up to the next midnight UTC.
|
||||
Instant created = ZonedDateTime.parse(head.header("Last-Modified"),
|
||||
DateTimeFormatter.RFC_1123_DATE_TIME).toInstant();
|
||||
String expected = "expiry-date=\"" + S3Controller.RFC_822.format(
|
||||
created.plus(3, ChronoUnit.DAYS).truncatedTo(ChronoUnit.DAYS).plus(1, ChronoUnit.DAYS))
|
||||
+ "\", rule-id=\"three%20days\"";
|
||||
head.then().header("x-amz-expiration", equalTo(expected));
|
||||
put.then().header("x-amz-expiration", equalTo(expected));
|
||||
given().get("/" + bucket + "/tmp/a.txt").then()
|
||||
.statusCode(200)
|
||||
.header("x-amz-expiration", equalTo(expected));
|
||||
|
||||
given().body("hi").put("/" + bucket + "/keep/b.txt").then()
|
||||
.statusCode(200)
|
||||
.header("x-amz-expiration", nullValue());
|
||||
given().head("/" + bucket + "/keep/b.txt").then()
|
||||
.statusCode(200)
|
||||
.header("x-amz-expiration", nullValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDateRuleReportsThatDateAsTheExpiryDate() {
|
||||
String bucket = "lc-expiration-date-header";
|
||||
given().put("/" + bucket).then().statusCode(200);
|
||||
putLifecycle(bucket, rule("future-date", "<Filter><Prefix></Prefix></Filter>",
|
||||
"<Expiration><Date>2099-01-01T00:00:00Z</Date></Expiration>"));
|
||||
given().body("hi").put("/" + bucket + "/a.txt").then().statusCode(200);
|
||||
|
||||
given().head("/" + bucket + "/a.txt").then()
|
||||
.statusCode(200)
|
||||
.header("x-amz-expiration",
|
||||
equalTo("expiry-date=\"Thu, 01 Jan 2099 00:00:00 GMT\", rule-id=\"future-date\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSweepDeletesObjectsPastTheirExpirationAndLeavesOthers() {
|
||||
String bucket = "lc-expiration-sweep";
|
||||
given().put("/" + bucket).then().statusCode(200);
|
||||
given().body("hi").put("/" + bucket + "/tmp/a.txt").then().statusCode(200);
|
||||
given().body("hi").put("/" + bucket + "/keep/b.txt").then().statusCode(200);
|
||||
putLifecycle(bucket, rule("past-date", "<Filter><Prefix>tmp/</Prefix></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
sweeper.sweep();
|
||||
|
||||
given().head("/" + bucket + "/tmp/a.txt").then().statusCode(404);
|
||||
given().get("/" + bucket + "?list-type=2").then()
|
||||
.statusCode(200)
|
||||
.body(not(containsString("<Key>tmp/a.txt</Key>")))
|
||||
.body(containsString("<Key>keep/b.txt</Key>"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSweepPlacesADeleteMarkerInAVersionedBucket() {
|
||||
String bucket = "lc-expiration-versioned";
|
||||
given().put("/" + bucket).then().statusCode(200);
|
||||
given().body("<VersioningConfiguration><Status>Enabled</Status></VersioningConfiguration>")
|
||||
.put("/" + bucket + "?versioning").then().statusCode(200);
|
||||
String versionId = given().body("hi").put("/" + bucket + "/tmp/a.txt")
|
||||
.then().statusCode(200).extract().header("x-amz-version-id");
|
||||
putLifecycle(bucket, rule("past-date", "<Filter><Prefix>tmp/</Prefix></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
sweeper.sweep();
|
||||
|
||||
given().head("/" + bucket + "/tmp/a.txt").then().statusCode(404);
|
||||
given().get("/" + bucket + "?versions").then()
|
||||
.statusCode(200)
|
||||
.body(containsString("<DeleteMarker>"))
|
||||
.body(containsString("<VersionId>" + versionId + "</VersionId>"));
|
||||
given().get("/" + bucket + "/tmp/a.txt?versionId=" + versionId).then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void theSweepAppliesEachAccountsRulesToThatAccountsBucket() {
|
||||
String bucket = "lc-expiration-accounts";
|
||||
String withRule = "AWS4-HMAC-SHA256 Credential=000000000002/20260215/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
String withoutRule = "AWS4-HMAC-SHA256 Credential=000000000003/20260215/us-east-1/s3/aws4_request, "
|
||||
+ "SignedHeaders=host, Signature=abc";
|
||||
for (String auth : new String[] {withRule, withoutRule}) {
|
||||
given().header("Authorization", auth).put("/" + bucket).then().statusCode(200);
|
||||
given().header("Authorization", auth).body("hi").put("/" + bucket + "/a.txt").then().statusCode(200);
|
||||
}
|
||||
given()
|
||||
.header("Authorization", withRule)
|
||||
.contentType("application/xml")
|
||||
.body("<LifecycleConfiguration>" + rule("past-date", "<Filter><Prefix></Prefix></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>") + "</LifecycleConfiguration>")
|
||||
.when()
|
||||
.put("/" + bucket + "?lifecycle")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
sweeper.sweep();
|
||||
|
||||
given().header("Authorization", withRule).head("/" + bucket + "/a.txt").then().statusCode(404);
|
||||
given().header("Authorization", withoutRule).head("/" + bucket + "/a.txt").then().statusCode(200);
|
||||
}
|
||||
|
||||
private static String rule(String id, String filter, String actions) {
|
||||
return "<Rule><ID>" + id + "</ID>" + filter + "<Status>Enabled</Status>" + actions + "</Rule>";
|
||||
}
|
||||
|
||||
private static void putLifecycle(String bucket, String rules) {
|
||||
given()
|
||||
.contentType("application/xml")
|
||||
.body("<LifecycleConfiguration>" + rules + "</LifecycleConfiguration>")
|
||||
.when()
|
||||
.put("/" + bucket + "?lifecycle")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,348 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.RegionResolver;
|
||||
import io.github.hectorvent.floci.core.storage.InMemoryStorage;
|
||||
import io.github.hectorvent.floci.services.lambda.model.InvocationType;
|
||||
import io.github.hectorvent.floci.services.s3.model.LambdaNotification;
|
||||
import io.github.hectorvent.floci.services.s3.model.MultipartUpload;
|
||||
import io.github.hectorvent.floci.services.s3.model.NotificationConfiguration;
|
||||
import io.github.hectorvent.floci.services.s3.model.S3Object;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.hamcrest.MatcherAssert.assertThat;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.hamcrest.Matchers.containsInAnyOrder;
|
||||
import static org.hamcrest.Matchers.empty;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The lifecycle sweep, driven directly with a chosen "now" instead of waiting on the scheduler.
|
||||
*/
|
||||
class S3LifecycleServiceTest {
|
||||
|
||||
private static final String BUCKET = "lifecycle-bucket";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private RecordingLambdaInvoker notifications;
|
||||
private S3Service s3Service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
notifications = new RecordingLambdaInvoker();
|
||||
s3Service = new S3Service(new InMemoryStorage<>(), new InMemoryStorage<>(), tempDir.resolve("s3"), false,
|
||||
notifications, new RegionResolver("us-east-1", "000000000000"));
|
||||
s3Service.createBucket(BUCKET, "us-east-1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDaysRuleDeletesMatchingObjectsOnlyOnceTheRoundedExpiryHasPassed() {
|
||||
put("tmp/a.txt");
|
||||
put("keep/b.txt");
|
||||
lifecycle(rule("Enabled", "<Filter><Prefix>tmp/</Prefix></Filter>", "<Expiration><Days>1</Days></Expiration>"));
|
||||
Instant created = s3Service.headObject(BUCKET, "tmp/a.txt").getLastModified();
|
||||
Instant due = S3LifecycleConfiguration.afterDays(created, 1);
|
||||
|
||||
s3Service.applyLifecycleExpiration(due.minusMillis(1));
|
||||
assertTrue(s3Service.objectExists(BUCKET, "tmp/a.txt"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(due);
|
||||
assertFalse(s3Service.objectExists(BUCKET, "tmp/a.txt"));
|
||||
assertTrue(s3Service.objectExists(BUCKET, "keep/b.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDisabledRuleIsNotApplied() {
|
||||
put("a.txt");
|
||||
lifecycle(rule("Disabled", "<Filter></Filter>", "<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
|
||||
assertTrue(s3Service.objectExists(BUCKET, "a.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aTagFilterExpiresOnlyObjectsCarryingTheTag() {
|
||||
put("tagged.txt");
|
||||
put("untagged.txt");
|
||||
s3Service.putObjectTagging(BUCKET, "tagged.txt", Map.of("env", "ephemeral"));
|
||||
lifecycle(rule("Enabled", "<Filter><Tag><Key>env</Key><Value>ephemeral</Value></Tag></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
|
||||
assertFalse(s3Service.objectExists(BUCKET, "tagged.txt"));
|
||||
assertTrue(s3Service.objectExists(BUCKET, "untagged.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void inAVersionedBucketTheCurrentVersionGetsADeleteMarkerOnce() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object original = put("a.txt");
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>", "<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
|
||||
List<S3Object> versions = versions("a.txt");
|
||||
assertEquals(2, versions.size(), "the original version and one delete marker");
|
||||
assertTrue(versions.getFirst().isDeleteMarker());
|
||||
assertEquals(original.getVersionId(), versions.get(1).getVersionId());
|
||||
assertFalse(s3Service.objectExists(BUCKET, "a.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void noncurrentVersionsBeyondTheRetainedCountExpireOnceOldEnough() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object v1 = put("a.txt");
|
||||
S3Object v2 = put("a.txt");
|
||||
S3Object v3 = put("a.txt");
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>", "<NoncurrentVersionExpiration><NoncurrentDays>1</NoncurrentDays>"
|
||||
+ "<NewerNoncurrentVersions>1</NewerNoncurrentVersions></NoncurrentVersionExpiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
assertThat(versionIds("a.txt"), contains(v3.getVersionId(), v2.getVersionId(), v1.getVersionId()));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now().plus(Duration.ofDays(3)));
|
||||
assertThat(versionIds("a.txt"), contains(v3.getVersionId(), v2.getVersionId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aNoncurrentVersionUnderALegalHoldIsKept() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object held = s3Service.putObject(BUCKET, "a.txt", "held".getBytes(StandardCharsets.UTF_8), "text/plain",
|
||||
Map.of(), null, null, "ON");
|
||||
S3Object current = put("a.txt");
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>",
|
||||
"<NoncurrentVersionExpiration><NoncurrentDays>1</NoncurrentDays></NoncurrentVersionExpiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now().plus(Duration.ofDays(3)));
|
||||
|
||||
assertThat(versionIds("a.txt"), containsInAnyOrder(current.getVersionId(), held.getVersionId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void anExpiredObjectDeleteMarkerIsRemoved() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object only = put("a.txt");
|
||||
s3Service.deleteObject(BUCKET, "a.txt");
|
||||
s3Service.deleteObject(BUCKET, "a.txt", only.getVersionId());
|
||||
assertEquals(1, versions("a.txt").size(), "only the delete marker remains");
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>",
|
||||
"<Expiration><ExpiredObjectDeleteMarker>true</ExpiredObjectDeleteMarker></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
|
||||
assertThat(versions("a.txt"), empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aDeleteMarkerWithNoncurrentVersionsIsKept() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
put("a.txt");
|
||||
s3Service.deleteObject(BUCKET, "a.txt");
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>",
|
||||
"<Expiration><ExpiredObjectDeleteMarker>true</ExpiredObjectDeleteMarker></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
|
||||
assertEquals(2, versions("a.txt").size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void incompleteMultipartUploadsAreAbortedAfterTheirDays() {
|
||||
MultipartUpload upload = s3Service.initiateMultipartUpload(BUCKET, "big/a.bin", "application/octet-stream");
|
||||
lifecycle(rule("Enabled", "<Filter><Prefix>big/</Prefix></Filter>",
|
||||
"<AbortIncompleteMultipartUpload><DaysAfterInitiation>1</DaysAfterInitiation>"
|
||||
+ "</AbortIncompleteMultipartUpload>"));
|
||||
Instant due = S3LifecycleConfiguration.afterDays(upload.getInitiated(), 1);
|
||||
|
||||
s3Service.applyLifecycleExpiration(due.minusMillis(1));
|
||||
assertEquals(1, s3Service.listMultipartUploads(BUCKET).size());
|
||||
|
||||
s3Service.applyLifecycleExpiration(due);
|
||||
assertThat(s3Service.listMultipartUploads(BUCKET), empty());
|
||||
}
|
||||
|
||||
@Test
|
||||
void lifecycleDeletionsAreReportedAsLifecycleExpirationEvents() throws IOException {
|
||||
put("a.txt");
|
||||
NotificationConfiguration config = new NotificationConfiguration();
|
||||
config.getLambdaFunctionConfigurations().add(new LambdaNotification("removed",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:removed", List.of("s3:ObjectRemoved:*"), List.of()));
|
||||
config.getLambdaFunctionConfigurations().add(new LambdaNotification("lifecycle",
|
||||
"arn:aws:lambda:us-east-1:000000000000:function:lifecycle",
|
||||
List.of("s3:LifecycleExpiration:*"), List.of()));
|
||||
s3Service.putBucketNotificationConfiguration(BUCKET, config, true);
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>", "<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now());
|
||||
|
||||
assertEquals(List.of("lifecycle"), notifications.functionNames);
|
||||
JsonNode record = new ObjectMapper().readTree(notifications.payloads.getFirst()).path("Records").get(0);
|
||||
assertEquals("LifecycleExpiration:Delete", record.path("eventName").asText());
|
||||
// The user guide's example names S3 itself, not a requester.
|
||||
assertEquals("s3.amazonaws.com", record.path("userIdentity").path("principalId").asText());
|
||||
assertEquals("s3.amazonaws.com", record.path("requestParameters").path("sourceIPAddress").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionsWrittenInTheSameMillisecondKeepTheOrderTheyWereWrittenIn() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object v1 = put("a.txt");
|
||||
S3Object v2 = put("a.txt");
|
||||
S3Object v3 = put("a.txt");
|
||||
Instant sameMillisecond = Instant.parse("2026-10-01T10:00:00Z");
|
||||
for (S3Object version : List.of(v1, v2, v3)) {
|
||||
version.setLastModified(sameMillisecond);
|
||||
}
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>", "<NoncurrentVersionExpiration><NoncurrentDays>1</NoncurrentDays>"
|
||||
+ "<NewerNoncurrentVersions>1</NewerNoncurrentVersions></NoncurrentVersionExpiration>"));
|
||||
|
||||
assertThat(versionIds("a.txt"), contains(v3.getVersionId(), v2.getVersionId(), v1.getVersionId()));
|
||||
s3Service.applyLifecycleExpiration(sameMillisecond.plus(Duration.ofDays(3)));
|
||||
|
||||
assertThat(versionIds("a.txt"), contains(v3.getVersionId(), v2.getVersionId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aKeyLeftWithOnlyVersionsInASuspendedBucketHasItsOlderVersionsExpired() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object v1 = put("a.txt");
|
||||
S3Object v2 = put("a.txt");
|
||||
s3Service.putBucketVersioning(BUCKET, "Suspended");
|
||||
s3Service.deleteObject(BUCKET, "a.txt");
|
||||
assertThat(versionIds("a.txt"), contains(v2.getVersionId(), v1.getVersionId()));
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>",
|
||||
"<NoncurrentVersionExpiration><NoncurrentDays>1</NoncurrentDays></NoncurrentVersionExpiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now().plus(Duration.ofDays(3)));
|
||||
|
||||
// v1 has been noncurrent since v2 was written. When v2 stopped being current is not recorded.
|
||||
assertThat(versionIds("a.txt"), contains(v2.getVersionId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRuleWithAValueS3WouldRefuseExpiresNothing() {
|
||||
put("small.txt");
|
||||
lifecycle(rule("Enabled", "<Filter><ObjectSizeGreaterThan>large</ObjectSizeGreaterThan></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>")
|
||||
+ rule("Enabled", "<Filter></Filter>", "<Expiration><Days>0</Days></Expiration>"));
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now().plus(Duration.ofDays(3)));
|
||||
|
||||
assertTrue(s3Service.objectExists(BUCKET, "small.txt"));
|
||||
assertNull(s3Service.expirationHeader(s3Service.headObject(BUCKET, "small.txt")));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBucketThatFailsDoesNotStopTheOthersAndTheRunReportsIt() {
|
||||
S3Service failing = new S3Service(new InMemoryStorage<>(), new FailingDeletes("broken/"),
|
||||
tempDir.resolve("failing"), false, notifications, new RegionResolver("us-east-1", "000000000000"));
|
||||
for (String bucket : List.of("broken", "healthy")) {
|
||||
failing.createBucket(bucket, "us-east-1");
|
||||
failing.putObject(bucket, "a.txt", "data".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
|
||||
failing.putBucketLifecycle(bucket, "<LifecycleConfiguration>" + rule("Enabled", "<Filter></Filter>",
|
||||
"<Expiration><Date>2020-01-01T00:00:00Z</Date></Expiration>") + "</LifecycleConfiguration>", null);
|
||||
}
|
||||
|
||||
IllegalStateException failure = assertThrows(IllegalStateException.class,
|
||||
() -> failing.applyLifecycleExpiration(Instant.now()));
|
||||
|
||||
assertTrue(failure.getMessage().contains("[broken]"), failure.getMessage());
|
||||
assertEquals("disk failure", failure.getSuppressed()[0].getMessage());
|
||||
assertFalse(failing.objectExists("healthy", "a.txt"));
|
||||
assertTrue(failing.objectExists("broken", "a.txt"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void theExpirationHeaderDescribesOnlyTheCurrentVersion() {
|
||||
s3Service.putBucketVersioning(BUCKET, "Enabled");
|
||||
S3Object older = put("a.txt");
|
||||
put("a.txt");
|
||||
lifecycle(rule("Enabled", "<Filter></Filter>", "<Expiration><Date>2099-01-01T00:00:00Z</Date></Expiration>"));
|
||||
|
||||
assertEquals("expiry-date=\"Thu, 01 Jan 2099 00:00:00 GMT\", rule-id=\"rule\"",
|
||||
s3Service.expirationHeader(s3Service.headObject(BUCKET, "a.txt")));
|
||||
assertNull(s3Service.expirationHeader(s3Service.headObject(BUCKET, "a.txt", older.getVersionId())));
|
||||
}
|
||||
|
||||
@Test
|
||||
void aBucketWithoutALifecycleConfigurationIsLeftAlone() {
|
||||
put("a.txt");
|
||||
|
||||
s3Service.applyLifecycleExpiration(Instant.now().plus(Duration.ofDays(10_000)));
|
||||
|
||||
assertTrue(s3Service.objectExists(BUCKET, "a.txt"));
|
||||
assertNull(s3Service.expirationHeader(s3Service.headObject(BUCKET, "a.txt")));
|
||||
assertNotNull(s3Service.headObject(BUCKET, "a.txt"));
|
||||
}
|
||||
|
||||
private S3Object put(String key) {
|
||||
return s3Service.putObject(BUCKET, key, "data".getBytes(StandardCharsets.UTF_8), "text/plain", Map.of());
|
||||
}
|
||||
|
||||
private void lifecycle(String rules) {
|
||||
s3Service.putBucketLifecycle(BUCKET, "<LifecycleConfiguration>" + rules + "</LifecycleConfiguration>", null);
|
||||
}
|
||||
|
||||
private static String rule(String status, String filter, String actions) {
|
||||
return "<Rule><ID>rule</ID>" + filter + "<Status>" + status + "</Status>" + actions + "</Rule>";
|
||||
}
|
||||
|
||||
/** Newest first. */
|
||||
private List<S3Object> versions(String key) {
|
||||
return s3Service.listObjectVersions(BUCKET, key, 1000, null).versions();
|
||||
}
|
||||
|
||||
private List<String> versionIds(String key) {
|
||||
return versions(key).stream().map(S3Object::getVersionId).toList();
|
||||
}
|
||||
|
||||
/** An object store whose deletes fail under one bucket, as a disk error would. */
|
||||
private static final class FailingDeletes extends InMemoryStorage<String, S3Object> {
|
||||
private final String failingPrefix;
|
||||
|
||||
FailingDeletes(String failingPrefix) {
|
||||
this.failingPrefix = failingPrefix;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String key) {
|
||||
if (key.startsWith(failingPrefix)) {
|
||||
throw new IllegalStateException("disk failure");
|
||||
}
|
||||
super.delete(key);
|
||||
}
|
||||
}
|
||||
|
||||
private static final class RecordingLambdaInvoker implements S3Service.LambdaInvoker {
|
||||
private final List<String> functionNames = new ArrayList<>();
|
||||
private final List<byte[]> payloads = new ArrayList<>();
|
||||
|
||||
@Override
|
||||
public void invoke(String region, String functionName, byte[] payload, InvocationType type) {
|
||||
functionNames.add(functionName);
|
||||
payloads.add(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package io.github.hectorvent.floci.services.s3;
|
||||
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig.S3ServiceConfig;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig.ServicesConfig;
|
||||
import io.quarkus.runtime.ShutdownEvent;
|
||||
import io.quarkus.runtime.StartupEvent;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
class S3LifecycleSweeperTest {
|
||||
|
||||
private static final Clock CLOCK = Clock.fixed(Instant.parse("2026-10-06T12:00:00Z"), ZoneOffset.UTC);
|
||||
|
||||
@Test
|
||||
void aFailingSweepDoesNotEscapeTheScheduledTask() {
|
||||
S3Service s3Service = mock(S3Service.class);
|
||||
doThrow(new IllegalStateException("sweep failed")).when(s3Service).applyLifecycleExpiration(CLOCK.instant());
|
||||
S3LifecycleSweeper sweeper = new S3LifecycleSweeper(s3Service, configWithInterval(60L), CLOCK);
|
||||
|
||||
assertDoesNotThrow(sweeper::sweep);
|
||||
verify(s3Service).applyLifecycleExpiration(CLOCK.instant());
|
||||
}
|
||||
|
||||
@Test
|
||||
void nonPositiveConfiguredInterval_doesNotPreventStartup() {
|
||||
for (long interval : new long[] {0L, -1L, Long.MIN_VALUE}) {
|
||||
S3LifecycleSweeper sweeper = new S3LifecycleSweeper(null, configWithInterval(interval), CLOCK);
|
||||
assertDoesNotThrow(() -> sweeper.onStart(new StartupEvent()),
|
||||
"interval " + interval + " must not abort startup");
|
||||
sweeper.onStop(new ShutdownEvent());
|
||||
}
|
||||
}
|
||||
|
||||
private static EmulatorConfig configWithInterval(long intervalSeconds) {
|
||||
EmulatorConfig config = configView(EmulatorConfig.class);
|
||||
ServicesConfig services = configView(ServicesConfig.class);
|
||||
S3ServiceConfig s3 = configView(S3ServiceConfig.class);
|
||||
doReturn(services).when(config).services();
|
||||
doReturn(s3).when(services).s3();
|
||||
doReturn(true).when(s3).enabled();
|
||||
doReturn(true).when(s3).lifecycleSweepEnabled();
|
||||
doReturn(intervalSeconds).when(s3).lifecycleSweepIntervalSeconds();
|
||||
return config;
|
||||
}
|
||||
|
||||
private static <T> T configView(Class<T> configType) {
|
||||
return mock(configType, invocation -> {
|
||||
throw new AssertionError("Unexpected configuration access: " + invocation.getMethod());
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user