Skip to content
Open
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 @@ -44,12 +44,15 @@ private void recalculate(Module module, Supplier<List<ModuleVersion>> versions)
if (Objects.equals(latestVersion, module.getLatestVersion())) {
return;
}
module.setLatestVersion(latestVersion);
// A targeted UPDATE instead of an entity save: the module was loaded before this write, and
// saving it would also write a field the API changed in between (e.g. description) back to
// its older value. Not calling module.setLatestVersion(...) is intentional too, so a managed
// Module is not dirtied and flushed back at transaction commit.
log.info("Latest module {}/{} version {}", module.getOrganization().getName(), module.getName(), latestVersion);
moduleRepository.save(module);
moduleRepository.updateLatestVersion(module.getId(), latestVersion);
} catch (Exception e) {
// Broad catch is intentional: a bad version string must not stop the refresh job or a version update.
log.error("Failed to calculate latest module version {}/{}", module.getOrganization().getName(), module.getName());
log.error("Failed to calculate latest module version {}/{}", module.getOrganization().getName(), module.getName(), e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import io.terrakube.api.rs.module.Module;

public interface ModuleRepository extends JpaRepository<Module, UUID> {
Expand Down Expand Up @@ -43,9 +44,8 @@ public interface ModuleRepository extends JpaRepository<Module, UUID> {

// First write of a successful refresh: takes the row lock and proves the lease is still ours, before
// the caller reads and inserts versions. Neither this nor finishRefresh clears the persistence context:
// the caller loads the module in between and keeps using it (Module has @DynamicUpdate, so saving it
// later does not write these columns back). Refresh results never go through an entity save, which
// would also move updatedDate on every refresh.
// the caller loads the module in between and keeps using it. Refresh results never go through an
// entity save, which would also move updatedDate on every refresh.
@Modifying
@Query("UPDATE module m SET m.lastRefresh = :now WHERE m.id = :id AND m.nextRefresh = :lease")
int markRefreshed(@Param("id") UUID id, @Param("lease") Date lease, @Param("now") Date now);
Expand All @@ -62,6 +62,15 @@ int finishRefresh(@Param("id") UUID id, @Param("next") Date next,
int recordFailure(@Param("id") UUID id, @Param("lease") Date lease, @Param("next") Date next,
@Param("now") Date now, @Param("error") String error);

// The newest served version, written by the version recalculation (ModuleLatestVersion) after a refresh
// and after a version change. A targeted UPDATE, not an entity save: the module the recalculation ran
// on was loaded before this write, so a save would also write fields the API changed in between
// (e.g. description) back to their older values.
@Transactional
@Modifying
@Query("UPDATE module m SET m.latestVersion = :latestVersion WHERE m.id = :id")
int updateLatestVersion(@Param("id") UUID id, @Param("latestVersion") String latestVersion);

// Manual sync. A refresh still running under the old lease then writes nothing, and the module is
// claimed again on the next tick.
@Modifying(clearAutomatically = true)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,13 @@
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;

import io.terrakube.api.plugin.scheduler.module.ModuleLatestVersion;
import io.terrakube.api.plugin.scheduler.module.ModuleRefreshTransactions;
import io.terrakube.api.plugin.scheduler.module.ModuleVersionNormalizer.NormalizedVersion;
import io.terrakube.api.repository.ModuleRepository;
import io.terrakube.api.repository.ModuleVersionRepository;
import io.terrakube.api.rs.Organization;
import io.terrakube.api.rs.VersionStatus;
import io.terrakube.api.rs.module.Module;
import io.terrakube.api.rs.module.ModuleVersion;
import io.terrakube.api.rs.vcs.Vcs;
Expand All @@ -38,6 +40,9 @@ class ModuleRefreshTransactionsIntegrationTest extends ServerApplicationTests {
@Autowired
ModuleRefreshTransactions transactions;

@Autowired
ModuleLatestVersion moduleLatestVersion;

@Autowired
ModuleRepository moduleRepository;

Expand Down Expand Up @@ -225,7 +230,7 @@ void successThatChangesLatestVersionKeepsTheComputedNextRefresh() {
Date lease = plusMinutes(now, 5);
transactions.claim(module.getId(), lease, now);

// A new version also moves latest_version, which ModuleLatestVersion saves through the entity.
// A new version also moves latest_version, which ModuleLatestVersion writes through a targeted UPDATE.
transactions.recordSuccess(module.getId(), lease, canonical("v1.0.0"), refs("v1.0.0"));

Module stored = reload(module);
Expand Down Expand Up @@ -257,6 +262,36 @@ void entityUpdateAfterClaimKeepsTheLease() {
assertThat(stored.getNextRefresh().getTime()).isEqualTo(lease.getTime());
}

@Test
void refreshKeepsADescriptionEditedWhileItRuns() {
Module seeded = seed(null);
seeded.setDescription("original description");
Module module = moduleRepository.save(seeded);

// A module snapshot from before the edit, as held by ModuleVersionManageHook (it recalculates
// POSTCOMMIT, outside a transaction) or by any caller with a stale snapshot. The refresh worker
// itself holds no Module across ls-remote: loadTarget returns a ModuleRefreshTarget DTO, and
// recordSuccess takes the row lock via markRefreshed before loading the Module.
Module older = reload(module);

// The API edits the description while the refresh runs its ls-remote.
TransactionTemplate request = new TransactionTemplate(transactionManager);
request.executeWithoutResult(edit -> moduleRepository.findById(module.getId()).orElseThrow()
.setDescription("edited while refreshing"));

// The recalculation then runs from the stale snapshot: latest_version moves through a targeted
// UPDATE, never an entity save, so the description edit survives. In recordSuccess, not calling
// save(module) also keeps refreshes from bumping updatedDate/updatedBy.
ModuleVersion discovered = new ModuleVersion();
discovered.setVersion("1.0.0");
discovered.setStatus(VersionStatus.active);
moduleLatestVersion.recalculate(older, List.of(discovered));

Module stored = reload(module);
assertThat(stored.getDescription()).isEqualTo("edited while refreshing");
assertThat(stored.getLatestVersion()).isEqualTo("1.0.0");
}

@Test
void markDueMakesTheModuleDueNow() {
Date now = nowSeconds();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,41 +9,44 @@
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;

class ModuleLatestVersionTest {

private static final UUID MODULE_ID = UUID.fromString("d5513d4b-9a09-4e3b-8d1e-4cb2f28f8a83");

private final ModuleRepository moduleRepository = mock(ModuleRepository.class);
private final ModuleVersionRepository moduleVersionRepository = mock(ModuleVersionRepository.class);
private final ModuleLatestVersion moduleLatestVersion =
new ModuleLatestVersion(moduleRepository, moduleVersionRepository);

@Test
void savesTheNewestServedVersionFromThePreloadedList() {
void writesTheNewestServedVersionFromThePreloadedList() {
Module module = module("1.0.0");

moduleLatestVersion.recalculate(module,
List.of(version("1.0.0", VersionStatus.active), version("1.2.0", VersionStatus.deprecated),
version("2.0.0", VersionStatus.removed)));

assertThat(module.getLatestVersion()).isEqualTo("1.2.0");
verify(moduleRepository).save(module);
verify(moduleRepository).updateLatestVersion(MODULE_ID, "1.2.0");
verify(moduleRepository, never()).save(any());
verifyNoInteractions(moduleVersionRepository);
}

@Test
void skipsTheSaveWhenTheLatestVersionIsUnchanged() {
void skipsTheWriteWhenTheLatestVersionIsUnchanged() {
Module module = module("1.2.0");

moduleLatestVersion.recalculate(module,
List.of(version("1.0.0", VersionStatus.active), version("1.2.0", VersionStatus.active)));

verify(moduleRepository, never()).save(module);
verifyNoInteractions(moduleRepository);
}

@Test
Expand All @@ -52,14 +55,15 @@ void marksAModuleWithoutServedVersionsAsPending() {

moduleLatestVersion.recalculate(module, List.of(version("1.0.0", VersionStatus.removed)));

assertThat(module.getLatestVersion()).isEqualTo("Version pending");
verify(moduleRepository).save(module);
verify(moduleRepository).updateLatestVersion(MODULE_ID, "Version pending");
verify(moduleRepository, never()).save(any());
}

private static Module module(String latestVersion) {
Organization organization = new Organization();
organization.setName("org");
Module module = new Module();
module.setId(MODULE_ID);
module.setName("module");
module.setOrganization(organization);
module.setLatestVersion(latestVersion);
Expand Down
Loading