Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

INC-1147: Generically typed domain event #404

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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 @@ -62,7 +62,7 @@ class IncentiveLevelAuditedService(
IncentivesDomainEventType.INCENTIVE_LEVEL_CHANGED,
"An incentive level has been changed: $levelCode",
occurredAt = LocalDateTime.now(clock),
AdditionalInformation(
IncentiveLevelRef(
incentiveLevel = levelCode,
),
)
Expand All @@ -73,6 +73,9 @@ class IncentiveLevelAuditedService(
IncentivesDomainEventType.INCENTIVE_LEVELS_REORDERED,
"Incentive levels have been re-ordered",
occurredAt = LocalDateTime.now(clock),
additionalInformation = null,
)
}
}

data class IncentiveLevelRef(val incentiveLevel: String)
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@ class PrisonIncentiveLevelAuditedService(
IncentivesDomainEventType.INCENTIVE_PRISON_LEVEL_CHANGED,
"Incentive level (${prisonIncentiveLevel.levelCode}) in prison ${prisonIncentiveLevel.prisonId} has been updated",
occurredAt = LocalDateTime.now(clock),
AdditionalInformation(
PrisonIncentiveLevelRef(
incentiveLevel = prisonIncentiveLevel.levelCode,
prisonId = prisonIncentiveLevel.prisonId,
),
)
}
}

data class PrisonIncentiveLevelRef(val incentiveLevel: String, val prisonId: String)
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package uk.gov.justice.digital.hmpps.incentivesapi.service

