You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@causeway.apache.org by da...@apache.org on 2024/06/20 14:45:00 UTC

(causeway) 02/05: CAUSEWAY-3770: refactors ECTD, no functional changes (intended)

This is an automated email from the ASF dual-hosted git repository.

danhaywood pushed a commit to branch ESTUP2-3770
in repository https://gitbox.apache.org/repos/asf/causeway.git

commit ab9cdf8c9984e464b362147a129f4ecbc8f33be3
Author: Dan Haywood <da...@haywood-associates.co.uk>
AuthorDate: Thu Jun 20 13:56:51 2024 +0100

    CAUSEWAY-3770: refactors ECTD, no functional changes (intended)
---
 .../publish/EntityChangesPublisherDefault.java     |  13 +-
 .../changetracking/EntityChangeTrackerDefault.java | 270 ++++++++++++++-------
 .../changetracking/_ChangingEntitiesFactory.java   |  92 -------
 3 files changed, 188 insertions(+), 187 deletions(-)

diff --git a/core/runtimeservices/src/main/java/org/apache/causeway/core/runtimeservices/publish/EntityChangesPublisherDefault.java b/core/runtimeservices/src/main/java/org/apache/causeway/core/runtimeservices/publish/EntityChangesPublisherDefault.java
index c4fc5731df..3ce32c2242 100644
--- a/core/runtimeservices/src/main/java/org/apache/causeway/core/runtimeservices/publish/EntityChangesPublisherDefault.java
+++ b/core/runtimeservices/src/main/java/org/apache/causeway/core/runtimeservices/publish/EntityChangesPublisherDefault.java
@@ -92,11 +92,14 @@ public class EntityChangesPublisherDefault implements EntityChangesPublisher {
     // -- HELPER
 
     private Optional<EntityChanges> getPayload(final @NonNull HasEnlistedEntityChanges hasEnlistedEntityChanges) {
-        return enabledSubscribers.isEmpty()
-                ? Optional.empty()
-                : hasEnlistedEntityChanges.getEntityChanges(
-                        clockService.getClock().nowAsJavaSqlTimestamp(), // current time
-                        userService.currentUserNameElseNobody()); // current user
+        if (enabledSubscribers.isEmpty()) {
+            return Optional.empty();
+        }
+
+        return hasEnlistedEntityChanges.getEntityChanges(
+                clockService.getClock().nowAsJavaSqlTimestamp(), // current time
+                userService.currentUserNameElseNobody()          // current user
+        );
     }
 
     // x-ray support
diff --git a/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java b/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java
index 1b8e447b78..12302b2133 100644
--- a/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java
+++ b/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/EntityChangeTrackerDefault.java
@@ -21,7 +21,6 @@ package org.apache.causeway.persistence.commons.integration.changetracking;
 
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.UUID;
@@ -35,6 +34,13 @@ import javax.inject.Inject;
 import javax.inject.Named;
 import javax.inject.Provider;
 
+import org.apache.causeway.applib.jaxb.JavaSqlXMLGregorianCalendarMarshalling;
+import org.apache.causeway.core.metamodel.execution.InteractionInternal;
+
+import org.apache.causeway.schema.chg.v2.ChangesDto;
+import org.apache.causeway.schema.chg.v2.ObjectsDto;
+import org.apache.causeway.schema.common.v2.OidsDto;
+
 import org.springframework.beans.factory.annotation.Qualifier;
 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 import org.springframework.core.Ordered;
@@ -149,16 +155,52 @@ implements
     private final Map<PropertyChangeRecordId, PropertyChangeRecord> enlistedPropertyChangeRecordsById = _Maps.newLinkedHashMap();
 
     /**
-     * Contains pre- and post- values of every property of every object that actually changed. A lazy snapshot,
-     * triggered by internal call to {@link #snapshotPropertyChangeRecords()}.
+     * As used when {@link #enlistCreated(ManagedObject)} or {@link #enlistUpdating(ManagedObject, Function)}
+     */
+    private void addPropertyChangeRecordIfAbsent(PropertyChangeRecordId pcrId, PropertyChangeRecord pcr) {
+        if(containsPropertyChangeRecord(pcrId)) {
+            return;
+        }
+        enlistedPropertyChangeRecordsById.put(pcrId, pcr);
+    }
+    /**
+     * As used when {@link #enlistDeleting(ManagedObject)}.
+     */
+    private void computePropertyChangeRecordIfAbsent(PropertyChangeRecordId pcrId, Function<PropertyChangeRecordId, PropertyChangeRecord> propertyChangeRecordIdPropertyChangeRecordFunction) {
+        enlistedPropertyChangeRecordsById.computeIfAbsent(pcrId, propertyChangeRecordIdPropertyChangeRecordFunction);
+    }
+    private boolean containsPropertyChangeRecord(PropertyChangeRecordId pcrId) {
+        return enlistedPropertyChangeRecordsById.containsKey(pcrId);
+    }
+
+    /**
+     * Contains pre- and post- values of every property of every object that actually changed. A lazy snapshot.
      */
     private final _Lazy<Set<PropertyChangeRecord>> entityPropertyChangeRecordsForPublishing
-        = _Lazy.threadSafe(this::capturePostValuesAndDrain);
+        = _Lazy.of(() -> {
+        val records = enlistedPropertyChangeRecordsById.values().stream()
+                // set post values, which have been left empty up to now
+                .peek(rec -> {
+                    if(MmEntityUtils.getEntityState(rec.getEntity()).isTransientOrRemoved()) {
+                        rec.withPostValueSetToDeleted();
+                    } else {
+                        rec.withPostValueSetToCurrentElseUnknown();
+                    }
+                })
+                .filter(managedProperty-> shouldPublish(managedProperty.getPreAndPostValue()))
+                .collect(_Sets.toUnmodifiable());
+
+        enlistedPropertyChangeRecordsById.clear();
+
+        return records;
+        });
+
+
 
     /**
      * @implNote access to this {@link Map} must be thread-safe (insertion order preservation is not required)
      */
-    private final Map<Bookmark, EntityChangeKind> changeKindByEnlistedAdapter = _Maps.newConcurrentHashMap();
+    private final Map<Bookmark, EntityChangeKind> changeKindByEnlistedAdapter = _Maps.newHashMap();
 
     private final LongAdder numberEntitiesLoaded = new LongAdder();
     private final LongAdder entityChangeEventCount = new LongAdder();
@@ -173,13 +215,11 @@ implements
             log.info("EntityChangeTrackerDefault.destroy xactn={} interactionId={} thread={}", transactionCounter.get(), interactionId, Thread.currentThread().getName());
         }
 
