Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(ram): advance share update timestamps within one clock tick (#6674)

Jimmy Liu Jia15e2c9895769
diff --git a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java
index 0541501daa..b470b65d4c 100644
--- a/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/ram/RamService.java
@@ -21,6 +21,7 @@ import jakarta.annotation.PostConstruct;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
+import java.time.Clock;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
@@ -73,14 +74,20 @@ public class RamService {
private final StorageFactory storageFactory;
private final OrganizationsService organizationsService;
+ private final Clock clock;
private StorageBackend<String, ResourceShare> shares;
private StorageBackend<String, Boolean> settings;
private StorageBackend<String, ResourceShareInvitation> invitations;
@Inject
public RamService(StorageFactory storageFactory, OrganizationsService organizationsService) {
+ this(storageFactory, organizationsService, Clock.systemUTC());
+ }
+
+ RamService(StorageFactory storageFactory, OrganizationsService organizationsService, Clock clock) {
this.storageFactory = storageFactory;
this.organizationsService = organizationsService;
+ this.clock = clock;
}
/** Constructor used by isolated service tests with an explicit Organizations test double. */
@@ -575,12 +582,31 @@ public class RamService {
}
/**
- * The single write seam: every create and every mutation lands here, so stamping
- * lastUpdatedTime once at this point keeps it advancing without six call sites having to
- * remember to do it. Returns the stamped share so callers respond with what was stored.
+ * The single write seam: every create and every mutation lands here. Existing shares are
+ * stamped here so lastUpdatedTime advances without six call sites having to remember to do it;
+ * a fresh share keeps its equal creation and last-updated timestamps. The read, timestamp
+ * calculation, and write are one critical section so concurrent mutations cannot reuse a stamp.
+ * Returns the stored share.
*/
- private ResourceShare putForOwner(ResourceShare share) {
- ResourceShare stamped = share.withLastUpdatedTime(Instant.now());
+ private synchronized ResourceShare putForOwner(ResourceShare share) {
+ String owningAccountId = share.getOwningAccountId();
+ Optional<ResourceShare> previous;
+ if (shares instanceof AccountAwareStorageBackend<ResourceShare> accountAware) {
+ previous = accountAware.getForAccountMigratingLegacy(
+ owningAccountId, share.getResourceShareArn(),
+ candidate -> owningAccountId.equals(candidate.getOwningAccountId()));
+ } else {
+ previous = shares.get(share.getResourceShareArn());
+ }
+ ResourceShare stamped = share;
+ if (previous.isPresent()) {
+ Instant now = clock.instant();
+ Instant previousLastUpdated = previous.get().getLastUpdatedTime();
+ if (now.toEpochMilli() <= previousLastUpdated.toEpochMilli()) {
+ now = Instant.ofEpochMilli(previousLastUpdated.toEpochMilli() + 1);
+ }
+ stamped = share.withLastUpdatedTime(now);
+ }
if (shares instanceof AccountAwareStorageBackend<ResourceShare> accountAware) {
accountAware.putForAccount(
stamped.getOwningAccountId(), stamped.getResourceShareArn(), stamped);
diff --git a/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java
index bc97ba9006..9de6aac2c0 100644
--- a/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/ram/RamServiceTest.java
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.core.type.TypeReference;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.PaginatedResult;
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.organizations.OrganizationsService;
@@ -16,15 +17,22 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.function.Executable;
+import java.time.Clock;
+import java.time.Instant;
+import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
@@ -478,6 +486,89 @@ class RamServiceTest {
assertEquals(created.getCreationTime(), tagged.getCreationTime());
}
+ @Test
+ void consecutiveWritesInOneClockTickAdvanceLastUpdatedTime() {
+ Clock fixedClock = Clock.fixed(Instant.parse("2030-01-01T00:00:00Z"), ZoneOffset.UTC);
+ RamService fixedClockService = new RamService(new SharedStorageFactory(), null, fixedClock);
+ fixedClockService.initializeStorage();
+
+ ResourceShare created = fixedClockService.createResourceShare(
+ "original", List.of(), List.of(), false, "us-east-1", OWNER);
+ assertEquals(created.getCreationTime(), created.getLastUpdatedTime());
+ String arn = created.getResourceShareArn();
+ ResourceShare firstUpdate = fixedClockService.updateResourceShare(
+ arn, "first", null, OWNER, "us-east-1");
+ ResourceShare secondUpdate = fixedClockService.updateResourceShare(
+ arn, "second", null, OWNER, "us-east-1");
+
+ assertEquals(created.getCreationTime(), firstUpdate.getCreationTime());
+ assertEquals(created.getCreationTime(), secondUpdate.getCreationTime());
+ assertTrue(firstUpdate.getLastUpdatedTime().toEpochMilli()
+ > created.getLastUpdatedTime().toEpochMilli());
+ assertTrue(secondUpdate.getLastUpdatedTime().toEpochMilli()
+ > firstUpdate.getLastUpdatedTime().toEpochMilli());
+ }
+
+ @Test
+ void updateOfLegacyUnprefixedShareAdvancesLastUpdatedTime() {
+ TestStorageFactory storage = new TestStorageFactory(false);
+ Instant creationTime = Instant.parse("2029-01-01T00:00:00Z");
+ String arn = "arn:aws:ram:us-east-1:" + OWNER + ":resource-share/legacy";
+ RamService legacyService = new RamService(
+ storage, null, Clock.fixed(Instant.parse("2030-01-01T00:00:00Z"), ZoneOffset.UTC));
+ legacyService.initializeStorage();
+ ResourceShare legacy = new ResourceShare(
+ arn, "legacy", OWNER, List.of(), List.of(), false, "ACTIVE",
+ creationTime, creationTime, Map.of());
+ storage.putLegacy("ram-resource-shares.json", arn, legacy);
+
+ ResourceShare updated = legacyService.updateResourceShare(
+ arn, "updated", null, OWNER, "us-east-1");
+
+ assertEquals(creationTime, updated.getCreationTime());
+ assertTrue(updated.getLastUpdatedTime().isAfter(creationTime));
+ }
+
+ @Test
+ void overlappingUpdatesAdvanceLastUpdatedTimeForEachWrite() throws Exception {
+ TestStorageFactory storage = new TestStorageFactory(true);
+ Clock fixedClock = Clock.fixed(Instant.parse("2030-01-01T00:00:00Z"), ZoneOffset.UTC);
+ RamService concurrentService = new RamService(storage, null, fixedClock);
+ concurrentService.initializeStorage();
+ ResourceShare seeded = concurrentService.createResourceShare(
+ "original", List.of(), List.of(), false, "us-east-1", OWNER);
+ storage.armShareReads();
+
+ int threadCount = 2;
+ ExecutorService executor = Executors.newFixedThreadPool(threadCount);
+ try {
+ CountDownLatch ready = new CountDownLatch(threadCount);
+ CountDownLatch start = new CountDownLatch(1);
+ List<Future<ResourceShare>> results = new ArrayList<>();
+ for (String name : List.of("first", "second")) {
+ results.add(executor.submit(() -> {
+ ready.countDown();
+ assertTrue(start.await(5, TimeUnit.SECONDS));
+ return concurrentService.updateResourceShare(
+ seeded.getResourceShareArn(), name, null, OWNER, "us-east-1");
+ }));
+ }
+ assertTrue(ready.await(5, TimeUnit.SECONDS), "every thread reached the start gate");
+ start.countDown();
+
+ Set<Instant> updateTimes = new HashSet<>();
+ for (Future<ResourceShare> result : results) {
+ updateTimes.add(result.get(5, TimeUnit.SECONDS).getLastUpdatedTime());
+ }
+ assertEquals(threadCount, updateTimes.size(), "each overlapping write gets a unique timestamp");
+ } finally {
+ executor.shutdownNow();
+ }
+
+ assertTrue(concurrentService.getResourceShares(OWNER, "SELF", "us-east-1").stream()
+ .findFirst().orElseThrow().getLastUpdatedTime().isAfter(seeded.getLastUpdatedTime()));
+ }
+
@Test
void accountPrincipalWithoutOrganizationSharingCreatesPendingInvitation() {
ResourceShare share = service.createResourceShare(
@@ -755,4 +846,65 @@ class RamServiceTest {
fileName, ignored -> AccountAwareStorageBackend.inMemory("000000000000"));
}
}
+
+ private static final class TestStorageFactory extends StorageFactory {
+ private final Map<String, RawStorage> rawStores = new HashMap<>();
+ private final Map<String, AccountAwareStorageBackend<Object>> stores = new HashMap<>();
+ private final boolean coordinateShareReads;
+
+ private TestStorageFactory(boolean coordinateShareReads) {
+ super(null, null);
+ this.coordinateShareReads = coordinateShareReads;
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ public <V> AccountAwareStorageBackend<V> create(String serviceName,
+ String fileName,
+ TypeReference<Map<String, V>> typeReference) {
+ AccountAwareStorageBackend<Object> store = stores.computeIfAbsent(fileName, ignored -> {
+ RawStorage raw = new RawStorage(coordinateShareReads && fileName.equals("ram-resource-shares.json"));
+ rawStores.put(fileName, raw);
+ return new AccountAwareStorageBackend<>(raw, null, "000000000000");
+ });
+ return (AccountAwareStorageBackend<V>) store;
+ }
+
+ private void putLegacy(String fileName, String key, ResourceShare value) {
+ rawStores.get(fileName).put(key, value);
+ }
+
+ private void armShareReads() {
+ rawStores.get("ram-resource-shares.json").armReads();
+ }
+ }
+
+ private static final class RawStorage extends InMemoryStorage<String, Object> {
+ private final boolean coordinateReads;
+ private final AtomicInteger coordinatedReads = new AtomicInteger();
+ private volatile CountDownLatch readGate = new CountDownLatch(0);
+
+ private RawStorage(boolean coordinateReads) {
+ this.coordinateReads = coordinateReads;
+ }
+
+ private void armReads() {
+ coordinatedReads.set(0);
+ readGate = new CountDownLatch(2);
+ }
+
+ @Override
+ public Optional<Object> get(String key) {
+ if (coordinateReads && key.startsWith(OWNER + "/") && coordinatedReads.incrementAndGet() <= 2) {
+ CountDownLatch gate = readGate;
+ gate.countDown();
+ try {
+ gate.await(250, TimeUnit.MILLISECONDS);
+ } catch (InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ return super.get(key);
+ }
+ }
}