From c3113449b19f436704e826777d72ba96e1724fd3 Mon Sep 17 00:00:00 2001 From: Command1264 Date: Tue, 22 Sep 2026 10:52:44 +0800 Subject: [PATCH] feat: implement recoverable reward delivery --- CHANGELOG.md | 1 + README.md | 8 +- docs/configuration/rewards.md | 72 ++++ .../command1264/invitecode/core/Reward.kt | 2 + .../invitecode/core/RewardDefinition.kt | 312 ++++++++++++++++++ .../core/RewardDeliveryProcessor.kt | 229 +++++++++++++ .../invitecode/core/RewardTriggerService.kt | 27 ++ .../core/StandardRewardActionExecutor.kt | 167 ++++++++++ .../invitecode/core/StorageRecords.kt | 45 +-- .../invitecode/core/RewardDefinitionTest.kt | 134 ++++++++ .../core/RewardDeliveryProcessorTest.kt | 288 ++++++++++++++++ .../core/RewardTriggerServiceTest.kt | 86 +++++ .../core/StandardRewardActionExecutorTest.kt | 162 +++++++++ .../BukkitRewardExecutionEnvironment.kt | 77 +++++ .../plugin/VaultEconomyRewardGateway.kt | 26 ++ .../src/main/resources/rewards.yml | 7 + .../storage/sql/SqliteInvitationRecords.kt | 12 + .../storage/sql/SqliteInviteCodeStorage.kt | 4 + .../sql/SqliteInviteCodeStorageTest.kt | 89 +++++ 19 files changed, 1727 insertions(+), 21 deletions(-) create mode 100644 docs/configuration/rewards.md create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDefinition.kt create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessor.kt create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardTriggerService.kt create mode 100644 invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutor.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDefinitionTest.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessorTest.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardTriggerServiceTest.kt create mode 100644 invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutorTest.kt create mode 100644 invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt create mode 100644 invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index 638aebb..bcc1881 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,3 +12,4 @@ - 最小 Bukkit 插件 metadata 與設定範例。 - SQLite persistence adapter、明確 schema migration、原子 Claim/Reward Delivery、可稽核且具復原流程的 Reward 狀態歷史,以及跨重啟 repository contract tests。 - 可設定的 Qualification Policy、內建與外部 condition provider、短路求值、不可逆 qualification,以及 Qualification Fact 的 SQLite transaction。 +- Qualification 與 Inviter milestone 獎勵規劃、穩定冪等鍵、先保存後執行的 Reward Action 狀態流程、離線補發邊界、失敗復原與 Vault Economy adapter。 diff --git a/README.md b/README.md index a1c615b..384d054 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ InviteCodeKt 是從零重寫的 Kotlin Minecraft 邀請與推薦獎勵插件。目標是以單一可安裝 JAR 支援 Spigot 與 Paper 1.8.8 到最新已測試版本,並透過隔離的 adapter 載入新版能力。 > [!IMPORTANT] -> 這個 repository 目前是 `0.1.0-SNAPSHOT`。平台無關的 Invitation 核心狀態機、Invite Code lifecycle、SQLite adapter 與 Qualification Policy 已實作;reward 與 Minecraft 平台工作流程尚未完成串接。 +> 這個 repository 目前是 `0.1.0-SNAPSHOT`。平台無關的 Invitation 核心狀態機、Invite Code lifecycle、SQLite adapter、Qualification Policy 與可復原的 Reward Delivery 已實作;Minecraft 平台工作流程尚未完成串接。 ## 專案目標 @@ -70,6 +70,12 @@ invitecode-plugin/build/libs/InviteCodeKt-0.1.0-SNAPSHOT.jar 設定格式、condition 參數與外部 provider 契約請參閱 [`docs/configuration/qualifications.md`](./docs/configuration/qualifications.md)。實際讀取 `qualifications.yml`、收集 Bukkit/Placeholder 值及 executor 排程會在 Bukkit 工作流程 Issue 串接。 +## Reward Delivery + +Qualification Reward 與 Inviter Milestone Reward 會先以穩定冪等鍵保存完整 Delivery/Action,再執行訊息、Console 指令、玩家指令或 Vault 經濟獎勵。玩家離線或 Vault integration 暫時不可用時維持 `PENDING`;外部結果無法判定時轉為 `UNCERTAIN`,只允許具稽核資訊的管理操作決定重試或視為已交付。 + +設定格式、placeholder、離線補發及失敗復原流程請參閱 [`docs/configuration/rewards.md`](./docs/configuration/rewards.md)。實際讀取 `rewards.yml`、登入補發、啟動復原與管理指令會在 Bukkit 工作流程 Issue 串接。 + ## 分支 - `main`:穩定發行基線與 GitHub 預設分支 diff --git a/docs/configuration/rewards.md b/docs/configuration/rewards.md new file mode 100644 index 0000000..f137dd5 --- /dev/null +++ b/docs/configuration/rewards.md @@ -0,0 +1,72 @@ +# Reward Delivery 設定與復原 + +`rewards.yml` 使用版本化格式。Qualification Reward 會在 Invitation 首次成為 `QUALIFIED` 時建立;Milestone Reward 會在 Inviter 的 qualified Invitation 數量首次到達指定門檻時建立。 + +```yaml +config-version: 1 + +qualification-rewards: + default: + inviter: + - type: MESSAGE + message: invite.qualified.inviter + - type: VAULT_ECONOMY + amount: 100 + invitee: + - type: CONSOLE_COMMAND + command: give {invitee_name} diamond 1 + +milestone-rewards: + five-qualified: + at: 5 + inviter: + - type: MESSAGE + message: invite.milestone.five +``` + +每個 reward ID 都是持久化冪等鍵的一部分。Reward 已投入使用後,不應把同一 ID 改成另一種獎勵;需要改變內容時請使用新的 ID。 + +## Action 類型 + +| `type` | 必要欄位 | 執行方式 | +| --- | --- | --- | +| `MESSAGE` | `message` | 將 locale key 對應的訊息傳給在線收件玩家。 | +| `CONSOLE_COMMAND` | `command` | 由伺服器 Console 執行不含開頭 `/` 的指令。 | +| `PLAYER_COMMAND` | `command` | 由在線收件玩家以原有權限執行指令;不會暫時提高權限。 | +| `VAULT_ECONOMY` | `amount` | 透過 Vault 已註冊的 Economy provider 存入正數金額。 | + +指令只接受下列 placeholder: + +- `{recipient_uuid}`、`{recipient_name}` +- `{inviter_uuid}`、`{inviter_name}` +- `{invitee_uuid}`、`{invitee_name}` + +名稱在執行當下無法取得時,使用該名稱的指令會進入 `FAILED`,且不會送出部分展開的指令。設定解析會拒絕未知 placeholder、換行、控制字元、開頭 `/` 及不成對的大括號。`MESSAGE` 的 `message` 是 locale key,不是直接顯示的文字。 + +Vault 是 soft dependency。沒有安裝 Vault、沒有 Economy provider,或 integration 暫時不可用時,`VAULT_ECONOMY` Action 會保留在 `PENDING`,待 integration 可用後再處理。`MESSAGE` 與 `PLAYER_COMMAND` 的收件玩家離線時也會保留在 `PENDING`,供玩家上線時補發。 + +## 持久化與失敗復原 + +每次 Reward Delivery 與完整 Action 清單會先以單一 storage transaction 寫入,再允許任何外部效果發生。Delivery、Action ID 與 idempotency key 都由 Invitation、reward ID、收件角色及 Action 位置穩定產生;相同事件重送只會讀回既有紀錄。 + +Action 執行流程如下: + +1. 確認玩家在線或 integration 可用;尚不可執行時維持 `PENDING`。 +2. 在 storage 將 Action 從 `PENDING` 寫成 `PROCESSING`。 +3. 執行訊息、指令或 Vault 存款。 +4. 依明確結果寫成 `DELIVERED` 或 `FAILED`。 + +如果玩家在步驟 1 與步驟 3 之間離線,平台 adapter 會在尚未執行外部效果時明確回報,Action 由 `PROCESSING` 安全回到 `PENDING`,等待下次登入。 + +如果外部呼叫拋出例外,或外部效果完成後無法保存最終狀態,結果可能已發生但無法證明。此時不會自動重送:仍是 `PROCESSING` 的紀錄會在重啟復原時轉成 `UNCERTAIN`。管理員必須根據外部系統紀錄選擇: + +- `RETRY`:將 Action 恢復為 `PENDING`,接受外部效果可能重複的風險。 +- `MARK_DELIVERED`:確認效果已發生,將 Action 視為 `DELIVERED`。 + +管理決定必須保存 actor 與 reason。指令 dispatcher 回傳已接受時,系統即視為 `DELIVERED`;插件無法驗證被呼叫指令後續所做的其他非同步工作。 + +## 執行緒邊界 + +`RewardDeliveryProcessor` 會呼叫同步 storage interface,必須在專用 storage executor 執行,不可在 Minecraft server main thread 執行。Bukkit environment 只把需要 Bukkit API 的在線狀態、訊息、指令與 Vault 操作切回 server main thread。 + +目前核心規劃、狀態處理、SQLite persistence 與 Bukkit/Vault adapter 已具備;實際載入 `rewards.yml`、玩家上線補發、啟動復原及管理指令會由 Bukkit 工作流程 Issue 串接。 diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/Reward.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/Reward.kt index 34c08e4..16e7479 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/Reward.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/Reward.kt @@ -43,6 +43,7 @@ fun RewardActionStatus.canTransitionTo(next: RewardActionStatus, administrative: RewardActionStatus.EXPIRED, ) RewardActionStatus.PROCESSING -> next in setOf( + RewardActionStatus.PENDING, RewardActionStatus.DELIVERED, RewardActionStatus.FAILED, RewardActionStatus.UNCERTAIN, @@ -67,6 +68,7 @@ fun RewardDeliveryStatus.canTransitionTo( RewardDeliveryStatus.UNCERTAIN, ) RewardDeliveryStatus.PROCESSING -> next in setOf( + RewardDeliveryStatus.PENDING, RewardDeliveryStatus.DELIVERED, RewardDeliveryStatus.FAILED, RewardDeliveryStatus.UNCERTAIN, diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDefinition.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDefinition.kt new file mode 100644 index 0000000..befbee8 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDefinition.kt @@ -0,0 +1,312 @@ +package io.github.command1264.invitecode.core + +import io.github.command1264.invitecode.api.InvitationStatus +import java.math.BigDecimal +import java.nio.charset.StandardCharsets +import java.util.Locale +import java.util.UUID + +enum class RewardActionType { + CONSOLE_COMMAND, + PLAYER_COMMAND, + MESSAGE, + VAULT_ECONOMY, +} + +data class RewardActionDefinition( + val type: RewardActionType, + val payload: String, +) { + init { + require(payload.isNotBlank()) { "Reward Action payload must not be blank." } + } +} + +data class QualificationRewardDefinition( + val id: String, + val inviterActions: List, + val inviteeActions: List, +) { + init { + require(id.isNotBlank()) { "Reward ID must not be blank." } + require(inviterActions.isNotEmpty() || inviteeActions.isNotEmpty()) { + "Qualification Reward $id must contain at least one action." + } + } +} + +data class MilestoneRewardDefinition( + val id: String, + val qualifiedInvitations: Int, + val inviterActions: List, +) { + init { + require(id.isNotBlank()) { "Milestone Reward ID must not be blank." } + require(qualifiedInvitations > 0) { "Milestone Reward threshold must be positive." } + require(inviterActions.isNotEmpty()) { "Milestone Reward $id must contain at least one Inviter action." } + } +} + +data class RewardConfiguration( + val version: Int, + val qualificationRewards: Map, + val milestoneRewards: Map, +) { + init { + require(qualificationRewards.isNotEmpty() || milestoneRewards.isNotEmpty()) { + "Reward configuration must contain at least one reward." + } + } +} + +object RewardConfigurationParser { + const val CURRENT_VERSION = 1 + + fun parse(value: Map): RewardConfiguration { + require(value.keys == setOf("config-version", "qualification-rewards", "milestone-rewards")) { + "Reward configuration must contain only config-version, qualification-rewards, and milestone-rewards." + } + val version = (value["config-version"] as? Number)?.toString()?.toIntOrNull() + ?: throw IllegalArgumentException("Reward configuration requires numeric integer config-version.") + require(version == CURRENT_VERSION) { + "Reward config-version $version is unsupported; expected $CURRENT_VERSION." + } + val milestoneRewards = value["milestone-rewards"].requiredStringMap("milestone-rewards") + .mapValues { (rewardId, rawReward) -> parseMilestoneReward(rewardId, rawReward) } + val rewards = value["qualification-rewards"].requiredStringMap("qualification-rewards") + .mapValues { (rewardId, rawReward) -> parseQualificationReward(rewardId, rawReward) } + return RewardConfiguration(version, rewards, milestoneRewards) + } + + private fun parseMilestoneReward( + rewardId: String, + rawReward: Any?, + ): MilestoneRewardDefinition { + val reward = rawReward.requiredStringMap("Milestone Reward $rewardId") + require(reward.keys == setOf("at", "inviter")) { + "Milestone Reward $rewardId must contain only at and inviter." + } + val threshold = (reward["at"] as? Number)?.toString()?.toIntOrNull() + ?: throw IllegalArgumentException("Milestone Reward $rewardId requires integer at.") + return MilestoneRewardDefinition( + id = rewardId, + qualifiedInvitations = threshold, + inviterActions = reward["inviter"].requiredList("Milestone Reward $rewardId inviter") + .mapIndexed { index, action -> parseAction(action, "$rewardId inviter action ${index + 1}") }, + ) + } + + private fun parseQualificationReward( + rewardId: String, + rawReward: Any?, + ): QualificationRewardDefinition { + val reward = rawReward.requiredStringMap("Qualification Reward $rewardId") + require(reward.keys == setOf("inviter", "invitee")) { + "Qualification Reward $rewardId must contain only inviter and invitee." + } + return QualificationRewardDefinition( + id = rewardId, + inviterActions = reward["inviter"].requiredList("Qualification Reward $rewardId inviter") + .mapIndexed { index, action -> parseAction(action, "$rewardId inviter action ${index + 1}") }, + inviteeActions = reward["invitee"].requiredList("Qualification Reward $rewardId invitee") + .mapIndexed { index, action -> parseAction(action, "$rewardId invitee action ${index + 1}") }, + ) + } + + private fun parseAction(rawAction: Any?, location: String): RewardActionDefinition { + val action = rawAction.requiredStringMap(location) + val rawType = action["type"] as? String + ?: throw IllegalArgumentException("$location requires string type.") + val type = try { + RewardActionType.valueOf(rawType.uppercase(Locale.ROOT)) + } catch (error: IllegalArgumentException) { + throw IllegalArgumentException("$location has unsupported type '$rawType'.", error) + } + val payloadKey = when (type) { + RewardActionType.MESSAGE -> "message" + RewardActionType.CONSOLE_COMMAND, + RewardActionType.PLAYER_COMMAND -> "command" + RewardActionType.VAULT_ECONOMY -> "amount" + } + require(action.keys == setOf("type", payloadKey)) { + "$location type $type must contain only type and $payloadKey." + } + val rawPayload = action[payloadKey] + ?: throw IllegalArgumentException("$location requires $payloadKey.") + val payload = when (type) { + RewardActionType.MESSAGE -> parseMessageKey(rawPayload, location) + RewardActionType.CONSOLE_COMMAND, + RewardActionType.PLAYER_COMMAND -> parseCommand(rawPayload, location) + RewardActionType.VAULT_ECONOMY -> parseAmount(rawPayload, location) + } + return RewardActionDefinition(type, payload) + } + + private fun parseMessageKey(rawValue: Any?, location: String): String { + val value = rawValue as? String + ?: throw IllegalArgumentException("$location message must be a string locale key.") + require(MESSAGE_KEY.matches(value)) { "$location message '$value' is not a valid locale key." } + return value + } + + private fun parseCommand(rawValue: Any?, location: String): String { + val value = rawValue as? String + ?: throw IllegalArgumentException("$location command must be a string.") + require(value.isNotBlank()) { "$location command must not be blank." } + require(!value.startsWith("/")) { "$location command must not start with '/'." } + require(value.none { it == '\n' || it == '\r' || it.code < 0x20 }) { + "$location command must not contain control characters." + } + val placeholders = PLACEHOLDER.findAll(value).map { it.groupValues[1] }.toSet() + require(placeholders.all { it in ALLOWED_PLACEHOLDERS }) { + "$location command contains an unsupported placeholder." + } + require(value.replace(PLACEHOLDER, "").none { it == '{' || it == '}' }) { + "$location command contains malformed placeholder braces." + } + return value + } + + private fun parseAmount(rawValue: Any?, location: String): String { + val amount = try { + BigDecimal(rawValue.toString()) + } catch (error: NumberFormatException) { + throw IllegalArgumentException("$location amount must be numeric.", error) + } + require(amount > BigDecimal.ZERO) { "$location amount must be greater than zero." } + return amount.stripTrailingZeros().toPlainString() + } + + private fun Any?.requiredStringMap(location: String): Map { + require(this is Map<*, *> && keys.all { it is String }) { "$location must be a map with string keys." } + @Suppress("UNCHECKED_CAST") + return this as Map + } + + private fun Any?.requiredList(location: String): List { + require(this is List<*>) { "$location must be a list." } + return this + } + + private val MESSAGE_KEY = Regex("^[a-z0-9][a-z0-9._-]*$") + private val PLACEHOLDER = Regex("\\{([a-z_]+)}") + private val ALLOWED_PLACEHOLDERS = setOf( + "recipient_uuid", + "recipient_name", + "inviter_uuid", + "inviter_name", + "invitee_uuid", + "invitee_name", + ) +} + +data class RewardDeliveryPlan( + val delivery: StoredRewardDelivery, + val actions: List, +) { + init { + require(actions.isNotEmpty()) { "Reward Delivery plan must contain at least one action." } + require(actions.all { it.rewardDeliveryId == delivery.id }) { + "Every planned Reward Action must belong to Reward Delivery ${delivery.id}." + } + } +} + +object RewardDeliveryPlanner { + fun planQualification( + definition: QualificationRewardDefinition, + invitation: Invitation, + ): RewardDeliveryPlan { + require(invitation.status == InvitationStatus.QUALIFIED) { + "Qualification Reward requires a Qualified Invitation." + } + val occurredAt = requireNotNull(invitation.qualifiedAt) { + "Qualified Invitation requires qualifiedAt." + } + val deliveryKey = "qualification:${invitation.id}:${definition.id}" + val deliveryId = stableUuid("delivery:$deliveryKey") + val planned = buildList { + definition.inviterActions.forEachIndexed { index, action -> + add(PlannedAction("inviter", index, invitation.inviterId, action)) + } + definition.inviteeActions.forEachIndexed { index, action -> + add(PlannedAction("invitee", index, invitation.inviteeId, action)) + } + } + val actions = planned.mapIndexed { position, plannedAction -> + val actionKey = "$deliveryKey:${plannedAction.role}:${plannedAction.rolePosition}" + StoredRewardAction( + id = stableUuid("action:$actionKey"), + rewardDeliveryId = deliveryId, + invitationId = invitation.id, + recipientId = plannedAction.recipientId, + position = position, + type = plannedAction.definition.type.name, + payload = plannedAction.definition.payload, + status = RewardActionStatus.PENDING, + idempotencyKey = actionKey, + createdAt = occurredAt, + updatedAt = occurredAt, + ) + } + return RewardDeliveryPlan( + delivery = StoredRewardDelivery( + id = deliveryId, + invitationId = invitation.id, + rewardId = definition.id, + status = RewardDeliveryStatus.PENDING, + idempotencyKey = deliveryKey, + createdAt = occurredAt, + updatedAt = occurredAt, + ), + actions = actions, + ) + } + + fun planMilestone( + definition: MilestoneRewardDefinition, + inviterId: UUID, + achievedAt: java.time.Instant, + ): RewardDeliveryPlan { + val deliveryKey = "milestone:$inviterId:${definition.qualifiedInvitations}:${definition.id}" + val deliveryId = stableUuid("delivery:$deliveryKey") + val actions = definition.inviterActions.mapIndexed { position, action -> + val actionKey = "$deliveryKey:inviter:$position" + StoredRewardAction( + id = stableUuid("action:$actionKey"), + rewardDeliveryId = deliveryId, + invitationId = null, + recipientId = inviterId, + position = position, + type = action.type.name, + payload = action.payload, + status = RewardActionStatus.PENDING, + idempotencyKey = actionKey, + createdAt = achievedAt, + updatedAt = achievedAt, + ) + } + return RewardDeliveryPlan( + StoredRewardDelivery( + id = deliveryId, + invitationId = null, + rewardId = definition.id, + status = RewardDeliveryStatus.PENDING, + idempotencyKey = deliveryKey, + createdAt = achievedAt, + updatedAt = achievedAt, + ), + actions, + ) + } + + private fun stableUuid(value: String): UUID = + UUID.nameUUIDFromBytes("InviteCodeKt:$value".toByteArray(StandardCharsets.UTF_8)) + + private data class PlannedAction( + val role: String, + val rolePosition: Int, + val recipientId: UUID, + val definition: RewardActionDefinition, + ) +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessor.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessor.kt new file mode 100644 index 0000000..060afe8 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessor.kt @@ -0,0 +1,229 @@ +package io.github.command1264.invitecode.core + +import java.time.Instant +import java.util.UUID + +data class RewardActionExecutionContext( + val recipientId: UUID, + val recipientName: String?, + val inviterId: UUID?, + val inviterName: String?, + val inviteeId: UUID?, + val inviteeName: String?, +) { + init { + require(recipientName == null || recipientName.isNotBlank()) { "Recipient name must not be blank." } + require(inviterName == null || inviterName.isNotBlank()) { "Inviter name must not be blank." } + require(inviteeName == null || inviteeName.isNotBlank()) { "Invitee name must not be blank." } + } +} + +enum class RewardActionReadiness { + READY, + RECIPIENT_OFFLINE, + INTEGRATION_UNAVAILABLE, +} + +sealed class RewardActionExecutionResult { + object Delivered : RewardActionExecutionResult() + + data class Deferred(val readiness: RewardActionReadiness) : RewardActionExecutionResult() { + init { + require(readiness != RewardActionReadiness.READY) { + "A deferred Reward Action must explain why it is not ready." + } + } + } + + data class Failed(val reason: String) : RewardActionExecutionResult() { + init { + require(reason.isNotBlank()) { "Reward Action failure reason must not be blank." } + require(reason.length <= 512) { "Reward Action failure reason must not exceed 512 characters." } + require(reason.none { it == '\r' || it == '\n' }) { + "Reward Action failure reason must not contain line breaks." + } + } + } +} + +interface RewardActionExecutor { + fun readiness( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionReadiness + + fun execute( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionExecutionResult +} + +class RewardDeliveryCoordinator( + private val records: RewardRecords, +) { + fun prepare(plan: RewardDeliveryPlan): RewardDeliveryPlan { + val existing = records.rewardDelivery(plan.delivery.id) + if (existing != null) { + require(existing.idempotencyKey == plan.delivery.idempotencyKey) { + "Reward Delivery ${plan.delivery.id} has an unexpected idempotency key." + } + return RewardDeliveryPlan(existing, records.rewardActions(existing.id)) + } + records.saveRewardDelivery(plan.delivery, plan.actions) + return plan + } + + fun action(actionId: UUID): StoredRewardAction? = records.rewardAction(actionId) + + fun pendingForRecipient(recipientId: UUID): List = + records.pendingRewardActions(recipientId) + + fun begin(actionId: UUID, occurredAt: Instant): StoredRewardAction = transition( + actionId, + requiredStatus = RewardActionStatus.PENDING, + nextStatus = RewardActionStatus.PROCESSING, + occurredAt = occurredAt, + lastError = null, + ) + + fun delivered(actionId: UUID, occurredAt: Instant): StoredRewardAction = transition( + actionId, + requiredStatus = RewardActionStatus.PROCESSING, + nextStatus = RewardActionStatus.DELIVERED, + occurredAt = occurredAt, + lastError = null, + ) + + fun failed(actionId: UUID, reason: String, occurredAt: Instant): StoredRewardAction = transition( + actionId, + requiredStatus = RewardActionStatus.PROCESSING, + nextStatus = RewardActionStatus.FAILED, + occurredAt = occurredAt, + lastError = reason, + ) + + fun deferred(actionId: UUID, occurredAt: Instant): StoredRewardAction = transition( + actionId, + requiredStatus = RewardActionStatus.PROCESSING, + nextStatus = RewardActionStatus.PENDING, + occurredAt = occurredAt, + lastError = null, + ) + + fun uncertain(actionId: UUID, reason: String, occurredAt: Instant): StoredRewardAction = transition( + actionId, + requiredStatus = RewardActionStatus.PROCESSING, + nextStatus = RewardActionStatus.UNCERTAIN, + occurredAt = occurredAt, + lastError = reason, + ) + + fun recoverInterrupted(recoveredAt: Instant): Int = + records.recoverInterruptedRewardActions(recoveredAt) + + fun resolveUncertain( + actionId: UUID, + resolution: UncertainRewardActionResolution, + context: RewardAdministrationContext, + ): StoredRewardAction = records.resolveUncertainRewardAction(actionId, resolution, context) + + private fun transition( + actionId: UUID, + requiredStatus: RewardActionStatus, + nextStatus: RewardActionStatus, + occurredAt: Instant, + lastError: String?, + ): StoredRewardAction { + val current = requireNotNull(records.rewardAction(actionId)) { "Reward Action $actionId does not exist." } + check(current.status == requiredStatus) { + "Reward Action $actionId must be $requiredStatus; current status is ${current.status}." + } + val transitionAt = if (occurredAt.isAfter(current.updatedAt)) { + occurredAt + } else { + current.updatedAt.plusNanos(1) + } + val updated = current.copy( + status = nextStatus, + updatedAt = transitionAt, + lastError = lastError, + ) + records.saveRewardAction(updated) + return updated + } +} + +enum class RewardActionProcessingStatus { + DELIVERED, + FAILED, + DEFERRED, + UNCERTAIN, + ALREADY_PROCESSING, + ALREADY_TERMINAL, +} + +data class RewardActionProcessingResult( + val status: RewardActionProcessingStatus, + val action: StoredRewardAction, + val readiness: RewardActionReadiness? = null, +) + +class RewardDeliveryProcessor( + private val coordinator: RewardDeliveryCoordinator, + private val executor: RewardActionExecutor, + private val now: () -> Instant = Instant::now, +) { + fun process( + requested: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionProcessingResult { + require(requested.recipientId == context.recipientId) { + "Reward Action recipient does not match execution context." + } + val current = requireNotNull(coordinator.action(requested.id)) { + "Reward Action ${requested.id} does not exist." + } + when (current.status) { + RewardActionStatus.PROCESSING -> return result(RewardActionProcessingStatus.ALREADY_PROCESSING, current) + RewardActionStatus.DELIVERED, + RewardActionStatus.FAILED, + RewardActionStatus.UNCERTAIN, + RewardActionStatus.EXPIRED -> return result(RewardActionProcessingStatus.ALREADY_TERMINAL, current) + RewardActionStatus.PENDING -> Unit + } + val readiness = executor.readiness(current, context) + if (readiness != RewardActionReadiness.READY) { + return RewardActionProcessingResult(RewardActionProcessingStatus.DEFERRED, current, readiness) + } + + val processing = coordinator.begin(current.id, now()) + val execution = try { + executor.execute(processing, context) + } catch (error: Exception) { + val uncertain = coordinator.uncertain( + processing.id, + "External Reward Action execution threw ${error.javaClass.simpleName}; result is unknown.", + now(), + ) + return result(RewardActionProcessingStatus.UNCERTAIN, uncertain) + } + return when (execution) { + RewardActionExecutionResult.Delivered -> result( + RewardActionProcessingStatus.DELIVERED, + coordinator.delivered(processing.id, now()), + ) + is RewardActionExecutionResult.Deferred -> RewardActionProcessingResult( + RewardActionProcessingStatus.DEFERRED, + coordinator.deferred(processing.id, now()), + execution.readiness, + ) + is RewardActionExecutionResult.Failed -> result( + RewardActionProcessingStatus.FAILED, + coordinator.failed(processing.id, execution.reason, now()), + ) + } + } + + private fun result(status: RewardActionProcessingStatus, action: StoredRewardAction) = + RewardActionProcessingResult(status, action) +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardTriggerService.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardTriggerService.kt new file mode 100644 index 0000000..a4d41b7 --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/RewardTriggerService.kt @@ -0,0 +1,27 @@ +package io.github.command1264.invitecode.core + +class RewardTriggerService( + private val records: RewardRecords, +) { + private val coordinator = RewardDeliveryCoordinator(records) + + fun prepareForQualification( + invitation: Invitation, + configuration: RewardConfiguration, + ): List { + val qualificationPlans = configuration.qualificationRewards + .toSortedMap() + .values + .map { RewardDeliveryPlanner.planQualification(it, invitation) } + val qualifiedCount = records.qualifiedInvitationCount(invitation.inviterId) + val achievedAt = requireNotNull(invitation.qualifiedAt) { + "Qualified Invitation requires qualifiedAt before planning Rewards." + } + val milestonePlans = configuration.milestoneRewards + .toSortedMap() + .values + .filter { it.qualifiedInvitations == qualifiedCount } + .map { RewardDeliveryPlanner.planMilestone(it, invitation.inviterId, achievedAt) } + return (qualificationPlans + milestonePlans).map(coordinator::prepare) + } +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutor.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutor.kt new file mode 100644 index 0000000..0a00a0b --- /dev/null +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutor.kt @@ -0,0 +1,167 @@ +package io.github.command1264.invitecode.core + +import java.math.BigDecimal +import java.util.Locale +import java.util.UUID + +interface RewardExecutionEnvironment { + fun isOnline(playerId: UUID): Boolean + + fun dispatchConsole(command: String): Boolean + + fun dispatchPlayer(playerId: UUID, command: String): OnlineRewardActionResult + + fun sendMessage(playerId: UUID, localeKey: String): OnlineRewardActionResult + + fun economyAvailable(): Boolean + + fun deposit(playerId: UUID, amount: BigDecimal): Boolean +} + +enum class OnlineRewardActionResult { + ACCEPTED, + REJECTED, + RECIPIENT_OFFLINE, +} + +class StandardRewardActionExecutor( + private val environment: RewardExecutionEnvironment, +) : RewardActionExecutor { + override fun readiness( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionReadiness { + require(action.recipientId == context.recipientId) { + "Reward Action recipient does not match execution context." + } + return when (action.type.toActionTypeOrNull()) { + RewardActionType.MESSAGE, + RewardActionType.PLAYER_COMMAND -> if (environment.isOnline(action.recipientId)) { + RewardActionReadiness.READY + } else { + RewardActionReadiness.RECIPIENT_OFFLINE + } + RewardActionType.VAULT_ECONOMY -> if (environment.economyAvailable()) { + RewardActionReadiness.READY + } else { + RewardActionReadiness.INTEGRATION_UNAVAILABLE + } + RewardActionType.CONSOLE_COMMAND, + null -> RewardActionReadiness.READY + } + } + + override fun execute( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ): RewardActionExecutionResult { + require(action.status == RewardActionStatus.PROCESSING) { + "Only a PROCESSING Reward Action can execute external effects." + } + require(action.recipientId == context.recipientId) { + "Reward Action recipient does not match execution context." + } + return when (action.type.toActionTypeOrNull()) { + RewardActionType.CONSOLE_COMMAND -> executeCommand(action.payload, context, environment::dispatchConsole) + RewardActionType.PLAYER_COMMAND -> executeOnlineCommand(action.payload, context) { command -> + environment.dispatchPlayer(action.recipientId, command) + } + RewardActionType.MESSAGE -> { + if (!MESSAGE_KEY.matches(action.payload)) { + return RewardActionExecutionResult.Failed("Stored Reward message key is invalid.") + } + environment.sendMessage(action.recipientId, action.payload).toExecutionResult() + } + RewardActionType.VAULT_ECONOMY -> { + val amount = action.payload.toBigDecimalOrNull() + ?: return RewardActionExecutionResult.Failed("Stored Vault economy amount is invalid.") + if (amount <= BigDecimal.ZERO) { + return RewardActionExecutionResult.Failed("Stored Vault economy amount is invalid.") + } + if (environment.deposit(action.recipientId, amount)) { + RewardActionExecutionResult.Delivered + } else { + RewardActionExecutionResult.Failed("Vault economy deposit was rejected.") + } + } + null -> RewardActionExecutionResult.Failed("Stored Reward Action type is unsupported.") + } + } + + private fun executeCommand( + template: String, + context: RewardActionExecutionContext, + dispatch: (String) -> Boolean, + ): RewardActionExecutionResult { + val command = try { + renderCommand(template, context) + } catch (_: IllegalArgumentException) { + return RewardActionExecutionResult.Failed("Reward command context is invalid.") + } + return commandResult(command, dispatch) + } + + private fun executeOnlineCommand( + template: String, + context: RewardActionExecutionContext, + dispatch: (String) -> OnlineRewardActionResult, + ): RewardActionExecutionResult { + val command = try { + renderCommand(template, context) + } catch (_: IllegalArgumentException) { + return RewardActionExecutionResult.Failed("Reward command context is invalid.") + } + return dispatch(command).toExecutionResult() + } + + private fun OnlineRewardActionResult.toExecutionResult(): RewardActionExecutionResult = when (this) { + OnlineRewardActionResult.ACCEPTED -> RewardActionExecutionResult.Delivered + OnlineRewardActionResult.REJECTED -> RewardActionExecutionResult.Failed("Reward action was rejected.") + OnlineRewardActionResult.RECIPIENT_OFFLINE -> RewardActionExecutionResult.Deferred( + RewardActionReadiness.RECIPIENT_OFFLINE, + ) + } + + private fun commandResult( + command: String, + dispatch: (String) -> Boolean, + ): RewardActionExecutionResult = if (dispatch(command)) { + RewardActionExecutionResult.Delivered + } else { + RewardActionExecutionResult.Failed("Command dispatch was rejected.") + } + + private fun renderCommand( + template: String, + context: RewardActionExecutionContext, + ): String { + require(template.isNotBlank() && !template.startsWith("/")) { "Stored Reward command is invalid." } + require(template.none { it == '\r' || it == '\n' || it.code < 0x20 }) { + "Stored Reward command contains control characters." + } + val values = mapOf( + "recipient_uuid" to context.recipientId.toString(), + "recipient_name" to context.recipientName, + "inviter_uuid" to context.inviterId?.toString(), + "inviter_name" to context.inviterName, + "invitee_uuid" to context.inviteeId?.toString(), + "invitee_name" to context.inviteeName, + ) + val rendered = PLACEHOLDER.replace(template) { match -> + val name = match.groupValues[1] + require(name in values) { "Stored Reward command contains unsupported placeholder '{$name}'." } + requireNotNull(values[name]) { "Reward command placeholder '{$name}' is unavailable." } + } + require(rendered.none { it == '{' || it == '}' }) { "Stored Reward command contains malformed braces." } + return rendered + } + + private fun String.toActionTypeOrNull(): RewardActionType? = try { + RewardActionType.valueOf(uppercase(Locale.ROOT)) + } catch (_: IllegalArgumentException) { + null + } + + private val PLACEHOLDER = Regex("\\{([a-z_]+)}") + private val MESSAGE_KEY = Regex("^[a-z0-9][a-z0-9._-]*$") +} diff --git a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt index e873195..9f9ebf4 100644 --- a/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt +++ b/invitecode-core/src/main/kotlin/io/github/command1264/invitecode/core/StorageRecords.kt @@ -124,24 +124,8 @@ interface QualificationRecords { fun saveQualificationFacts(facts: List) } -interface InviteCodeStorage : - InvitationTransactions, - InviteCodeRegistry, - QualificationRecords, - AutoCloseable { - fun savePlayer(player: StoredPlayer) - - fun player(playerId: UUID): StoredPlayer? - - fun activeInviteCode(inviterId: UUID): ActiveInviteCode? - - fun isInviteCodeReserved(code: InviteCode): Boolean - - fun saveInvitation(invitation: Invitation) - - fun saveQualificationFact(fact: QualificationFact) - - fun qualificationFact(factId: UUID): QualificationFact? +interface RewardRecords { + fun qualifiedInvitationCount(inviterId: UUID): Int fun saveRewardAction(action: StoredRewardAction) @@ -151,8 +135,6 @@ interface InviteCodeStorage : fun pendingRewardActions(recipientId: UUID): List - fun rewardActionTransitions(actionId: UUID): List - fun recoverInterruptedRewardActions(recoveredAt: Instant): Int fun resolveUncertainRewardAction( @@ -164,6 +146,29 @@ interface InviteCodeStorage : fun saveRewardDelivery(delivery: StoredRewardDelivery, actions: List) fun rewardDelivery(deliveryId: UUID): StoredRewardDelivery? +} + +interface InviteCodeStorage : + InvitationTransactions, + InviteCodeRegistry, + QualificationRecords, + RewardRecords, + AutoCloseable { + fun savePlayer(player: StoredPlayer) + + fun player(playerId: UUID): StoredPlayer? + + fun activeInviteCode(inviterId: UUID): ActiveInviteCode? + + fun isInviteCodeReserved(code: InviteCode): Boolean + + fun saveInvitation(invitation: Invitation) + + fun saveQualificationFact(fact: QualificationFact) + + fun qualificationFact(factId: UUID): QualificationFact? + + fun rewardActionTransitions(actionId: UUID): List fun rewardDeliveryTransitions(deliveryId: UUID): List diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDefinitionTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDefinitionTest.kt new file mode 100644 index 0000000..9a3dd18 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDefinitionTest.kt @@ -0,0 +1,134 @@ +package io.github.command1264.invitecode.core + +import io.github.command1264.invitecode.api.InvitationStatus +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import java.time.Instant +import java.util.UUID + +class RewardDefinitionTest { + @Test + fun `parses qualification reward actions and creates deterministic delivery plan`() { + val definition = RewardConfigurationParser.parse( + mapOf( + "config-version" to 1, + "qualification-rewards" to mapOf( + "default" to mapOf( + "inviter" to listOf( + mapOf("type" to "MESSAGE", "message" to "invite.qualified.inviter"), + mapOf( + "type" to "CONSOLE_COMMAND", + "command" to "give {inviter_name} diamond 1", + ), + ), + "invitee" to listOf( + mapOf("type" to "VAULT_ECONOMY", "amount" to "100.50"), + ), + ), + ), + "milestone-rewards" to emptyMap(), + ), + ).qualificationRewards.getValue("default") + + val first = RewardDeliveryPlanner.planQualification(definition, invitation()) + val replay = RewardDeliveryPlanner.planQualification(definition, invitation()) + + assertEquals(first, replay) + assertEquals(listOf(inviterId, inviterId, inviteeId), first.actions.map { it.recipientId }) + assertEquals(listOf(0, 1, 2), first.actions.map { it.position }) + assertEquals( + listOf("MESSAGE", "CONSOLE_COMMAND", "VAULT_ECONOMY"), + first.actions.map { it.type }, + ) + } + + @Test + fun `rejects unsafe reward action payloads`() { + assertThrows { + parseAction(mapOf("type" to "PLAYER_COMMAND", "command" to "/op {recipient_name}")) + } + assertThrows { + parseAction(mapOf("type" to "CONSOLE_COMMAND", "command" to "give {unknown} diamond")) + } + assertThrows { + parseAction(mapOf("type" to "VAULT_ECONOMY", "amount" to "0")) + } + assertThrows { + parseAction(mapOf("type" to "MESSAGE", "message" to "bad key with spaces")) + } + } + + @Test + fun `parses milestone reward and plans deterministic Inviter delivery`() { + val definition = RewardConfigurationParser.parse( + mapOf( + "config-version" to 1, + "qualification-rewards" to emptyMap(), + "milestone-rewards" to mapOf( + "five-qualified" to mapOf( + "at" to 5, + "inviter" to listOf( + mapOf("type" to "MESSAGE", "message" to "invite.milestone.five"), + ), + ), + ), + ), + ).milestoneRewards.getValue("five-qualified") + val achievedAt = Instant.parse("2026-09-22T00:00:00Z") + + val first = RewardDeliveryPlanner.planMilestone(definition, inviterId, achievedAt) + val replay = RewardDeliveryPlanner.planMilestone(definition, inviterId, achievedAt) + + assertEquals(first, replay) + assertEquals(null, first.delivery.invitationId) + assertEquals(listOf(inviterId), first.actions.map { it.recipientId }) + assertEquals("milestone:$inviterId:5:five-qualified", first.delivery.idempotencyKey) + } + + @Test + fun `rejects non-positive milestone thresholds`() { + assertThrows { + RewardConfigurationParser.parse( + mapOf( + "config-version" to 1, + "qualification-rewards" to emptyMap(), + "milestone-rewards" to mapOf( + "invalid" to mapOf( + "at" to 0, + "inviter" to listOf( + mapOf("type" to "MESSAGE", "message" to "invite.milestone.invalid"), + ), + ), + ), + ), + ) + } + } + + private fun parseAction(action: Map) = RewardConfigurationParser.parse( + mapOf( + "config-version" to 1, + "qualification-rewards" to mapOf( + "test" to mapOf("inviter" to listOf(action), "invitee" to emptyList()), + ), + "milestone-rewards" to emptyMap(), + ), + ) + + private fun invitation() = Invitation( + id = UUID.fromString("00000000-0000-0000-0000-000000000003"), + inviterId = inviterId, + inviteeId = inviteeId, + status = InvitationStatus.QUALIFIED, + claimedAt = Instant.EPOCH, + qualifiedAt = Instant.EPOCH, + qualificationPolicyId = "new-player", + qualificationRevision = "sha256:" + "1".repeat(64), + ) + + companion object { + private val inviterId = UUID.fromString("00000000-0000-0000-0000-000000000001") + private val inviteeId = UUID.fromString("00000000-0000-0000-0000-000000000002") + } +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessorTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessorTest.kt new file mode 100644 index 0000000..f4ec6ce --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardDeliveryProcessorTest.kt @@ -0,0 +1,288 @@ +package io.github.command1264.invitecode.core + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.assertThrows +import java.time.Instant +import java.util.UUID + +class RewardDeliveryProcessorTest { + @Test + fun `failed initial persistence creates no executable action`() { + val records = RecordingRewardRecords().apply { failDeliveryWrite = true } + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + + assertThrows { coordinator.prepare(plan) } + + assertEquals(null, coordinator.action(plan.actions.single().id)) + assertEquals(0, records.saveDeliveryCalls) + } + + @Test + fun `preparing the same logical delivery is idempotent`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + + val first = coordinator.prepare(plan) + val replay = coordinator.prepare(plan) + + assertEquals(first, replay) + assertEquals(1, records.saveDeliveryCalls) + } + + @Test + fun `persists plan and PROCESSING before executing external effect`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + coordinator.prepare(plan) + var effectCalls = 0 + val executor = executor( + execute = { + assertEquals(RewardActionStatus.PROCESSING, records.action(it.id)!!.status) + assertEquals(listOf("save-delivery", "save-action:PROCESSING"), records.events) + effectCalls++ + RewardActionExecutionResult.Delivered + }, + ) + + val result = RewardDeliveryProcessor(coordinator, executor) { Instant.parse("2026-09-22T00:00:01Z") } + .process(plan.actions.single(), context()) + + assertEquals(RewardActionProcessingStatus.DELIVERED, result.status) + assertEquals(1, effectCalls) + assertEquals(RewardActionStatus.DELIVERED, records.action(plan.actions.single().id)!!.status) + } + + @Test + fun `offline recipient remains pending until login retry`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + coordinator.prepare(plan) + var effectCalls = 0 + val processor = RewardDeliveryProcessor( + coordinator, + executor( + readiness = { RewardActionReadiness.RECIPIENT_OFFLINE }, + execute = { effectCalls++; RewardActionExecutionResult.Delivered }, + ), + ) { Instant.parse("2026-09-22T00:00:01Z") } + + val result = processor.process(plan.actions.single(), context()) + + assertEquals(RewardActionProcessingStatus.DEFERRED, result.status) + assertEquals(0, effectCalls) + assertEquals(RewardActionStatus.PENDING, records.action(plan.actions.single().id)!!.status) + assertEquals(listOf(plan.actions.single()), coordinator.pendingForRecipient(recipientId)) + } + + @Test + fun `recipient disconnect after PROCESSING returns action to pending`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + coordinator.prepare(plan) + val processor = RewardDeliveryProcessor( + coordinator, + executor( + execute = { + RewardActionExecutionResult.Deferred(RewardActionReadiness.RECIPIENT_OFFLINE) + }, + ), + ) { Instant.parse("2026-09-22T00:00:01Z") } + + val result = processor.process(plan.actions.single(), context()) + + assertEquals(RewardActionProcessingStatus.DEFERRED, result.status) + assertEquals(RewardActionReadiness.RECIPIENT_OFFLINE, result.readiness) + assertEquals(RewardActionStatus.PENDING, records.action(plan.actions.single().id)!!.status) + assertEquals( + listOf("save-delivery", "save-action:PROCESSING", "save-action:PENDING"), + records.events, + ) + } + + @Test + fun `failed final persistence never repeats an external effect`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + coordinator.prepare(plan) + var effectCalls = 0 + records.failDeliveredWrite = true + val processor = RewardDeliveryProcessor( + coordinator, + executor(execute = { effectCalls++; RewardActionExecutionResult.Delivered }), + ) { Instant.parse("2026-09-22T00:00:01Z") } + + assertThrows { processor.process(plan.actions.single(), context()) } + assertEquals(1, effectCalls) + assertEquals(RewardActionStatus.PROCESSING, records.action(plan.actions.single().id)!!.status) + + val replay = processor.process(plan.actions.single(), context()) + assertEquals(RewardActionProcessingStatus.ALREADY_PROCESSING, replay.status) + assertEquals(1, effectCalls) + + coordinator.recoverInterrupted(Instant.parse("2026-09-22T00:00:02Z")) + assertEquals(RewardActionStatus.UNCERTAIN, records.action(plan.actions.single().id)!!.status) + } + + @Test + fun `executor exception becomes uncertain without exposing exception message`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + coordinator.prepare(plan) + val processor = RewardDeliveryProcessor( + coordinator, + executor(execute = { throw IllegalStateException("secret token value") }), + ) { Instant.parse("2026-09-22T00:00:01Z") } + + val result = processor.process(plan.actions.single(), context()) + + assertEquals(RewardActionProcessingStatus.UNCERTAIN, result.status) + val stored = records.action(plan.actions.single().id)!! + assertEquals(RewardActionStatus.UNCERTAIN, stored.status) + assertTrue(!stored.lastError.orEmpty().contains("secret token value")) + } + + @Test + fun `failed PROCESSING persistence prevents external effect`() { + val records = RecordingRewardRecords() + val coordinator = RewardDeliveryCoordinator(records) + val plan = plan() + coordinator.prepare(plan) + records.failProcessingWrite = true + var effectCalls = 0 + val processor = RewardDeliveryProcessor( + coordinator, + executor(execute = { effectCalls++; RewardActionExecutionResult.Delivered }), + ) { Instant.parse("2026-09-22T00:00:01Z") } + + assertThrows { processor.process(plan.actions.single(), context()) } + + assertEquals(0, effectCalls) + assertEquals(RewardActionStatus.PENDING, records.action(plan.actions.single().id)!!.status) + } + + private fun executor( + readiness: (StoredRewardAction) -> RewardActionReadiness = { RewardActionReadiness.READY }, + execute: (StoredRewardAction) -> RewardActionExecutionResult, + ) = object : RewardActionExecutor { + override fun readiness( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ) = readiness(action) + + override fun execute( + action: StoredRewardAction, + context: RewardActionExecutionContext, + ) = execute(action) + } + + private fun plan(): RewardDeliveryPlan { + val deliveryId = UUID.fromString("00000000-0000-0000-0000-000000000010") + val at = Instant.parse("2026-09-22T00:00:00Z") + return RewardDeliveryPlan( + StoredRewardDelivery( + deliveryId, invitationId, "default", RewardDeliveryStatus.PENDING, + "qualification:$invitationId:default", at, at, + ), + listOf( + StoredRewardAction( + actionId, deliveryId, invitationId, recipientId, 0, "MESSAGE", "invite.qualified", + RewardActionStatus.PENDING, "action-key", at, at, + ), + ), + ) + } + + private fun context() = RewardActionExecutionContext( + recipientId = recipientId, + recipientName = "Invitee", + inviterId = UUID.fromString("00000000-0000-0000-0000-000000000001"), + inviterName = "Inviter", + inviteeId = recipientId, + inviteeName = "Invitee", + ) + + companion object { + private val invitationId = UUID.fromString("00000000-0000-0000-0000-000000000003") + private val recipientId = UUID.fromString("00000000-0000-0000-0000-000000000002") + private val actionId = UUID.fromString("00000000-0000-0000-0000-000000000011") + } +} + +private class RecordingRewardRecords : RewardRecords { + private var delivery: StoredRewardDelivery? = null + private val actions = linkedMapOf() + val events = mutableListOf() + var failProcessingWrite = false + var failDeliveredWrite = false + var failDeliveryWrite = false + var saveDeliveryCalls = 0 + + override fun qualifiedInvitationCount(inviterId: UUID) = 0 + + override fun saveRewardDelivery(delivery: StoredRewardDelivery, actions: List) { + if (failDeliveryWrite) error("delivery write failed") + this.delivery = delivery + this.actions.putAll(actions.associateBy { it.id }) + saveDeliveryCalls++ + events += "save-delivery" + } + + override fun rewardDelivery(deliveryId: UUID): StoredRewardDelivery? = + delivery?.takeIf { it.id == deliveryId } + + override fun rewardActions(deliveryId: UUID): List = + actions.values.filter { it.rewardDeliveryId == deliveryId }.sortedBy { it.position } + + override fun rewardAction(actionId: UUID): StoredRewardAction? = actions[actionId] + + fun action(actionId: UUID) = actions[actionId] + + override fun saveRewardAction(action: StoredRewardAction) { + if (action.status == RewardActionStatus.PROCESSING && failProcessingWrite) error("processing write failed") + if (action.status == RewardActionStatus.DELIVERED && failDeliveredWrite) error("delivered write failed") + actions[action.id] = action + events += "save-action:${action.status}" + } + + override fun pendingRewardActions(recipientId: UUID): List = + actions.values.filter { it.recipientId == recipientId && it.status == RewardActionStatus.PENDING } + + override fun recoverInterruptedRewardActions(recoveredAt: Instant): Int { + val interrupted = actions.values.filter { it.status == RewardActionStatus.PROCESSING } + interrupted.forEach { + actions[it.id] = it.copy( + status = RewardActionStatus.UNCERTAIN, + updatedAt = recoveredAt, + lastError = "Interrupted while processing; delivery result is unknown.", + ) + } + return interrupted.size + } + + override fun resolveUncertainRewardAction( + actionId: UUID, + resolution: UncertainRewardActionResolution, + context: RewardAdministrationContext, + ): StoredRewardAction { + val current = requireNotNull(actions[actionId]) + val resolved = current.copy( + status = when (resolution) { + UncertainRewardActionResolution.RETRY -> RewardActionStatus.PENDING + UncertainRewardActionResolution.MARK_DELIVERED -> RewardActionStatus.DELIVERED + }, + updatedAt = context.occurredAt, + lastError = null, + ) + actions[actionId] = resolved + return resolved + } +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardTriggerServiceTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardTriggerServiceTest.kt new file mode 100644 index 0000000..a7061fa --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/RewardTriggerServiceTest.kt @@ -0,0 +1,86 @@ +package io.github.command1264.invitecode.core + +import io.github.command1264.invitecode.api.InvitationStatus +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.time.Instant +import java.util.UUID + +class RewardTriggerServiceTest { + @Test + fun `qualification prepares qualification and newly reached milestone rewards once`() { + val records = TriggerRewardRecords(qualifiedCount = 5) + val service = RewardTriggerService(records) + val configuration = RewardConfiguration( + version = 1, + qualificationRewards = mapOf( + "default" to QualificationRewardDefinition( + "default", + inviterActions = listOf(RewardActionDefinition(RewardActionType.MESSAGE, "qualified.inviter")), + inviteeActions = emptyList(), + ), + ), + milestoneRewards = mapOf( + "five" to MilestoneRewardDefinition( + "five", + 5, + listOf(RewardActionDefinition(RewardActionType.MESSAGE, "milestone.five")), + ), + ), + ) + + val first = service.prepareForQualification(invitation(), configuration) + val replay = service.prepareForQualification(invitation(), configuration) + + assertEquals(2, first.size) + assertEquals(first, replay) + assertEquals(2, records.saveDeliveryCalls) + assertEquals(setOf("default", "five"), first.map { it.delivery.rewardId }.toSet()) + } + + private fun invitation() = Invitation( + invitationId, + inviterId, + inviteeId, + InvitationStatus.QUALIFIED, + Instant.EPOCH, + Instant.parse("2026-09-22T00:00:00Z"), + "new-player", + "sha256:" + "1".repeat(64), + ) + + companion object { + private val invitationId = UUID.fromString("00000000-0000-0000-0000-000000000003") + private val inviterId = UUID.fromString("00000000-0000-0000-0000-000000000001") + private val inviteeId = UUID.fromString("00000000-0000-0000-0000-000000000002") + } +} + +private class TriggerRewardRecords( + private val qualifiedCount: Int, +) : RewardRecords { + private val deliveries = linkedMapOf() + private val actions = linkedMapOf() + var saveDeliveryCalls = 0 + + override fun qualifiedInvitationCount(inviterId: UUID) = qualifiedCount + + override fun saveRewardDelivery(delivery: StoredRewardDelivery, actions: List) { + deliveries[delivery.id] = delivery + this.actions.putAll(actions.associateBy { it.id }) + saveDeliveryCalls++ + } + + override fun rewardDelivery(deliveryId: UUID) = deliveries[deliveryId] + override fun rewardActions(deliveryId: UUID) = actions.values.filter { it.rewardDeliveryId == deliveryId } + override fun rewardAction(actionId: UUID) = actions[actionId] + override fun saveRewardAction(action: StoredRewardAction) { actions[action.id] = action } + override fun pendingRewardActions(recipientId: UUID) = + actions.values.filter { it.recipientId == recipientId && it.status == RewardActionStatus.PENDING } + override fun recoverInterruptedRewardActions(recoveredAt: Instant) = 0 + override fun resolveUncertainRewardAction( + actionId: UUID, + resolution: UncertainRewardActionResolution, + context: RewardAdministrationContext, + ) = error("Not needed by this test") +} diff --git a/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutorTest.kt b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutorTest.kt new file mode 100644 index 0000000..a1fa4d6 --- /dev/null +++ b/invitecode-core/src/test/kotlin/io/github/command1264/invitecode/core/StandardRewardActionExecutorTest.kt @@ -0,0 +1,162 @@ +package io.github.command1264.invitecode.core + +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Test +import java.math.BigDecimal +import java.time.Instant +import java.util.UUID + +class StandardRewardActionExecutorTest { + @Test + fun `console command expands only validated execution context placeholders`() { + val environment = RecordingRewardEnvironment() + val executor = StandardRewardActionExecutor(environment) + val action = action("CONSOLE_COMMAND", "give {recipient_name} diamond 1") + + val result = executor.execute(action, context()) + + assertEquals(RewardActionExecutionResult.Delivered, result) + assertEquals(listOf("give Invitee diamond 1"), environment.consoleCommands) + } + + @Test + fun `player command requires online recipient and never requests operator state`() { + val environment = RecordingRewardEnvironment(online = false) + val executor = StandardRewardActionExecutor(environment) + val action = action("PLAYER_COMMAND", "spawn") + + assertEquals(RewardActionReadiness.RECIPIENT_OFFLINE, executor.readiness(action, context())) + assertEquals(emptyList(), environment.playerCommands) + } + + @Test + fun `player disconnect before dispatch defers delivery`() { + val environment = RecordingRewardEnvironment(onlineActionResult = OnlineRewardActionResult.RECIPIENT_OFFLINE) + val executor = StandardRewardActionExecutor(environment) + val action = action("PLAYER_COMMAND", "spawn") + + val result = executor.execute(action, context()) + + assertEquals( + RewardActionExecutionResult.Deferred(RewardActionReadiness.RECIPIENT_OFFLINE), + result, + ) + assertEquals(listOf("spawn"), environment.playerCommands) + } + + @Test + fun `message sends locale key only when recipient is online`() { + val environment = RecordingRewardEnvironment() + val executor = StandardRewardActionExecutor(environment) + val action = action("MESSAGE", "invite.qualified.invitee") + + val result = executor.execute(action, context()) + + assertEquals(RewardActionExecutionResult.Delivered, result) + assertEquals(listOf("invite.qualified.invitee"), environment.messages) + } + + @Test + fun `Vault action stays pending when economy integration is unavailable`() { + val environment = RecordingRewardEnvironment(economyAvailable = false) + val executor = StandardRewardActionExecutor(environment) + val action = action("VAULT_ECONOMY", "100.5") + + assertEquals(RewardActionReadiness.INTEGRATION_UNAVAILABLE, executor.readiness(action, context())) + assertEquals(emptyList(), environment.deposits) + } + + @Test + fun `Vault rejection is a terminal failure`() { + val environment = RecordingRewardEnvironment(economyAccepted = false) + val executor = StandardRewardActionExecutor(environment) + val action = action("VAULT_ECONOMY", "100.5") + + val result = executor.execute(action, context()) + + assertEquals( + RewardActionExecutionResult.Failed("Vault economy deposit was rejected."), + result, + ) + assertEquals(listOf(BigDecimal("100.5")), environment.deposits) + } + + @Test + fun `missing command placeholder context fails before dispatch`() { + val environment = RecordingRewardEnvironment() + val executor = StandardRewardActionExecutor(environment) + val action = action("CONSOLE_COMMAND", "give {inviter_name} diamond 1") + val contextWithoutInviterName = context().copy(inviterName = null) + + val result = executor.execute(action, contextWithoutInviterName) + + assertEquals( + RewardActionExecutionResult.Failed("Reward command context is invalid."), + result, + ) + assertEquals(emptyList(), environment.consoleCommands) + } + + private fun action(type: String, payload: String) = StoredRewardAction( + id = UUID.randomUUID(), + rewardDeliveryId = UUID.randomUUID(), + invitationId = UUID.randomUUID(), + recipientId = recipientId, + position = 0, + type = type, + payload = payload, + status = RewardActionStatus.PROCESSING, + idempotencyKey = "test-action", + createdAt = Instant.EPOCH, + updatedAt = Instant.EPOCH.plusNanos(1), + ) + + private fun context() = RewardActionExecutionContext( + recipientId, + "Invitee", + UUID.fromString("00000000-0000-0000-0000-000000000001"), + "Inviter", + recipientId, + "Invitee", + ) + + companion object { + private val recipientId = UUID.fromString("00000000-0000-0000-0000-000000000002") + } +} + +private class RecordingRewardEnvironment( + private val online: Boolean = true, + private val economyAvailable: Boolean = true, + private val economyAccepted: Boolean = true, + private val onlineActionResult: OnlineRewardActionResult = OnlineRewardActionResult.ACCEPTED, +) : RewardExecutionEnvironment { + val consoleCommands = mutableListOf() + val playerCommands = mutableListOf() + val messages = mutableListOf() + val deposits = mutableListOf() + + override fun isOnline(playerId: UUID) = online + + override fun dispatchConsole(command: String): Boolean { + consoleCommands += command + return true + } + + override fun dispatchPlayer(playerId: UUID, command: String): OnlineRewardActionResult { + playerCommands += command + return onlineActionResult + } + + override fun sendMessage(playerId: UUID, localeKey: String): OnlineRewardActionResult { + messages += localeKey + return onlineActionResult + } + + override fun economyAvailable() = economyAvailable + + override fun deposit(playerId: UUID, amount: BigDecimal): Boolean { + deposits += amount + return economyAccepted + } +} diff --git a/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt new file mode 100644 index 0000000..9525e4b --- /dev/null +++ b/invitecode-platform-bukkit/src/main/kotlin/io/github/command1264/invitecode/platform/bukkit/BukkitRewardExecutionEnvironment.kt @@ -0,0 +1,77 @@ +package io.github.command1264.invitecode.platform.bukkit + +import io.github.command1264.invitecode.core.OnlineRewardActionResult +import io.github.command1264.invitecode.core.RewardExecutionEnvironment +import org.bukkit.Bukkit +import org.bukkit.Server +import org.bukkit.plugin.Plugin +import java.math.BigDecimal +import java.util.UUID +import java.util.concurrent.Callable +import java.util.concurrent.ExecutionException + +fun interface RewardMessageResolver { + fun resolve(playerId: UUID, localeKey: String): String +} + +fun interface EconomyRewardGateway { + fun deposit(playerId: UUID, amount: BigDecimal): Boolean +} + +class BukkitMainThreadExecutor( + private val server: Server, + private val plugin: Plugin, +) { + fun call(operation: () -> T): T { + if (Bukkit.isPrimaryThread()) return operation() + return try { + server.scheduler.callSyncMethod(plugin, Callable(operation)).get() + } catch (error: InterruptedException) { + Thread.currentThread().interrupt() + throw IllegalStateException("Interrupted while waiting for a Bukkit main-thread Reward operation.", error) + } catch (error: ExecutionException) { + val cause = error.cause ?: error + if (cause is RuntimeException) throw cause + throw IllegalStateException("Bukkit main-thread Reward operation failed.", cause) + } + } +} + +class BukkitRewardExecutionEnvironment( + private val server: Server, + private val mainThread: BukkitMainThreadExecutor, + private val messages: RewardMessageResolver, + private val economy: EconomyRewardGateway? = null, +) : RewardExecutionEnvironment { + override fun isOnline(playerId: UUID): Boolean = mainThread.call { + server.getPlayer(playerId)?.isOnline == true + } + + override fun dispatchConsole(command: String): Boolean = mainThread.call { + server.dispatchCommand(server.consoleSender, command) + } + + override fun dispatchPlayer(playerId: UUID, command: String): OnlineRewardActionResult = mainThread.call { + val player = server.getPlayer(playerId) + ?: return@call OnlineRewardActionResult.RECIPIENT_OFFLINE + if (player.performCommand(command)) { + OnlineRewardActionResult.ACCEPTED + } else { + OnlineRewardActionResult.REJECTED + } + } + + override fun sendMessage(playerId: UUID, localeKey: String): OnlineRewardActionResult = mainThread.call { + val player = server.getPlayer(playerId) + ?: return@call OnlineRewardActionResult.RECIPIENT_OFFLINE + player.sendMessage(messages.resolve(playerId, localeKey)) + OnlineRewardActionResult.ACCEPTED + } + + override fun economyAvailable(): Boolean = economy != null + + override fun deposit(playerId: UUID, amount: BigDecimal): Boolean = mainThread.call { + requireNotNull(economy) { "Vault economy integration is unavailable." } + .deposit(playerId, amount) + } +} diff --git a/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt new file mode 100644 index 0000000..9857dab --- /dev/null +++ b/invitecode-plugin/src/main/kotlin/io/github/command1264/invitecode/plugin/VaultEconomyRewardGateway.kt @@ -0,0 +1,26 @@ +package io.github.command1264.invitecode.plugin + +import io.github.command1264.invitecode.platform.bukkit.EconomyRewardGateway +import net.milkbowl.vault.economy.Economy +import org.bukkit.Server +import java.math.BigDecimal +import java.util.UUID + +class VaultEconomyRewardGateway private constructor( + private val server: Server, + private val economy: Economy, +) : EconomyRewardGateway { + override fun deposit(playerId: UUID, amount: BigDecimal): Boolean { + val value = amount.toDouble() + require(value.isFinite() && value > 0.0) { "Vault economy amount is outside the supported range." } + return economy.depositPlayer(server.getOfflinePlayer(playerId), value).transactionSuccess() + } + + companion object { + fun find(server: Server): VaultEconomyRewardGateway? { + if (!server.pluginManager.isPluginEnabled("Vault")) return null + val provider = server.servicesManager.getRegistration(Economy::class.java)?.provider ?: return null + return VaultEconomyRewardGateway(server, provider) + } + } +} diff --git a/invitecode-plugin/src/main/resources/rewards.yml b/invitecode-plugin/src/main/resources/rewards.yml index 7afd031..2ee8c9a 100644 --- a/invitecode-plugin/src/main/resources/rewards.yml +++ b/invitecode-plugin/src/main/resources/rewards.yml @@ -10,3 +10,10 @@ qualification-rewards: message: invite.qualified.invitee milestone-rewards: {} +# 範例:將上一行的 {} 改成下列內容,會在 Inviter 累積 5 筆 Qualified Invitation 時發送一次。 +# milestone-rewards: +# five-qualified: +# at: 5 +# inviter: +# - type: MESSAGE +# message: invite.milestone.five diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt index 370c31b..024c797 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInvitationRecords.kt @@ -129,6 +129,18 @@ internal object SqliteInvitationRecords { ) } } + + fun countQualifiedForInviter(connection: Connection, inviterId: UUID): Int = + connection.prepareStatement( + "SELECT COUNT(*) FROM invitecode_invitations WHERE inviter_id = ? AND status = ?", + ).use { statement -> + statement.setString(1, inviterId.toString()) + statement.setString(2, InvitationStatus.QUALIFIED.name) + statement.executeQuery().use { result -> + check(result.next()) { "Qualified Invitation count query returned no row." } + result.getInt(1) + } + } } internal object SqliteQualificationRecords { diff --git a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt index accba39..0e79139 100644 --- a/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt +++ b/invitecode-storage-sql/src/main/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorage.kt @@ -31,6 +31,10 @@ class SqliteInviteCodeStorage private constructor( private val database: Path, private val blockingOperationGuard: BlockingOperationGuard, ) : InviteCodeStorage { + override fun qualifiedInvitationCount(inviterId: UUID): Int = read { + SqliteInvitationRecords.countQualifiedForInviter(it, inviterId) + } + override fun savePlayer(player: StoredPlayer) { write { SqlitePlayerRecords.save(it, player) } } diff --git a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt index af70b14..cd3b495 100644 --- a/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt +++ b/invitecode-storage-sql/src/test/kotlin/io/github/command1264/invitecode/storage/sql/SqliteInviteCodeStorageTest.kt @@ -467,6 +467,55 @@ class SqliteInviteCodeStorageTest { } } + @Test + fun `qualified Invitation count excludes claimed Invitations`() { + val database = temporaryDirectory.resolve("qualified-invitation-count.db") + val guard = BlockingOperationGuard { } + val inviterId = UUID.fromString("00000000-0000-0000-0000-000000000071") + val qualifiedInviteeId = UUID.fromString("00000000-0000-0000-0000-000000000072") + val claimedInviteeId = UUID.fromString("00000000-0000-0000-0000-000000000073") + val qualified = Invitation( + UUID.fromString("10000000-0000-0000-0000-000000000071"), + inviterId, + qualifiedInviteeId, + InvitationStatus.CLAIMED, + Instant.EPOCH, + ).qualify(Instant.EPOCH.plusSeconds(1), "default", "revision-1") + val claimed = Invitation( + UUID.fromString("10000000-0000-0000-0000-000000000072"), + inviterId, + claimedInviteeId, + InvitationStatus.CLAIMED, + Instant.EPOCH, + ) + val fact = QualificationFact( + UUID.fromString("20000000-0000-0000-0000-000000000071"), + qualified.id, + "default", + "revision-1", + "play-time", + QualificationFactOutcome.SATISFIED, + Instant.EPOCH.plusSeconds(1), + ) + + SqliteSchemaMigrator(database, guard).migrate() + SqliteInviteCodeStorage.open(database, guard).use { storage -> + listOf(inviterId, qualifiedInviteeId, claimedInviteeId).forEach { + storage.savePlayer(StoredPlayer(it, Instant.EPOCH)) + } + storage.saveInvitation(qualified.copy( + status = InvitationStatus.CLAIMED, + qualifiedAt = null, + qualificationPolicyId = null, + qualificationRevision = null, + )) + storage.saveInvitation(claimed) + storage.saveQualifiedInvitation(qualified, listOf(fact)) + + assertEquals(1, storage.qualifiedInvitationCount(inviterId)) + } + } + @Test fun `Reward Delivery and all actions roll back together`() { val database = temporaryDirectory.resolve("reward-rollback.db") @@ -818,6 +867,46 @@ class SqliteInviteCodeStorageTest { } } + @Test + fun `Reward Action can return to pending when recipient disconnects before the effect`() { + val database = temporaryDirectory.resolve("reward-deferred-after-processing.db") + val guard = BlockingOperationGuard { } + val recipientId = UUID.fromString("00000000-0000-0000-0000-0000000000b2") + val delivery = StoredRewardDelivery( + UUID.fromString("31000000-0000-0000-0000-0000000000b2"), null, "deferred", + RewardDeliveryStatus.PENDING, "deferred-delivery", Instant.EPOCH, Instant.EPOCH, + ) + val pending = StoredRewardAction( + UUID.fromString("30000000-0000-0000-0000-0000000000b2"), delivery.id, null, + recipientId, 0, "player-command", "kit starter", RewardActionStatus.PENDING, + "deferred-action", Instant.EPOCH, Instant.EPOCH, + ) + val processingAt = Instant.parse("2026-09-22T10:00:00Z") + val deferredAt = processingAt.plusNanos(1) + + SqliteSchemaMigrator(database, guard).migrate() + SqliteInviteCodeStorage.open(database, guard).use { storage -> + storage.savePlayer(StoredPlayer(recipientId, Instant.EPOCH)) + storage.saveRewardDelivery(delivery, listOf(pending)) + storage.saveRewardAction(pending.copy( + status = RewardActionStatus.PROCESSING, + updatedAt = processingAt, + )) + storage.saveRewardAction(pending.copy(updatedAt = deferredAt)) + + assertEquals(RewardActionStatus.PENDING, storage.rewardAction(pending.id)!!.status) + assertEquals(RewardDeliveryStatus.PENDING, storage.rewardDelivery(delivery.id)!!.status) + assertEquals( + listOf( + RewardActionStatus.PENDING, + RewardActionStatus.PROCESSING, + RewardActionStatus.PENDING, + ), + storage.rewardActionTransitions(pending.id).map { it.currentStatus }, + ) + } + } + @Test fun `Reward Delivery rejects a completed state with pending Actions`() { val database = temporaryDirectory.resolve("reward-aggregate-state.db")