-        clearEnlistedPropertyChangeRecordsById();
-        entityPropertyChangeRecordsForPublishing.clear();
-        changeKindByEnlistedAdapter.clear();
+        resetState();
+    }
 
-        numberEntitiesLoaded.reset();
-        entityChangeEventCount.reset();
-        persistentChangesEncountered.set(false);
+    private void resetState() {
+        resetState(numberEntitiesLoaded, entityChangeEventCount);
     }
 
 
@@ -192,53 +232,11 @@ implements
      *      and ensure that the lock is released only when the thread exits the synchronized block
      *      or method the same number of times it entered it.
      */
-    private void runThreadsafeAndSuppressAutoFlushIfRequired(final Runnable runnable) {
-        synchronized (enlistedPropertyChangeRecordsById) {
-            if (configuration.isSuppressAutoFlush()) {
-                FlushMgmt.suppressAutoFlush(runnable);
-            } else {
-                runnable.run();
-            }
-        }
-    }
-
-    Set<PropertyChangeRecord> snapshotPropertyChangeRecords() {
-        // this code path has side-effects, it locks the result for this transaction,
-        // such that cannot enlist on top of it
-        return entityPropertyChangeRecordsForPublishing.get();
-    }
-
-    /**
-     * Returns a defensive copy of the {@code changeKindByEnlistedAdapter} {@link Map}.
-     */
-    public Map<Bookmark, EntityChangeKind> snapshotChangeKindByEnlistedAdapter() {
-        return new HashMap<>(changeKindByEnlistedAdapter);
-    }
-
-    /**
-     * For any enlisted Object Properties collects those, that are meant for publishing,
-     * then clears enlisted objects.
-     *
-     * @implNote sets a lock on the {@code enlistedPropertyChangeRecordsById} {@link Map} until its drained and cleared
-     */
-    private Set<PropertyChangeRecord> capturePostValuesAndDrain() {
-        synchronized (enlistedPropertyChangeRecordsById) {
-
-            val records = enlistedPropertyChangeRecordsById.values().stream()
-                // set post values, which have been left empty up to now
-                .peek(rec -> {
-                    if(MmEntityUtils.getEntityState(rec.getEntity()).isTransientOrRemoved()) {
-                        rec.withPostValueSetToDeleted();
-                    } else {
-                        rec.withPostValueSetToCurrentElseUnknown();
-                    }
-                })
-                .filter(managedProperty-> shouldPublish(managedProperty.getPreAndPostValue()))
-                .collect(_Sets.toUnmodifiable());
-
-            enlistedPropertyChangeRecordsById.clear();
-
-            return records;
+    private void suppressAutoFlushIfRequired(final Runnable runnable) {
+        if (configuration.isSuppressAutoFlush()) {
+            FlushMgmt.suppressAutoFlush(runnable);
+        } else {
+            runnable.run();
         }
     }
 
@@ -273,21 +271,30 @@ implements
             _Xray.publish(this, interactionProviderProvider);
 
             log.debug("about to publish entity changes");
+
+            memoizePropertyChangeRecordsIfRequired();
+
             entityPropertyChangePublisher.publishChangedProperties();
             entityChangesPublisher.publishChangingEntities(this);
 
         } finally {
             log.debug("purging entity change records");
 
-            clearEnlistedPropertyChangeRecordsById();
-            entityPropertyChangeRecordsForPublishing.clear();
-
-            changeKindByEnlistedAdapter.clear();
-            entityChangeEventCount.reset();
-            numberEntitiesLoaded.reset();
+            resetState(entityChangeEventCount, numberEntitiesLoaded);
         }
     }
 
