Skip to content

Commit

Permalink
m7l1 - Repository: Refining
Browse files Browse the repository at this point in the history
  • Loading branch information
svok committed May 3, 2024
1 parent e1feac3 commit 25236be
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 26 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package ru.otus.otuskotlin.marketplace.biz.repo

import ru.otus.otuskotlin.marketplace.common.MkplContext
import ru.otus.otuskotlin.marketplace.common.models.MkplState
import ru.otus.otuskotlin.marketplace.common.models.MkplUserId
import ru.otus.otuskotlin.marketplace.cor.ICorChainDsl
import ru.otus.otuskotlin.marketplace.cor.worker

Expand All @@ -10,8 +11,8 @@ fun ICorChainDsl<MkplContext>.repoPrepareCreate(title: String) = worker {
description = "Подготовка объекта к сохранению в базе данных"
on { state == MkplState.RUNNING }
handle {
adRepoRead = adValidated.deepCopy()
adRepoPrepare = adRepoRead

adRepoPrepare = adValidated.deepCopy()
// TODO будет реализовано в занятии по управлению пользвателями
adRepoPrepare.ownerId = MkplUserId.NONE
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package ru.otus.otuskotlin.marketplace.common.repo

import ru.otus.otuskotlin.marketplace.common.helpers.errorSystem

abstract class AdRepoBase: IRepoAd {

protected suspend fun tryAdMethod(block: suspend () -> IDbAdResponse) = try {
block()
} catch (e: Throwable) {
DbAdResponseErr(errorSystem("methodException", e = e))
}

protected suspend fun tryAdsMethod(block: suspend () -> IDbAdsResponse) = try {
block()
} catch (e: Throwable) {
DbAdsResponseErr(errorSystem("methodException", e = e))
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ data class AdEntity(
adType = model.adType.takeIf { it != MkplDealSide.NONE }?.name,
visibility = model.visibility.takeIf { it != MkplVisibility.NONE }?.name,
lock = model.lock.asString().takeIf { it.isNotBlank() }
// Не нужно сохранять permissions, потому что он ВЫЧИСЛЯЕМЫЙ, а не хранимый
)

fun toInternal() = MkplAd(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import com.benasher44.uuid.uuid4
import io.github.reactivecircus.cache4k.Cache
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import ru.otus.otuskotlin.marketplace.common.helpers.errorSystem
import ru.otus.otuskotlin.marketplace.common.models.*
import ru.otus.otuskotlin.marketplace.common.repo.*
import ru.otus.otuskotlin.marketplace.repo.common.IRepoAdInitializable
Expand All @@ -13,7 +14,7 @@ import kotlin.time.Duration.Companion.minutes
class AdRepoInMemory(
ttl: Duration = 2.minutes,
val randomUuid: () -> String = { uuid4().toString() },
) : IRepoAd, IRepoAdInitializable {
) : AdRepoBase(), IRepoAd, IRepoAdInitializable {

private val mutex: Mutex = Mutex()
private val cache = Cache.Builder<String, AdEntity>()
Expand All @@ -27,28 +28,32 @@ class AdRepoInMemory(
ad
}

override suspend fun createAd(rq: DbAdRequest): IDbAdResponse {
override suspend fun createAd(rq: DbAdRequest): IDbAdResponse = tryAdMethod {
val key = randomUuid()
val ad = rq.ad.copy(id = MkplAdId(key))
val entity = AdEntity(ad)
cache.put(key, entity)
return DbAdResponseOk(ad)
mutex.withLock {
cache.put(key, entity)
}
DbAdResponseOk(ad)
}

override suspend fun readAd(rq: DbAdIdRequest): IDbAdResponse {
val key = rq.id.takeIf { it != MkplAdId.NONE }?.asString() ?: return errorEmptyId
return cache.get(key)
?.let {
DbAdResponseOk(it.toInternal())
} ?: errorNotFound(rq.id)
override suspend fun readAd(rq: DbAdIdRequest): IDbAdResponse = tryAdMethod {
val key = rq.id.takeIf { it != MkplAdId.NONE }?.asString() ?: return@tryAdMethod errorEmptyId
mutex.withLock {
cache.get(key)
?.let {
DbAdResponseOk(it.toInternal())
} ?: errorNotFound(rq.id)
}
}

override suspend fun updateAd(rq: DbAdRequest): IDbAdResponse {
override suspend fun updateAd(rq: DbAdRequest): IDbAdResponse = tryAdMethod {
val rqAd = rq.ad
val id = rqAd.id.takeIf { it != MkplAdId.NONE } ?: return errorEmptyId
val id = rqAd.id.takeIf { it != MkplAdId.NONE } ?: return@tryAdMethod errorEmptyId
val key = id.asString()

return mutex.withLock {
mutex.withLock {
val oldAd = cache.get(key)?.toInternal()
when {
oldAd == null -> errorNotFound(id)
Expand All @@ -60,16 +65,14 @@ class AdRepoInMemory(
}
}
}


}


override suspend fun deleteAd(rq: DbAdIdRequest): IDbAdResponse {
val id = rq.id.takeIf { it != MkplAdId.NONE } ?: return errorEmptyId
override suspend fun deleteAd(rq: DbAdIdRequest): IDbAdResponse = tryAdMethod {
val id = rq.id.takeIf { it != MkplAdId.NONE } ?: return@tryAdMethod errorEmptyId
val key = id.asString()

return mutex.withLock {
mutex.withLock {
val oldAd = cache.get(key)?.toInternal()
when {
oldAd == null -> errorNotFound(id)
Expand All @@ -85,8 +88,8 @@ class AdRepoInMemory(
* Поиск объявлений по фильтру
* Если в фильтре не установлен какой-либо из параметров - по нему фильтрация не идет
*/
override suspend fun searchAd(rq: DbAdFilterRequest): IDbAdsResponse {
val result = cache.asMap().asSequence()
override suspend fun searchAd(rq: DbAdFilterRequest): IDbAdsResponse = tryAdsMethod {
val result: List<MkplAd> = cache.asMap().asSequence()
.filter { entry ->
rq.ownerId.takeIf { it != MkplUserId.NONE }?.let {
it.asString() == entry.value.ownerId
Expand All @@ -104,6 +107,6 @@ class AdRepoInMemory(
}
.map { it.value.toInternal() }
.toList()
return DbAdsResponseOk(result)
DbAdsResponseOk(result)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import ru.otus.otuskotlin.marketplace.repo.inmemory.AdRepoInMemory

class AdRepoInMemoryCreateTest : RepoAdCreateTest() {
override val repo = AdRepoInitialized(
AdRepoInMemory(),
AdRepoInMemory(randomUuid = { uuidNew.asString() }),
initObjects = initObjects,
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import kotlin.test.*

abstract class RepoAdCreateTest {
abstract val repo: IRepoAdInitializable
protected open val uuidNew = MkplAdId("10000000-0000-0000-0000-000000000001")

private val createObj = MkplAd(
title = "create object",
Expand All @@ -21,8 +22,9 @@ abstract class RepoAdCreateTest {
@Test
fun createSuccess() = runRepoTest {
val result = repo.createAd(DbAdRequest(createObj))
val expected = createObj
assertIs<DbAdResponseOk>(result)
val expected = createObj.copy(id = result.data.id)
assertEquals(uuidNew, result.data.id)
assertEquals(expected.title, result.data.title)
assertEquals(expected.description, result.data.description)
assertEquals(expected.adType, result.data.adType)
Expand Down

0 comments on commit 25236be

Please sign in to comment.