Skip to content

Commit

Permalink
fix: Handle firing delete events twice
Browse files Browse the repository at this point in the history
  • Loading branch information
jamespfaulkner committed Nov 2, 2023
1 parent 6647bc7 commit 46f3e77
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ private <K extends Entity.Key<S>, S extends Specification> Entity<K, S> update(S
}

private <K extends Entity.Key<S>, S extends Specification> Entity<K, S> delete(SpecificationDeletionEvent<K, S> event) {
val oldEntity = (Entity<K, S>) getExistingEntity(event.getKey());
val oldEntity = (Entity<K, S>) getPossiblyDeletedEntity(event.getKey());
entities.put(event.getKey(), deleted(oldEntity));
log.debug("Deleted entity for {}", event.getKey());
return oldEntity;
Expand All @@ -108,6 +108,24 @@ private <K extends Entity.Key<S>, S extends Specification> Entity<K, S> delete(S
return oldEntity;
}

/**
* There is a chance the entity will have already been deleted.
*/
private Entity<?, ?> getPossiblyDeletedEntity(Entity.Key<?> key) {
val stateValue = Optional.ofNullable(entities.get(key));
stateValue.ifPresent(it -> {
if (it.deleted) {
log.debug("Found deleted entity for key={}", key);
} else {
log.debug("Found entity for key={}", key);
}
}
);
return stateValue
.map(it -> it.entity)
.orElse(null);
}

private Entity<?, ?> getExistingEntity(Entity.Key<?> key) {
return Optional.ofNullable(entities.get(key))
.filter(it -> !it.deleted)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,25 @@ public void deleteSpecificationEvent() {
assertThat(entities, hasEntry(key, deleted(entity.withStatus(oldStatus))));
}

@Test
public void doubleDeleteSpecificationEvent() {
val previousEntity = underTest.update(specificationEvent);

assertThat(previousEntity, is(nullValue()));
assertThat(entities, is(aMapWithSize(1)));
assertThat(entities, hasEntry(key, existing(entity.withStatus(oldStatus))));

val deletedEntity = underTest.update(specificationDeletionEvent);
assertThat(deletedEntity, is(entity.withStatus(oldStatus)));
assertThat(entities, is(aMapWithSize(1)));
assertThat(entities, hasEntry(key, deleted(entity.withStatus(oldStatus))));

val doubleDeletedEntity = underTest.update(specificationDeletionEvent);
assertThat(doubleDeletedEntity, is(entity.withStatus(oldStatus)));
assertThat(entities, is(aMapWithSize(1)));
assertThat(entities, hasEntry(key, deleted(entity.withStatus(oldStatus))));
}

@Test
public void deleteStatusEvent() {
entities.put(key, existing(oldEntity));
Expand Down

0 comments on commit 46f3e77

Please sign in to comment.