+    private void resetState(LongAdder entityChangeEventCount, LongAdder numberEntitiesLoaded) {
+        enlistedPropertyChangeRecordsById.clear();
+        entityPropertyChangeRecordsForPublishing.clear();
+
+        changeKindByEnlistedAdapter.clear();
+        entityChangeEventCount.reset();
+        numberEntitiesLoaded.reset();
+
+        persistentChangesEncountered.set(false);
+    }
+
     private void enableCommandPublishing() {
         val alreadySet = persistentChangesEncountered.getAndSet(true);
         if(!alreadySet) {
@@ -299,15 +306,104 @@ implements
     public Optional<EntityChanges> getEntityChanges(
             final java.sql.Timestamp timestamp,
             final String userName) {
-        return _ChangingEntitiesFactory.createChangingEntities(timestamp, userName, this);
+
+        // a defensive copy of
+        val changeKindByEnlistedAdapter = (Map<Bookmark, EntityChangeKind>) new HashMap<>(this.changeKindByEnlistedAdapter);
+        if(changeKindByEnlistedAdapter.isEmpty()) {
+            return Optional.empty();
+        }
+
+        final Interaction interaction = currentInteraction();
+        final int numberEntitiesLoaded1 = numberEntitiesLoaded();
+
+        // this code path has side-effects, it locks the result for this transaction,
+        // such that cannot enlist on top of it
+        final int numberEntityPropertiesModified = memoizePropertyChangeRecordsIfRequired().size();
+
+        val interactionId = interaction.getInteractionId();
+        final int nextEventSequence = ((InteractionInternal) interaction).getThenIncrementTransactionSequence();
+
+        // side-effect: it locks the result for this transaction,
+        // such that cannot enlist on top of it
+        val changingEntities = (EntityChanges) new _SimpleChangingEntities(
+                interactionId, nextEventSequence,
+                userName, timestamp,
+                numberEntitiesLoaded1,
+                numberEntityPropertiesModified,
+                () -> newDto(
+                        interactionId, nextEventSequence,
+                        userName, timestamp,
+                        numberEntitiesLoaded1,
+                        numberEntityPropertiesModified,
+                        changeKindByEnlistedAdapter));
+
+        return Optional.of(changingEntities);
     }
 
+    private Set<PropertyChangeRecord> memoizePropertyChangeRecordsIfRequired() {
+        return entityPropertyChangeRecordsForPublishing.get();
+    }
+
+    private static ChangesDto newDto(
+            final UUID interactionId, final int transactionSequenceNum,
+            final String userName, final java.sql.Timestamp completedAt,
+            final int numberEntitiesLoaded,
+            final int numberEntityPropertiesModified,
+            final Map<Bookmark, EntityChangeKind> changeKindByEnlistedEntity) {
+
+        val objectsDto = new ObjectsDto();
+        objectsDto.setCreated(new OidsDto());
+        objectsDto.setUpdated(new OidsDto());
+        objectsDto.setDeleted(new OidsDto());
+
+        changeKindByEnlistedEntity.forEach((bookmark, kind)->{
+            val oidDto = bookmark.toOidDto();
+            if(oidDto==null) {
+                return;
+            }
+            switch(kind) {
+                case CREATE:
+                    objectsDto.getCreated().getOid().add(oidDto);
+                    return;
+                case UPDATE:
+                    objectsDto.getUpdated().getOid().add(oidDto);
+                    return;
+                case DELETE:
+                    objectsDto.getDeleted().getOid().add(oidDto);
+                    return;
+            }
+        });
+
+        objectsDto.setLoaded(numberEntitiesLoaded);
+        objectsDto.setPropertiesModified(numberEntityPropertiesModified);
+
+        val changesDto = new ChangesDto();
+
+        changesDto.setMajorVersion("2");
+        changesDto.setMinorVersion("0");
+
+        changesDto.setInteractionId(interactionId.toString());
+        changesDto.setSequence(transactionSequenceNum);
+
+        changesDto.setUsername(userName);
+        changesDto.setCompletedAt(JavaSqlXMLGregorianCalendarMarshalling.toXMLGregorianCalendar(completedAt));
+
+        changesDto.setObjects(objectsDto);
+        return changesDto;
+    }
+
+
     @Override
     public Can<EntityPropertyChange> getPropertyChanges(
             final java.sql.Timestamp timestamp,
             final String userName,
             final TransactionId txId) {
-        return snapshotPropertyChangeRecords().stream()
+
+        // this code path has side-effects, it locks the result for this transaction,
+        // such that cannot enlist on top of it
+        Set<PropertyChangeRecord> propertyChangeRecords = memoizePropertyChangeRecordsIfRequired();
+
+        return propertyChangeRecords.stream()
                 .map(propertyChangeRecord -> propertyChangeRecord.toEntityPropertyChange(timestamp, userName, txId))
                 .collect(Can.toCan());
     }
@@ -365,9 +461,7 @@ implements
 
     // side-effect free, used by XRay
     long countPotentialPropertyChangeRecords() {
-        synchronized (enlistedPropertyChangeRecordsById) {
-            return enlistedPropertyChangeRecordsById.size();
-        }
+        return enlistedPropertyChangeRecordsById.size();
     }
 
     // -- ENTITY CHANGE TRACKING
@@ -383,15 +477,15 @@ implements
 
         log.debug("enlist entity's property changes for publishing {}", entity);
 
-        runThreadsafeAndSuppressAutoFlushIfRequired(() -> {
+        suppressAutoFlushIfRequired(() -> {
             enlistForChangeKindPublishing(entity, EntityChangeKind.CREATE);
 
             MmEntityUtils.streamPropertyChangeRecordIdsForChangePublishing(entity)
-                .filter(pcrId -> ! enlistedPropertyChangeRecordsById.containsKey(pcrId)) // only if not previously seen
-                .forEach(pcrId -> enlistedPropertyChangeRecordsById.put(pcrId, PropertyChangeRecord.ofNew(pcrId)));
+                .forEach(pcrId -> addPropertyChangeRecordIfAbsent(pcrId, PropertyChangeRecord.ofNew(pcrId)));
         });
     }
 
+
     @Override
     public void enlistUpdating(
             final ManagedObject entity,
@@ -403,9 +497,11 @@ implements
             return;
         }
 
-        log.debug("enlist entity's property changes for publishing {}", entity);
+        if(log.isDebugEnabled()) {
+            log.debug("enlist entity's property changes for publishing {}", entity);
+        }
 
-        runThreadsafeAndSuppressAutoFlushIfRequired(() -> {
+        suppressAutoFlushIfRequired(() -> {
             // we call this come what may;
             // additional properties may now have been changed, and the changeKind for publishing might also be modified
             enlistForChangeKindPublishing(entity, EntityChangeKind.UPDATE);
@@ -418,19 +514,16 @@ implements
                 // provided by ORM
                 ormPropertyChangeRecords
                     .stream()
-                    .filter(pcr -> ! enlistedPropertyChangeRecordsById.containsKey(pcr.getId())) // only if not previously seen
-                    .forEach(pcr -> enlistedPropertyChangeRecordsById.put(pcr.getId(), pcr));
+                    .forEach(pcr -> addPropertyChangeRecordIfAbsent(pcr.getId(), pcr));
             } else {
                 // home-grown approach
                 MmEntityUtils.streamPropertyChangeRecordIdsForChangePublishing(entity)
-                    .filter(pcrId -> ! enlistedPropertyChangeRecordsById.containsKey(pcrId)) // only if not previously seen
-                    .map(pcrId -> enlistedPropertyChangeRecordsById.put(pcrId, PropertyChangeRecord.ofCurrent(pcrId)))
-                    .filter(Objects::nonNull)   // shouldn't happen, just keeping compiler happy
-                    .forEach(PropertyChangeRecord::withPreValueSetToCurrentElseUnknown);
+                    .forEach(pcrId -> addPropertyChangeRecordIfAbsent(pcrId, PropertyChangeRecord.ofCurrent(pcrId)));
             }
         });
     }
 
+
     @Override
     public void enlistDeleting(final ManagedObject entity) {
 
@@ -438,14 +531,17 @@ implements
 
         if (isEntityExcludedForChangePublishing(entity)) return;
 
-        runThreadsafeAndSuppressAutoFlushIfRequired(() -> {
+        suppressAutoFlushIfRequired(() -> {
             final boolean enlisted = enlistForChangeKindPublishing(entity, EntityChangeKind.DELETE);
             if(enlisted) {
-                log.debug("enlist entity's property changes for publishing {}", entity);
+                if(log.isDebugEnabled()) {
+                    log.debug("enlist entity's property changes for publishing {}", entity);
+                }
 
                 MmEntityUtils.streamPropertyChangeRecordIdsForChangePublishing(entity)
-                    .forEach(pcrId -> enlistedPropertyChangeRecordsById
-                        .computeIfAbsent(pcrId, id -> PropertyChangeRecord.ofDeleting(id)));
+                    .forEach(pcrId -> {
+                        computePropertyChangeRecordIfAbsent(pcrId, PropertyChangeRecord::ofDeleting);
+                    });
             }
         });
     }
@@ -474,12 +570,6 @@ implements
 
     // -- HELPER
 
-    private void clearEnlistedPropertyChangeRecordsById() {
-        synchronized (enlistedPropertyChangeRecordsById) {
-            enlistedPropertyChangeRecordsById.clear();
-        }
-    }
-
     /**
      * SPI to allow this service to be configured through different mechanisms.
      */
diff --git a/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/_ChangingEntitiesFactory.java b/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/_ChangingEntitiesFactory.java
index 3001014492..89103c36ed 100644
--- a/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/_ChangingEntitiesFactory.java
+++ b/persistence/commons/src/main/java/org/apache/causeway/persistence/commons/integration/changetracking/_ChangingEntitiesFactory.java
@@ -20,7 +20,6 @@
 package org.apache.causeway.persistence.commons.integration.changetracking;
 
 import java.util.Map;
-import java.util.Optional;
 import java.util.UUID;
 
 import org.apache.causeway.applib.annotation.EntityChangeKind;
@@ -37,100 +36,9 @@ import lombok.val;
 
 final class _ChangingEntitiesFactory {
 
-    public static Optional<EntityChanges> createChangingEntities(
-            final java.sql.Timestamp completedAt,
-            final String userName,
-            final EntityChangeTrackerDefault entityChangeTracker) {
-
-        val changeKindByEnlistedAdapter = entityChangeTracker.snapshotChangeKindByEnlistedAdapter();
-        if(changeKindByEnlistedAdapter.isEmpty()) return Optional.empty();
-
-        val changingEntities = newChangingEntities(
-                completedAt,
-                userName,
-                entityChangeTracker.currentInteraction(),
-                entityChangeTracker.numberEntitiesLoaded(),
-                // side-effect: it locks the result for this transaction,
-                // such that cannot enlist on top of it
-                entityChangeTracker.snapshotPropertyChangeRecords().size(),
-                changeKindByEnlistedAdapter);
-
-        return Optional.of(changingEntities);
-    }
-
     // -- HELPER
 
-    private static EntityChanges newChangingEntities(
-            final java.sql.Timestamp completedAt,
-            final String userName,
-            final Interaction interaction,
-            final int numberEntitiesLoaded,
-            final int numberEntityPropertiesModified,
-            final Map<Bookmark, EntityChangeKind> changeKindByEnlistedAdapter) {
-
-        val interactionId = interaction.getInteractionId();
-        final int nextEventSequence = ((InteractionInternal) interaction).getThenIncrementTransactionSequence();
-
-        return new _SimpleChangingEntities(
-                    interactionId, nextEventSequence,
-                    userName, completedAt,
-                    numberEntitiesLoaded,
-                    numberEntityPropertiesModified,
-                    ()->newDto(
-                            interactionId, nextEventSequence,
-                            userName, completedAt,
-                            numberEntitiesLoaded,
-                            numberEntityPropertiesModified,
-                            changeKindByEnlistedAdapter));
-    }
-
-    private static ChangesDto newDto(
-            final UUID interactionId, final int transactionSequenceNum,
-            final String userName, final java.sql.Timestamp completedAt,
-            final int numberEntitiesLoaded,
-            final int numberEntityPropertiesModified,
-            final Map<Bookmark, EntityChangeKind> changeKindByEnlistedEntity) {
-
-        val objectsDto = new ObjectsDto();
-        objectsDto.setCreated(new OidsDto());
-        objectsDto.setUpdated(new OidsDto());
-        objectsDto.setDeleted(new OidsDto());
-
-        changeKindByEnlistedEntity.forEach((bookmark, kind)->{
-            val oidDto = bookmark.toOidDto();
-            if(oidDto==null) {
-                return;
-            }
-            switch(kind) {
-            case CREATE:
-                objectsDto.getCreated().getOid().add(oidDto);
-                return;
-            case UPDATE:
-                objectsDto.getUpdated().getOid().add(oidDto);
-                return;
-            case DELETE:
-                objectsDto.getDeleted().getOid().add(oidDto);
-                return;
-            }
-        });
-
-        objectsDto.setLoaded(numberEntitiesLoaded);
-        objectsDto.setPropertiesModified(numberEntityPropertiesModified);
-
-        val changesDto = new ChangesDto();
-
-        changesDto.setMajorVersion("2");
-        changesDto.setMinorVersion("0");
-
-        changesDto.setInteractionId(interactionId.toString());
-        changesDto.setSequence(transactionSequenceNum);
-
-        changesDto.setUsername(userName);
-        changesDto.setCompletedAt(JavaSqlXMLGregorianCalendarMarshalling.toXMLGregorianCalendar(completedAt));
 
-        changesDto.setObjects(objectsDto);
-        return changesDto;
-    }
 
 
 }