Paperless / rebuild
Course 2 28ef273

Transactions, versions, and locking

Snapshot 28ef273Markdown

Assessment review: Do not generalize the document concurrency safeguards to all features. Document-type updates replace a stale version with a fresh one and can overwrite intervening changes. See F2.

A correct update must remain correct while another request modifies the same data. Immutable model snapshots make changes explicit, but do not by themselves prevent stale writes.

Service-owned transactions

Service implementations carry class-level @Transactional; read paths override it with readOnly=true. Adapters participate in the caller's transaction. With Spring's default proxy mode, calls must enter through the proxy for annotations to take effect; a self-call does not activate a new method's transactional settings. Default rollback rules cover RuntimeException and Error, not every Java checked exception. Kotlin's lack of checked-exception syntax does not change that classification. See Spring transaction annotations.

Preserve the loaded version

AbstractEntity carries shared UUID identity, timestamps, and @Version. Domain models retain the loaded version. Entity mapping must carry it back on writes. Replacing it with a default loses the concurrency information associated with the read. Migration V2 adds/backfills shared properties for existing databases; inspect both schema and mapping when introducing a shared base entity.

Trace the sharing race

updateDocument first loads a snapshot. It computes source and requested team IDs, locks teams in sorted order, resolves the actor's roles, and refreshes the document through the adapter. refreshUnchanged compares version, owner ID, and team ID against the initial snapshot. A concurrent deletion or changed sharing state becomes a conflict rather than allowing a write authorized against stale data.

Sorted lock acquisition reduces inconsistent lock-order risk for operations following the same convention. It is not proof that every possible transaction is deadlock-free. Optimistic versions detect competing writes; pessimistic locks coordinate critical membership/team operations. They serve related but different purposes.

Flush is not commit

An explicit flush() surfaces pending database failures before later steps continue. The encompassing transaction can still roll back. Deleting a physical file immediately after flush would be premature; the next chapter follows the completion callbacks.

Practice

Write a two-request timeline: A reads version 3; B changes sharing and commits; A acquires locks and refreshes. Explain which comparison rejects A. Repeat with a concurrent deletion. Compare this with the final database optimistic-lock check.

Run DomainVersionPersistenceTest and the adapter tests in a practice checkout. Add a genuine database-backed race test if you need stronger evidence than the existing deterministic checks; a mocked repository cannot establish database lock behavior.

Verification gate

Explain why preserving version is necessary but not the whole authorization race solution. Distinguish transaction, flush, commit, rollback, and file-system side effects. State the isolation/locking assumptions you would verify against PostgreSQL.

Read the implementation

Complete source walkthrough

Read these pinned files alongside the explanation above. These are the inspected implementation, not the capstone solution.

AbstractEntity.kt

Browse source

package at.fhtw.swen3.paperless.common.entity

import jakarta.persistence.Column
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
import jakarta.persistence.MappedSuperclass
import jakarta.persistence.Version
import org.hibernate.annotations.CreationTimestamp
import org.hibernate.annotations.UpdateTimestamp
import java.time.Instant
import java.util.UUID

@MappedSuperclass
abstract class AbstractEntity(
    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    val id: UUID? = null,
    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    val createdAt: Instant = Instant.now(),
    @UpdateTimestamp
    @Column(nullable = false)
    var updatedAt: Instant = createdAt,
    @Version
    @Column(nullable = false)
    var version: Long = 0
)

V2__shared_entity_properties.sql

Browse source

-- Add shared audit and optimistic-locking fields without changing existing IDs.
ALTER TABLE users ADD COLUMN version bigint NOT NULL DEFAULT 0;
ALTER TABLE teams ADD COLUMN version bigint NOT NULL DEFAULT 0;
ALTER TABLE document_types ADD COLUMN version bigint NOT NULL DEFAULT 0;
ALTER TABLE team_members ADD COLUMN version bigint NOT NULL DEFAULT 0;

ALTER TABLE document_types ADD COLUMN created_at timestamp(6) with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE document_types ADD COLUMN updated_at timestamp(6) with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE team_members ADD COLUMN created_at timestamp(6) with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP;
ALTER TABLE team_members ADD COLUMN updated_at timestamp(6) with time zone NOT NULL DEFAULT CURRENT_TIMESTAMP;