import com.fasterxml.jackson.core.type.TypeReference
import com.fasterxml.jackson.databind.ObjectMapper
import kotlinx.coroutines.runBlocking
import org.slf4j.Logger
Expand All @@ -22,7 +23,7 @@ class PrisonOffenderEventListener(
val eventType = messageAttributes.eventType.Value
log.info("Received message $message, type $eventType")

val hmppsDomainEvent = mapper.readValue(message, HMPPSDomainEvent::class.java)
val hmppsDomainEvent = mapper.readValue(message, object : TypeReference<HMPPSDomainEvent<AdditionalInformation>>() {})
when (eventType) {
"prisoner-offender-search.prisoner.received", "prison-offender-events.prisoner.merged" -> {
prisonerIepLevelReviewService.processOffenderEvent(hmppsDomainEvent)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,42 +182,47 @@ class PrisonerIepLevelReviewService(
suspend fun getReviewById(id: Long): IepDetail =
prisonerIepLevelRepository.findById(id)?.toIepDetail(incentiveLevelService.getAllIncentiveLevelsMapByCode()) ?: throw NoDataFoundException(id)

suspend fun processOffenderEvent(prisonOffenderEvent: HMPPSDomainEvent) =
when (prisonOffenderEvent.additionalInformation?.reason) {
suspend fun processOffenderEvent(prisonOffenderEvent: HMPPSDomainEvent<AdditionalInformation>) =
when (prisonOffenderEvent.additionalInformation.reason) {
"NEW_ADMISSION" -> createIepForReceivedPrisoner(prisonOffenderEvent, ReviewType.INITIAL)
// NOTE: This may NOT be a recall. Someone could be readmitted back to prison for a number of other reasons (e.g. remands)
"READMISSION" -> createIepForReceivedPrisoner(prisonOffenderEvent, ReviewType.READMISSION)
"TRANSFERRED" -> createIepForReceivedPrisoner(prisonOffenderEvent, ReviewType.TRANSFER)
"MERGE" -> mergedPrisonerDetails(prisonOffenderEvent)
else -> {
log.debug("Ignoring prisonOffenderEvent with reason ${prisonOffenderEvent.additionalInformation?.reason}")
log.debug("Ignoring prisonOffenderEvent with reason ${prisonOffenderEvent.additionalInformation.reason}")
}
}

@Transactional
suspend fun processPrisonerAlertsUpdatedEvent(prisonOffenderEvent: HMPPSDomainEvent) {
val acctAdded: Boolean = prisonOffenderEvent.additionalInformation?.alertsAdded
suspend fun processPrisonerAlertsUpdatedEvent(prisonOffenderEvent: HMPPSDomainEvent<AdditionalInformation>) {
val acctAdded: Boolean = prisonOffenderEvent.additionalInformation.alertsAdded
?.contains(PrisonerAlert.ACCT_ALERT_CODE) == true
val acctRemoved: Boolean = prisonOffenderEvent.additionalInformation?.alertsRemoved
val acctRemoved: Boolean = prisonOffenderEvent.additionalInformation.alertsRemoved
?.contains(PrisonerAlert.ACCT_ALERT_CODE) == true

if (acctAdded || acctRemoved) {
updateNextReviewDate(prisonOffenderEvent)
} else {
log.debug("Ignoring 'prisoner-offender-search.prisoner.alerts-updated' event, No ACCT alerts added/removed: prisonerNumber = ${prisonOffenderEvent.additionalInformation?.nomsNumber}, alertsAdded = ${prisonOffenderEvent.additionalInformation?.alertsAdded}, alertsRemoved = ${prisonOffenderEvent.additionalInformation?.alertsRemoved}")
log.debug(
"Ignoring 'prisoner-offender-search.prisoner.alerts-updated' event, " +
"No ACCT alerts added/removed: prisonerNumber = ${prisonOffenderEvent.additionalInformation.nomsNumber}, " +
"alertsAdded = ${prisonOffenderEvent.additionalInformation.alertsAdded}, " +
"alertsRemoved = ${prisonOffenderEvent.additionalInformation.alertsRemoved}",
)
}
}

private suspend fun updateNextReviewDate(prisonOffenderEvent: HMPPSDomainEvent) {
prisonOffenderEvent.additionalInformation?.bookingId?.let { bookingId ->
private suspend fun updateNextReviewDate(prisonOffenderEvent: HMPPSDomainEvent<AdditionalInformation>) {
prisonOffenderEvent.additionalInformation.bookingId?.let { bookingId ->
nextReviewDateUpdaterService.update(bookingId)
} ?: run {
log.error("Could not update next review date: bookingId null for prisonOffenderEvent: $prisonOffenderEvent")
}
}

private suspend fun createIepForReceivedPrisoner(prisonOffenderEvent: HMPPSDomainEvent, reviewType: ReviewType) {
prisonOffenderEvent.additionalInformation?.nomsNumber?.let {
private suspend fun createIepForReceivedPrisoner(prisonOffenderEvent: HMPPSDomainEvent<AdditionalInformation>, reviewType: ReviewType) {
prisonOffenderEvent.additionalInformation.nomsNumber?.let {
val prisonerInfo = prisonApiService.getPrisonerInfo(it, true)
val iepLevel = getIepLevelForReviewType(prisonerInfo, reviewType)
val comment = getReviewCommentForEvent(prisonOffenderEvent)
Expand Down Expand Up @@ -289,7 +294,7 @@ class PrisonerIepLevelReviewService(
}
}

private fun getReviewCommentForEvent(prisonOffenderEvent: HMPPSDomainEvent) = when (prisonOffenderEvent.additionalInformation?.reason) {
private fun getReviewCommentForEvent(prisonOffenderEvent: HMPPSDomainEvent<AdditionalInformation>) = when (prisonOffenderEvent.additionalInformation.reason) {
"NEW_ADMISSION", "READMISSION" -> "Default level assigned on arrival"
"TRANSFERRED" -> "Level transferred from previous establishment"
else -> prisonOffenderEvent.description
Expand Down Expand Up @@ -395,8 +400,8 @@ class PrisonerIepLevelReviewService(
}

@Transactional
suspend fun mergedPrisonerDetails(prisonerMergeEvent: HMPPSDomainEvent) {
val removedPrisonerNumber = prisonerMergeEvent.additionalInformation?.removedNomsNumber!!
suspend fun mergedPrisonerDetails(prisonerMergeEvent: HMPPSDomainEvent<AdditionalInformation>) {
val removedPrisonerNumber = prisonerMergeEvent.additionalInformation.removedNomsNumber!!
val remainingPrisonerNumber = prisonerMergeEvent.additionalInformation.nomsNumber!!
log.info("Processing merge event: Prisoner Number Merge $removedPrisonerNumber -> $remainingPrisonerNumber")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ class SnsService(hmppsQueueService: HmppsQueueService, private val objectMapper:
}
private val domaineventsTopicClient by lazy { domaineventsTopic.snsClient }

fun publishDomainEvent(
fun <T> publishDomainEvent(
eventType: IncentivesDomainEventType,
description: String,
occurredAt: LocalDateTime,
additionalInformation: AdditionalInformation? = null,
additionalInformation: T? = null,
) {
publishToDomainEventsTopic(
HMPPSDomainEvent(
Expand All @@ -41,7 +41,7 @@ class SnsService(hmppsQueueService: HmppsQueueService, private val objectMapper:
)
}

private fun publishToDomainEventsTopic(payload: HMPPSDomainEvent) {
private fun <T> publishToDomainEventsTopic(payload: HMPPSDomainEvent<T>) {
log.debug("Event {} for id {}", payload.eventType, payload.additionalInformation)
domaineventsTopicClient.publish(
PublishRequest(domaineventsTopic.arn, objectMapper.writeValueAsString(payload))
Expand All @@ -64,20 +64,18 @@ data class AdditionalInformation(
val bookingId: Long? = null,
val alertsAdded: List<String>? = null,
val alertsRemoved: List<String>? = null,
val incentiveLevel: String? = null,
val prisonId: String? = null,
)

data class HMPPSDomainEvent(
data class HMPPSDomainEvent<T>(
val eventType: String? = null,
val additionalInformation: AdditionalInformation?,
val additionalInformation: T,
val version: String,
val occurredAt: String,
val description: String,
) {
constructor(
eventType: String,
additionalInformation: AdditionalInformation?,
additionalInformation: T,
occurredAt: Instant,
description: String,
) : this(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import uk.gov.justice.digital.hmpps.incentivesapi.jpa.repository.PrisonIncentive
import uk.gov.justice.digital.hmpps.incentivesapi.service.AuditEvent
import uk.gov.justice.digital.hmpps.incentivesapi.service.HMPPSDomainEvent
import uk.gov.justice.digital.hmpps.incentivesapi.service.HMPPSMessage
import uk.gov.justice.digital.hmpps.incentivesapi.service.IncentiveLevelRef
import uk.gov.justice.digital.hmpps.incentivesapi.service.PrisonIncentiveLevelRef
import java.time.Clock
import java.time.Instant
import java.time.LocalDateTime
Expand Down Expand Up @@ -76,27 +78,31 @@ class IncentiveLevelResourceTestBase : SqsIntegrationTestBase() {
assertThat(queueSize).isEqualTo(0)
}

protected fun assertDomainEventSent(eventType: String): HMPPSDomainEvent {
protected val anyDomainEvent = object : TypeReference<HMPPSDomainEvent<Any?>>() {}
protected val incentiveLevelDomainEvent = object : TypeReference<HMPPSDomainEvent<IncentiveLevelRef>>() {}
protected val prisonIncentiveLevelDomainEvent = object : TypeReference<HMPPSDomainEvent<PrisonIncentiveLevelRef>>() {}

protected fun <T> assertDomainEventSent(eventType: String, typeReference: TypeReference<HMPPSDomainEvent<T>>): HMPPSDomainEvent<T> {
val sqsClient = incentivesQueue.sqsClient
val queueSize = sqsClient.getApproxQueueSize(testDomainEventQueueUrl!!)
assertThat(queueSize).isEqualTo(1)

val body = sqsClient.receiveMessage(testDomainEventQueueUrl).messages[0].body
val (message, attributes) = objectMapper.readValue(body, HMPPSMessage::class.java)
assertThat(attributes.eventType.Value).isEqualTo(eventType)
val domainEvent = objectMapper.readValue(message, HMPPSDomainEvent::class.java)
val domainEvent = objectMapper.readValue(message, typeReference)
assertThat(domainEvent.eventType).isEqualTo(eventType)

return domainEvent
}

protected fun getPublishedDomainEvents(): List<HMPPSDomainEvent> {
protected fun getPublishedDomainEvents(): List<HMPPSDomainEvent<Map<String, *>>> {
Copy link
Contributor Author

@ushkarev ushkarev Apr 4, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Map<String, *> is an effective super set of IncentiveLevelRef and PrisonIncentiveLevelRef or any other non-null additional information structure

val sqsClient = incentivesQueue.sqsClient
val request = ReceiveMessageRequest(testDomainEventQueueUrl).withMaxNumberOfMessages(10)
return sqsClient.receiveMessage(request).messages
.map {
val (message) = objectMapper.readValue(it.body, HMPPSMessage::class.java)
objectMapper.readValue(message, HMPPSDomainEvent::class.java)
objectMapper.readValue(message, object : TypeReference<HMPPSDomainEvent<Map<String, *>>>() {})
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -186,9 +186,9 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
assertThat(prisonIncentiveLevelRepository.count()).isEqualTo(0)
}

assertDomainEventSent("incentives.level.changed").let {
assertDomainEventSent("incentives.level.changed", incentiveLevelDomainEvent).let {
assertThat(it.description).isEqualTo("An incentive level has been changed: EN4")
assertThat(it.additionalInformation?.incentiveLevel).isEqualTo("EN4")
assertThat(it.additionalInformation.incentiveLevel).isEqualTo("EN4")
}
assertAuditMessageSentWithMap("INCENTIVE_LEVEL_ADDED").let {
assertThat(it["code"]).isEqualTo("EN4")
Expand Down Expand Up @@ -240,7 +240,7 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
val expectedPrisonIncentiveLevelIdsAffected = setOf("MDI", "WRI")
assertThat(
domainEvents.filter { it.eventType == "incentives.prison-level.changed" }
.map { it.additionalInformation?.prisonId }
.map { it.additionalInformation["prisonId"] }
.toSet(),
).isEqualTo(expectedPrisonIncentiveLevelIdsAffected)
assertThat(
Expand Down Expand Up @@ -442,7 +442,7 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
}
}

assertDomainEventSent("incentives.levels.reordered").let {
assertDomainEventSent("incentives.levels.reordered", anyDomainEvent).let {
assertThat(it.description).isEqualTo("Incentive levels have been re-ordered")
assertThat(it.additionalInformation).isNull()
}
Expand Down Expand Up @@ -581,9 +581,9 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
assertThat(incentiveLevel?.whenUpdated).isEqualTo(now)
}

assertDomainEventSent("incentives.level.changed").let {
assertDomainEventSent("incentives.level.changed", incentiveLevelDomainEvent).let {
assertThat(it.description).isEqualTo("An incentive level has been changed: STD")
assertThat(it.additionalInformation?.incentiveLevel).isEqualTo("STD")
assertThat(it.additionalInformation.incentiveLevel).isEqualTo("STD")
}
assertAuditMessageSentWithMap("INCENTIVE_LEVEL_UPDATED").let {
assertThat(it["description"]).isEqualTo("Silver")
Expand Down Expand Up @@ -636,7 +636,7 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
val expectedPrisonIncentiveLevelIdsAffected = setOf("MDI", "WRI")
assertThat(
domainEvents.filter { it.eventType == "incentives.prison-level.changed" }
.map { it.additionalInformation?.prisonId }
.map { it.additionalInformation["prisonId"] }
.toSet(),
).isEqualTo(expectedPrisonIncentiveLevelIdsAffected)
assertThat(
Expand Down Expand Up @@ -823,9 +823,9 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
assertThat(incentiveLevel?.whenUpdated).isEqualTo(now)
}

assertDomainEventSent("incentives.level.changed").let {
assertDomainEventSent("incentives.level.changed", incentiveLevelDomainEvent).let {
assertThat(it.description).isEqualTo("An incentive level has been changed: STD")
assertThat(it.additionalInformation?.incentiveLevel).isEqualTo("STD")
assertThat(it.additionalInformation.incentiveLevel).isEqualTo("STD")
}
assertAuditMessageSentWithMap("INCENTIVE_LEVEL_UPDATED").let {
assertThat(it["description"]).isEqualTo("Silver")
Expand Down Expand Up @@ -878,7 +878,7 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
val expectedPrisonIncentiveLevelIdsAffected = setOf("MDI", "WRI")
assertThat(
domainEvents.filter { it.eventType == "incentives.prison-level.changed" }
.map { it.additionalInformation?.prisonId }
.map { it.additionalInformation["prisonId"] }
.toSet(),
).isEqualTo(expectedPrisonIncentiveLevelIdsAffected)
assertThat(
Expand Down Expand Up @@ -974,9 +974,9 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
assertThat(incentiveLevel?.whenUpdated).isNotEqualTo(now)
}

assertDomainEventSent("incentives.level.changed").let {
assertDomainEventSent("incentives.level.changed", incentiveLevelDomainEvent).let {
assertThat(it.description).isEqualTo("An incentive level has been changed: ENH")
assertThat(it.additionalInformation?.incentiveLevel).isEqualTo("ENH")
assertThat(it.additionalInformation.incentiveLevel).isEqualTo("ENH")
}
assertAuditMessageSentWithMap("INCENTIVE_LEVEL_UPDATED").let {
assertThat(it["code"]).isEqualTo("ENH")
Expand Down Expand Up @@ -1063,9 +1063,9 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
assertThat(incentiveLevel?.whenUpdated).isEqualTo(now)
}

assertDomainEventSent("incentives.level.changed").let {
assertDomainEventSent("incentives.level.changed", incentiveLevelDomainEvent).let {
assertThat(it.description).isEqualTo("An incentive level has been changed: EN2")
assertThat(it.additionalInformation?.incentiveLevel).isEqualTo("EN2")
assertThat(it.additionalInformation.incentiveLevel).isEqualTo("EN2")
}
assertAuditMessageSentWithMap("INCENTIVE_LEVEL_UPDATED").let {
assertThat(it["code"]).isEqualTo("EN2")
Expand Down Expand Up @@ -1095,9 +1095,9 @@ class IncentiveLevelResourceTest : IncentiveLevelResourceTestBase() {
assertThat(incentiveLevel?.whenUpdated).isEqualTo(now)
}

assertDomainEventSent("incentives.level.changed").let {
assertDomainEventSent("incentives.level.changed", incentiveLevelDomainEvent).let {
assertThat(it.description).isEqualTo("An incentive level has been changed: ENT")
assertThat(it.additionalInformation?.incentiveLevel).isEqualTo("ENT")
assertThat(it.additionalInformation.incentiveLevel).isEqualTo("ENT")
}
assertAuditMessageSentWithMap("INCENTIVE_LEVEL_UPDATED").let {
assertThat(it["code"]).isEqualTo("ENT")
Expand Down
Loading