UPDATE users SET updated_at = created_at WHERE updated_at IS NULL;
UPDATE teams SET updated_at = created_at WHERE updated_at IS NULL;
ALTER TABLE users ALTER COLUMN updated_at SET NOT NULL;
ALTER TABLE teams ALTER COLUMN updated_at SET NOT NULL;

JpaDocumentPersistence.kt

Browse source

package at.fhtw.swen3.paperless.document.persistence

import at.fhtw.swen3.paperless.document.model.Document
import at.fhtw.swen3.paperless.document.entity.DocumentEntity
import at.fhtw.swen3.paperless.document.persistence.mapper.DocumentEntityMapper
import at.fhtw.swen3.paperless.document.persistence.repository.DocumentRepository
import at.fhtw.swen3.paperless.documenttype.entity.DocumentTypeEntity
import at.fhtw.swen3.paperless.team.entity.TeamEntity
import at.fhtw.swen3.paperless.user.entity.UserEntity
import jakarta.persistence.EntityManager
import jakarta.persistence.EntityNotFoundException
import jakarta.persistence.OptimisticLockException
import java.util.Optional
import java.util.UUID
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Repository

@Repository
class JpaDocumentPersistence(
    private val repository: DocumentRepository,
    private val entityManager: EntityManager,
    private val documentEntityMapper: DocumentEntityMapper
) : DocumentPersistence {

    override fun findById(id: UUID): Optional<Document> = repository.findById(id).map(documentEntityMapper::toModel)

    override fun findOwnerOnlyDocuments(ownerId: UUID, documentTypeId: UUID?, pageable: Pageable): Page<Document> =
        repository.findOwnerOnlyDocuments(ownerId, documentTypeId, pageable).map(documentEntityMapper::toModel)

    override fun findVisibleDocuments(
        ownerId: UUID, teamIds: Set<UUID>, documentTypeId: UUID?, pageable: Pageable
    ): Page<Document> = repository.findVisibleDocuments(ownerId, teamIds, documentTypeId, pageable)
        .map(documentEntityMapper::toModel)

    override fun findOwnerOnlyDocuments(ownerId: UUID): List<Document> =
        repository.findOwnerOnlyDocuments(ownerId).map(documentEntityMapper::toModel)

    override fun findVisibleDocuments(ownerId: UUID, teamIds: Set<UUID>): List<Document> =
        repository.findVisibleDocuments(ownerId, teamIds).map(documentEntityMapper::toModel)

    override fun save(document: Document): Document {
        val references = DocumentEntityMapper.References(
            owner = entityManager.getReference(UserEntity::class.java, document.ownerId),
            team = document.teamId?.let { entityManager.getReference(TeamEntity::class.java, it) },
            documentType = document.documentType?.let {
                entityManager.getReference(DocumentTypeEntity::class.java, requireNotNull(it.id))
            }
        )
        val entity = documentEntityMapper.toEntity(document, references)

        return documentEntityMapper.toModel(repository.save(entity))
    }

    override fun refreshUnchanged(document: Document): Document {
        val entity = repository.findById(requireNotNull(document.id)).orElseThrow {
            OptimisticLockException("Document was deleted concurrently")
        }
        try {
            entityManager.refresh(entity)
        } catch (exception: EntityNotFoundException) {
            throw OptimisticLockException("Document was deleted concurrently", exception)
        }
        val changed = entity.version != document.version || entity.team?.id != document.teamId ||
            entity.owner.id != document.ownerId
        if (changed) {
            throw OptimisticLockException("Document sharing changed concurrently")
        }

        return documentEntityMapper.toModel(entity)
    }

    override fun delete(document: Document) {
        repository.delete(entityManager.getReference(DocumentEntity::class.java, requireNotNull(document.id)))
    }

    override fun flush() = entityManager.flush()
}

DomainVersionPersistenceTest.kt

Browse source

package at.fhtw.swen3.paperless.common.entity

import at.fhtw.swen3.paperless.common.mapper.MappingConverters

import at.fhtw.swen3.paperless.documenttype.model.DocumentType
import at.fhtw.swen3.paperless.documenttype.persistence.DocumentTypePersistence
import at.fhtw.swen3.paperless.documenttype.persistence.JpaDocumentTypePersistence
import at.fhtw.swen3.paperless.documenttype.persistence.mapper.DocumentTypeEntityMapperImpl

import at.fhtw.swen3.paperless.team.model.Team
import at.fhtw.swen3.paperless.team.persistence.JpaTeamPersistence
import at.fhtw.swen3.paperless.team.persistence.mapper.TeamEntityMapperImpl

import at.fhtw.swen3.paperless.team.persistence.TeamPersistence
import at.fhtw.swen3.paperless.user.model.User
import at.fhtw.swen3.paperless.user.persistence.JpaUserPersistence
import at.fhtw.swen3.paperless.user.persistence.mapper.UserEntityMapperImpl

import at.fhtw.swen3.paperless.user.persistence.UserPersistence
import jakarta.persistence.EntityManager
import java.time.Instant
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThatThrownBy
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest
import org.springframework.context.annotation.Import
import org.springframework.dao.OptimisticLockingFailureException

@DataJpaTest
@Import(
    JpaUserPersistence::class,
    JpaTeamPersistence::class,
    JpaDocumentTypePersistence::class,
    UserEntityMapperImpl::class,
    TeamEntityMapperImpl::class,
    DocumentTypeEntityMapperImpl::class,
    MappingConverters::class
)
class DomainVersionPersistenceTest(@Autowired private val entityManager: EntityManager) {
    @Autowired private lateinit var users: UserPersistence
    @Autowired private lateinit var teams: TeamPersistence
    @Autowired private lateinit var types: DocumentTypePersistence

    @Test
    fun user_updates_preserve_versions_and_reject_stale_models_ok() {
        // given
        val saved = users.save(User(null, "version-user", "unused", Instant.now(), null))
        flushAndClear()
        val id = requireNotNull(saved.id)
        val initial = users.findById(id).orElseThrow()

        // when
        users.save(initial.copy(username = "version-user-1"))
        flushAndClear()
        val updated = users.findById(id).orElseThrow()
        users.save(updated.copy(username = "version-user-2"))
        flushAndClear()

        // then
        assertThat(updated.version).isEqualTo(initial.version + 1)
        assertThat(users.findById(id).orElseThrow().version).isEqualTo(initial.version + 2)
        assertThatThrownBy { users.save(initial.copy(username = "stale-user")) }
            .isInstanceOf(OptimisticLockingFailureException::class.java)
    }

    @Test
    fun team_updates_preserve_versions_and_reject_stale_models_ok() {
        // given
        val saved = teams.save(Team(null, "Version team", null, Instant.now(), null, UUID.randomUUID()))
        flushAndClear()
        val id = requireNotNull(saved.id)
        val initial = teams.findById(id).orElseThrow()

        // when
        teams.save(initial.copy(name = "Version team 1"))
        flushAndClear()
        val updated = teams.findById(id).orElseThrow()
        teams.save(updated.copy(name = "Version team 2"))
        flushAndClear()

        // then
        assertThat(updated.version).isEqualTo(initial.version + 1)
        assertThat(teams.findById(id).orElseThrow().version).isEqualTo(initial.version + 2)
        assertThatThrownBy { teams.save(initial.copy(name = "Stale team")) }
            .isInstanceOf(OptimisticLockingFailureException::class.java)
    }

    @Test
    fun document_type_updates_preserve_versions_and_reject_stale_models_ok() {
        // given
        val saved = types.save(DocumentType(null, "Version type", null))
        flushAndClear()
        val id = requireNotNull(saved.id)
        val initial = types.findById(id).orElseThrow()

        // when
        types.save(initial.copy(name = "Version type 1"))
        flushAndClear()
        val updated = types.findById(id).orElseThrow()
        types.save(updated.copy(name = "Version type 2"))
        flushAndClear()

        // then
        assertThat(updated.version).isEqualTo(initial.version + 1)
        assertThat(types.findById(id).orElseThrow().version).isEqualTo(initial.version + 2)
        assertThatThrownBy { types.save(initial.copy(name = "Stale type")) }
            .isInstanceOf(OptimisticLockingFailureException::class.java)
    }

    private fun flushAndClear() {
        entityManager.flush()
        entityManager.clear()
    }
}
Ready to move on?

Complete the practice and verification gate first.

Search chapters, reference and source filenames.