Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
774e80d9d5
|
||
|
|
505cfe38f0
|
||
|
|
85bcdcadb8
|
||
|
|
e67c475c38
|
||
|
|
07983dc5b0
|
||
|
|
5e9587b93f
|
||
|
|
fd62f2574d
|
||
|
|
828bd0639e
|
||
|
|
da13b0d2b8
|
||
|
|
d632dc0f6b
|
||
|
|
b60e4aa457
|
||
|
|
e262f35b27
|
||
|
|
77e4cab8ad
|
||
|
|
7291419c9f
|
||
|
|
b2b8fcf92f
|
||
|
|
4e4b307275
|
||
|
|
e87a36caa5
|
||
|
|
e2d7942c7e
|
@@ -0,0 +1,26 @@
|
|||||||
|
# Version control
|
||||||
|
.git
|
||||||
|
.github
|
||||||
|
|
||||||
|
# Gradle build outputs / caches (must always be rebuilt fresh inside the image)
|
||||||
|
.gradle
|
||||||
|
build/
|
||||||
|
.kotlin
|
||||||
|
!gradle/wrapper/gradle-wrapper.jar
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
.run
|
||||||
|
*.iml
|
||||||
|
*.iws
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
# Docker-only local files (secrets/env must never be baked into the image)
|
||||||
|
docker/.env
|
||||||
|
docker/*.env.docker
|
||||||
|
docker/*.secret
|
||||||
|
|
||||||
|
# Misc
|
||||||
|
*.hprof
|
||||||
|
.gradle-docker-cache/
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
* text=auto
|
||||||
|
* eol=lf
|
||||||
|
*.sh text eol=lf
|
||||||
|
*.png binary
|
||||||
|
*.jar binary
|
||||||
|
gradlew.bat eol=crlf
|
||||||
|
gradlew text eol=lf
|
||||||
+49
-33
@@ -18,10 +18,10 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Set up JDK 21
|
- name: Set up JDK 21
|
||||||
uses: actions/setup-java@v4
|
uses: actions/setup-java@v5
|
||||||
with:
|
with:
|
||||||
distribution: 'temurin'
|
distribution: 'temurin'
|
||||||
java-version: '21'
|
java-version: '21'
|
||||||
@@ -31,7 +31,7 @@ jobs:
|
|||||||
run: echo "key=gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}" >> $GITHUB_OUTPUT
|
run: echo "key=gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
- name: Cache Gradle dependencies
|
- name: Cache Gradle dependencies
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@@ -48,16 +48,16 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Set up JDK 21
|
- name: Set up JDK 21
|
||||||
uses: actions/setup-java@v4
|
uses: actions/setup-java@v5
|
||||||
with:
|
with:
|
||||||
distribution: 'temurin'
|
distribution: 'temurin'
|
||||||
java-version: '21'
|
java-version: '21'
|
||||||
|
|
||||||
- name: Restore Gradle cache
|
- name: Restore Gradle cache
|
||||||
uses: actions/cache@v3
|
uses: actions/cache@v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@@ -70,58 +70,74 @@ jobs:
|
|||||||
run: chmod +x gradlew
|
run: chmod +x gradlew
|
||||||
|
|
||||||
- name: Run lint
|
- name: Run lint
|
||||||
run: ./gradlew ktlintCheck
|
# Path scoped to :backend on purpose: :composeApp applies the Android Gradle plugin,
|
||||||
|
# which needs an Android SDK to even configure. Keeping every gradlew invocation on a
|
||||||
|
# fully-qualified project path (with org.gradle.configureondemand=true) lets CI skip
|
||||||
|
# configuring :composeApp entirely, so no Android SDK setup is needed on this runner.
|
||||||
|
run: ./gradlew :backend:ktlintCheck
|
||||||
|
|
||||||
- name: Publish ktlint report
|
- name: Publish ktlint report
|
||||||
uses: yutailang0119/action-ktlint@v4
|
uses: yutailang0119/action-ktlint@v5
|
||||||
if: always()
|
if: always()
|
||||||
with:
|
with:
|
||||||
report-path: build/reports/ktlint/**/*.xml
|
report-path: backend/build/reports/ktlint/**/*.xml
|
||||||
continue-on-error: false
|
continue-on-error: false
|
||||||
|
|
||||||
test:
|
test:
|
||||||
needs: build
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
env:
|
||||||
|
GRADLE_CACHE_DIR: ${{ github.workspace }}/.gradle-docker-cache
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout code
|
- name: Checkout code
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v6
|
||||||
|
|
||||||
- name: Set up JDK 21
|
- name: Install a pinned Docker Compose version
|
||||||
uses: actions/setup-java@v4
|
run: |
|
||||||
with:
|
mkdir -p ~/.docker/cli-plugins
|
||||||
distribution: 'temurin'
|
curl -fSL https://github.com/docker/compose/releases/download/v5.1.4/docker-compose-linux-x86_64 \
|
||||||
java-version: '21'
|
-o ~/.docker/cli-plugins/docker-compose
|
||||||
|
chmod +x ~/.docker/cli-plugins/docker-compose
|
||||||
|
docker compose version
|
||||||
|
|
||||||
- name: Restore Gradle cache
|
- name: Prepare docker secrets
|
||||||
uses: actions/cache@v3
|
run: |
|
||||||
|
[ -f docker/postgresql.secret ] || echo -n "changeit" > docker/postgresql.secret
|
||||||
|
|
||||||
|
- name: Generate cache key
|
||||||
|
id: cache-key-generator
|
||||||
|
run: echo "key=gradle-docker-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Restore Gradle cache (Docker)
|
||||||
|
uses: actions/cache@v6
|
||||||
with:
|
with:
|
||||||
path: |
|
path: ${{ env.GRADLE_CACHE_DIR }}
|
||||||
~/.gradle/caches
|
key: ${{ steps.cache-key-generator.outputs.key }}
|
||||||
~/.gradle/wrapper
|
|
||||||
key: ${{ needs.build.outputs.cache-key }}
|
|
||||||
restore-keys: |
|
restore-keys: |
|
||||||
gradle-${{ runner.os }}-
|
gradle-docker-${{ runner.os }}-
|
||||||
|
|
||||||
- name: Grant execute permission to Gradle wrapper
|
- name: Prepare cache directory permissions
|
||||||
run: chmod +x gradlew
|
run: |
|
||||||
|
mkdir -p "$GRADLE_CACHE_DIR"
|
||||||
|
chmod -R 777 "$GRADLE_CACHE_DIR"
|
||||||
|
|
||||||
- name: Start CI Docker Compose services
|
- name: Run tests in Docker
|
||||||
run: ./gradlew composeUp -Pci
|
run: docker compose -f docker/docker-compose-test.yaml run tests
|
||||||
|
|
||||||
- name: Run tests
|
- name: Shut down Docker services
|
||||||
run: ./gradlew test -x composeUp --no-daemon
|
if: always()
|
||||||
|
run: docker compose -f docker/docker-compose-test.yaml down -v
|
||||||
|
|
||||||
- name: Upload test reports
|
- name: Upload test reports
|
||||||
if: always()
|
if: always()
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v7
|
||||||
with:
|
with:
|
||||||
name: test-results
|
name: test-results
|
||||||
path: build/reports/tests/test
|
path: backend/build/reports/tests/test
|
||||||
|
|
||||||
- name: Publish Test Report
|
- name: Publish Test Report
|
||||||
uses: dorny/test-reporter@v1
|
uses: dorny/test-reporter@v3
|
||||||
if: always()
|
if: always()
|
||||||
with:
|
with:
|
||||||
name: JUnit Tests
|
name: JUnit Tests
|
||||||
path: build/test-results/test/TEST-*.xml
|
path: backend/build/test-results/test/TEST-*.xml
|
||||||
reporter: java-junit
|
reporter: java-junit
|
||||||
@@ -1,9 +1,15 @@
|
|||||||
.gradle
|
.gradle
|
||||||
|
.kotlin/
|
||||||
build/
|
build/
|
||||||
!gradle/wrapper/gradle-wrapper.jar
|
!gradle/wrapper/gradle-wrapper.jar
|
||||||
!**/src/main/**/build/
|
!**/src/main/**/build/
|
||||||
!**/src/test/**/build/
|
!**/src/test/**/build/
|
||||||
|
|
||||||
|
### Android / KMP ###
|
||||||
|
local.properties
|
||||||
|
captures/
|
||||||
|
.cxx/
|
||||||
|
|
||||||
### STS ###
|
### STS ###
|
||||||
.apt_generated
|
.apt_generated
|
||||||
.classpath
|
.classpath
|
||||||
@@ -37,3 +43,4 @@ out/
|
|||||||
/docker/.env
|
/docker/.env
|
||||||
/docker/*.secret
|
/docker/*.secret
|
||||||
*.hprof
|
*.hprof
|
||||||
|
/.gradle-docker-cache/
|
||||||
|
|||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
<DataSourcesHistory>
|
||||||
|
<DataSourceFromHistory isRemovedFromProject="false">
|
||||||
|
<data-source source="LOCAL" name="event-demo@localhost" uuid="af2eabb1-64f7-49de-a94f-be1560baa96a">
|
||||||
|
<database-info product="PostgreSQL" version="18.4 (Debian 18.4-1.pgdg13+1)" jdbc-version="4.2" driver-name="PostgreSQL JDBC Driver" driver-version="42.7.3" dbms="POSTGRES" exact-version="18.4" exact-driver-version="42.7">
|
||||||
|
<identifier-quote-string>"</identifier-quote-string>
|
||||||
|
</database-info>
|
||||||
|
<case-sensitivity plain-identifiers="lower" quoted-identifiers="exact" />
|
||||||
|
<driver-ref>postgresql</driver-ref>
|
||||||
|
<synchronize>true</synchronize>
|
||||||
|
<jdbc-driver>org.postgresql.Driver</jdbc-driver>
|
||||||
|
<jdbc-url>jdbc:postgresql://localhost:5432/event-demo</jdbc-url>
|
||||||
|
<secret-storage>master_key</secret-storage>
|
||||||
|
<user-name>event-demo</user-name>
|
||||||
|
<schema-mapping>
|
||||||
|
<introspection-scope>
|
||||||
|
<node negative="1">
|
||||||
|
<node kind="database" qname="@">
|
||||||
|
<node kind="schema" qname="@" />
|
||||||
|
</node>
|
||||||
|
<node kind="database" qname="event-demo">
|
||||||
|
<node kind="schema">
|
||||||
|
<name qname="auth" />
|
||||||
|
<name qname="game" />
|
||||||
|
</node>
|
||||||
|
</node>
|
||||||
|
</node>
|
||||||
|
</introspection-scope>
|
||||||
|
</schema-mapping>
|
||||||
|
<working-dir>$ProjectFileDir$</working-dir>
|
||||||
|
</data-source>
|
||||||
|
</DataSourceFromHistory>
|
||||||
|
</DataSourcesHistory>
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# CLAUDE.md — event-demo
|
||||||
|
|
||||||
|
Ce fichier donne le contexte du projet pour toute session Claude Code future sur ce dépôt.
|
||||||
|
|
||||||
|
## Vue d'ensemble
|
||||||
|
|
||||||
|
`event-demo` est un projet démo personnel (Fabrice Lecomte) qui illustre plusieurs patterns
|
||||||
|
d'architecture backend :
|
||||||
|
|
||||||
|
- Event Sourcing
|
||||||
|
- Event-Driven (bus d'événements asynchrone)
|
||||||
|
- CQRS (séparation commandes / projections en lecture)
|
||||||
|
- Architecture Hexagonale (ports & adapters), un dossier par *bounded context*
|
||||||
|
|
||||||
|
Le cas d'usage servant de support est un jeu de cartes façon UNO (créer une partie, rejoindre,
|
||||||
|
jouer une carte, piocher, etc.), avec authentification des joueurs.
|
||||||
|
|
||||||
|
Dépôts distants configurés : `gitea` (auto-hébergé, git.gogn.synology.me — remote historique)
|
||||||
|
et `github` (`flecomte/event-demo`, miroir). Vérifier vers lequel pousser selon le contexte.
|
||||||
|
|
||||||
|
## Stack technique
|
||||||
|
|
||||||
|
- **Langage** : Kotlin 2.1.21, JDK 21 (toolchain Gradle)
|
||||||
|
- **Framework serveur** : Ktor 3.5.1 (Netty), DI via Koin 4.2.1
|
||||||
|
- **Sérialisation** : kotlinx.serialization (JSON)
|
||||||
|
- **Persistance** :
|
||||||
|
- PostgreSQL (event store, via HikariCP) + migrations Flyway (`migrations/events/`)
|
||||||
|
- RabbitMQ (bus d'événements / bus de commandes, via amqp-client)
|
||||||
|
- **Auth** : JWT (ktor-server-auth-jwt), hash de mot de passe via password4j
|
||||||
|
- **Infra dev/prod** : Docker Compose (fichiers `docker/docker-compose-{dev,test,prod}.yaml`
|
||||||
|
incluant des « parts » réutilisables dans `docker/parts/`), reverse proxy Træfik
|
||||||
|
- **Tests** : Kotest (runner JUnit5), MockK, kotest-extensions-koin, ArchUnit (test d'architecture)
|
||||||
|
- **Qualité** : ktlint (`ktlint_official`, standard + experimental activés), reporting checkstyle
|
||||||
|
- **CI** : GitHub Actions (`.github/workflows/tests.yml`) — build/cache Gradle, `ktlintCheck`,
|
||||||
|
puis tests exécutés **dans Docker** (`docker compose -f docker/docker-compose-test.yaml run tests`)
|
||||||
|
- **API** : documentée en OpenAPI (`resources/openapi/documentation.yaml`)
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
Un dossier par *bounded context* sous `src/main/kotlin/eventDemo/contexts/<context>/`, chacun
|
||||||
|
strictement découpé en 3 couches :
|
||||||
|
|
||||||
|
- `domain/` — aucune dépendance vers les autres couches
|
||||||
|
- `application/` — ne dépend que de `domain`
|
||||||
|
- `infrastructure/` — dépend de `domain` et `application`
|
||||||
|
|
||||||
|
Contexts actuels :
|
||||||
|
|
||||||
|
- **`auth`** : `User`, création de compte, login JWT, event store dédié (Postgresql),
|
||||||
|
projection utilisateur.
|
||||||
|
- **`game`** : cœur du jeu — `Card`, `DrawPile`/`DiscardPile`, `Player`, `GameId`, commandes
|
||||||
|
(`JoinTheGameCommand`, `PlayCardCommand`, `ReadyToPlayCommand`, `TakeCartFromDrawPileCommand`),
|
||||||
|
state machine du jeu via `sealed interface Game` (`GameInit` → `GameCreated` → `GameStarted` →
|
||||||
|
`GameEnded`), notifications, projections (liste de parties), listeners/réactions.
|
||||||
|
|
||||||
|
Libs transverses dans `libs/` (indépendantes de tout contexte) :
|
||||||
|
|
||||||
|
- `bus/` — abstraction `Bus<E>` avec implémentations in-memory et RabbitMQ (fanout exchange)
|
||||||
|
- `command/` — `Command`, `CommandUnicityChecker` (empêche la double exécution d'une commande,
|
||||||
|
cache glissant de 10 min par défaut)
|
||||||
|
- `eventSource/` — `Event`, `EventStream` (append/lecture par version, gestion de
|
||||||
|
`VersionConflictException`), `EventStore` in-memory / Postgresql
|
||||||
|
- `helpers/`, `serializer/` — utilitaires (conversion de frames WebSocket, sérialiseurs UUID, etc.)
|
||||||
|
|
||||||
|
## Patterns notables dans le code
|
||||||
|
|
||||||
|
- **Event sourcing** : `Game.loadFromHistory(events)` reconstruit l'état en repliant
|
||||||
|
(`fold`) les événements sur une state machine scellée, en utilisant la syntaxe Kotlin 2.1
|
||||||
|
`when` avec garde `if` (ex. `is GameCreatedEvent if this is GameInit -> applyEvent(event)`).
|
||||||
|
- **CQRS** : écriture via les command handlers (`application/command/handlers`), lecture via des
|
||||||
|
projections dédiées (`application/projections`), propagées via le bus RabbitMQ, pas de couplage
|
||||||
|
direct avec l'écriture.
|
||||||
|
- **Event-driven** : réactions asynchrones (`ReactionListener`, `EventToNotificationSubscriber`)
|
||||||
|
déclenchées par le bus RabbitMQ (exchange fanout, une queue par abonné).
|
||||||
|
- **Exceptions métier** : hiérarchie `GameException` / `IllegalActionException` dans
|
||||||
|
`domain/game/errors`, une exception par règle métier violée (ex.
|
||||||
|
`NeedMorePlayersToStartGameException`, `ItsNotTheTurnException`).
|
||||||
|
|
||||||
|
## Commandes utiles
|
||||||
|
|
||||||
|
```shell
|
||||||
|
./gradlew build # build complet
|
||||||
|
./gradlew test # tests (JUnit5 via Kotest)
|
||||||
|
./gradlew ktlintCheck # lint
|
||||||
|
./gradlew ktlintFormat # auto-format
|
||||||
|
./gradlew buildFatJar # jar exécutable "all-in-one" (utilisé par le Dockerfile prod)
|
||||||
|
|
||||||
|
# Dépendances seules (Postgres, RabbitMQ, Træfik, pgAdmin...) pour lancer l'app en local hors docker
|
||||||
|
docker compose -f docker/docker-compose-dev.yaml up -d
|
||||||
|
|
||||||
|
# Stack de test façon CI
|
||||||
|
docker compose -f docker/docker-compose-test.yaml up -d
|
||||||
|
# ou directement (comme en CI) :
|
||||||
|
docker compose -f docker/docker-compose-test.yaml run tests
|
||||||
|
|
||||||
|
# Stack complète en prod
|
||||||
|
docker compose -f docker/docker-compose-prod.yaml -p event-demo up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
URLs en dev (voir `doc/installation.md`, nécessite Træfik + résolution des `*.traefik.me`) :
|
||||||
|
API sur `http://api.traefik.me/`, dashboard
|
||||||
|
Træfik, pgAdmin et RabbitMQ management exposés via des sous-domaines `traefik.me`.
|
||||||
|
|
||||||
|
## Conventions de code
|
||||||
|
|
||||||
|
- ktlint en mode `ktlint_official` + règles `standard` et `experimental` activées
|
||||||
|
(voir `.editorconfig`), indentation **2 espaces**, virgules finales (*trailing commas*)
|
||||||
|
systématiques, wrapping forcé des expressions/signatures multi-lignes.
|
||||||
|
- Fins de ligne forcées en **LF** (`.gitattributes`), sauf `gradlew.bat` en CRLF.
|
||||||
|
- Code et identifiants en anglais.
|
||||||
|
- Style Kotlin idiomatique/fonctionnel : `fold`, `let`, `apply`, `when` exhaustifs, classes/interfaces
|
||||||
|
scellées (`sealed class`/`sealed interface`) pour modéliser états et événements plutôt que des enums
|
||||||
|
avec des champs optionnels.
|
||||||
|
|
||||||
|
## Pièges connus / choses à savoir avant de toucher au build ou à la CI
|
||||||
|
|
||||||
|
- **MockK/ByteBuddy en Docker** : l'auto-attach dynamique de MockK échoue dans les conteneurs
|
||||||
|
(le handshake SIGQUIT de l'AttachListener JVM time-out). Le `build.gradle.kts` charge donc
|
||||||
|
l'agent `byte-buddy-agent` de façon statique via `-javaagent` pour les tâches `Test`, afin
|
||||||
|
que MockK détecte l'instrumentation déjà présente et saute l'attach dynamique. Ne pas retirer
|
||||||
|
ce bloc sans repenser l'exécution des tests en Docker.
|
||||||
|
- **Secret Postgres en CI** : `docker/postgresql.secret` est généré à la volée par le workflow
|
||||||
|
GitHub Actions s'il n'existe pas (`echo -n "changeit" > docker/postgresql.secret`) — normal,
|
||||||
|
pas un fichier à committer.
|
||||||
|
- Les tests « officiels » de la CI tournent **dans Docker**, pas directement via `./gradlew test`
|
||||||
|
sur l'hôte — en cas de comportement différent entre local et CI, vérifier d'abord les
|
||||||
|
variables d'environnement/versions du `docker-compose-test.yaml`.
|
||||||
|
|
||||||
|
## Historique récent (pour contexte)
|
||||||
|
|
||||||
|
Le projet a connu un « Massive refactor to build the V2 » (commit `e2d7942`) : passage d'une
|
||||||
|
architecture par couches techniques plates (`adapter/presenter/domain`) à l'organisation actuelle
|
||||||
|
par bounded context (`auth`/`game`) avec 3 couches hexagonales chacune.
|
||||||
@@ -2,7 +2,6 @@ Event Demo
|
|||||||
==========
|
==========
|
||||||
- [Installation](./doc/installation.md)
|
- [Installation](./doc/installation.md)
|
||||||
- [What's the demo for ?](#whats-the-demo-for-)
|
- [What's the demo for ?](#whats-the-demo-for-)
|
||||||
- [What's in this demo](#whats-in-this-demo)
|
|
||||||
- [The stack](#the-stack)
|
- [The stack](#the-stack)
|
||||||
- [Architecture](./doc/architecture.md)
|
- [Architecture](./doc/architecture.md)
|
||||||
|
|
||||||
@@ -18,31 +17,6 @@ of different patterns and architectures.
|
|||||||
- The CQRS pattern.
|
- The CQRS pattern.
|
||||||
- With the Hexagonal architecture.
|
- With the Hexagonal architecture.
|
||||||
|
|
||||||
|
|
||||||
What's in this demo
|
|
||||||
-------------------
|
|
||||||
|
|
||||||
- The **event sourcing** pattern.
|
|
||||||
- The **event driven** pattern.
|
|
||||||
- The **CQRS** pattern with **command** and **query**.
|
|
||||||
- A fully **asynchronous** architecture.Concurently process.
|
|
||||||
- A **pure Kotlin** implementation of **readmodel**/**projection**.
|
|
||||||
- A **Redis** implementation of **readmodel**/**projection**.
|
|
||||||
- A **pure Kotlin** implementation of **Event Store**.
|
|
||||||
- A **Postgresql** implementation of **Event Store**.
|
|
||||||
- A **pure Kotlin** implementation of **Event Bus**.
|
|
||||||
- A **RabbitMQ** implementation of **Event Bus**.
|
|
||||||
- A **Hexagonal** architecture.
|
|
||||||
- Use of **Web Sockets**.
|
|
||||||
- Use of the classic **Rest** route.
|
|
||||||
- Simple usage of the **JWT**.
|
|
||||||
- The **Ktor** framework.
|
|
||||||
- The **Koin** Dependency Injection framework
|
|
||||||
- Concurrently process.
|
|
||||||
- Use of coroutines.
|
|
||||||
- Using **docker compose** for the stack with **traefik**.
|
|
||||||
- Use of **flyway** to migrate the postgresql schema.
|
|
||||||
|
|
||||||
The stack
|
The stack
|
||||||
---------
|
---------
|
||||||
|
|
||||||
@@ -51,11 +25,11 @@ Language
|
|||||||
|
|
||||||
Framework
|
Framework
|
||||||
- Ktor
|
- Ktor
|
||||||
|
- with Koin for Dependency Injection
|
||||||
|
|
||||||
Database
|
Database
|
||||||
- Postgresql
|
- Postgresql
|
||||||
- with Flyway
|
- with Flyway
|
||||||
- Redis
|
|
||||||
- RabbitMQ
|
- RabbitMQ
|
||||||
|
|
||||||
Infra
|
Infra
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
import org.jlleitschuh.gradle.ktlint.KtlintExtension
|
||||||
|
|
||||||
|
val ktorVersion: Provider<String> = providers.gradleProperty("ktor_version")
|
||||||
|
val kotlinVersion: Provider<String> = providers.gradleProperty("kotlin_version")
|
||||||
|
val kotlinSerializationVersion: Provider<String> = providers.gradleProperty("kotlin_serialization_version")
|
||||||
|
val logbackVersion: Provider<String> = providers.gradleProperty("logback_version")
|
||||||
|
val koinVersion: Provider<String> = providers.gradleProperty("koin_version")
|
||||||
|
val kotlinLoggingVersion: Provider<String> = providers.gradleProperty("kotlin_logging_version")
|
||||||
|
val kotestVersion: Provider<String> = providers.gradleProperty("kotest_version")
|
||||||
|
|
||||||
|
plugins {
|
||||||
|
application
|
||||||
|
kotlin("jvm")
|
||||||
|
id("io.ktor.plugin") version "3.5.1"
|
||||||
|
id("org.jetbrains.kotlin.plugin.serialization")
|
||||||
|
id("org.jlleitschuh.gradle.ktlint") version "14.2.0"
|
||||||
|
}
|
||||||
|
|
||||||
|
group = "io.github.flecomte"
|
||||||
|
|
||||||
|
application {
|
||||||
|
mainClass.set("eventDemo.ApplicationKt")
|
||||||
|
|
||||||
|
val isDevelopment: Boolean = project.ext.has("development")
|
||||||
|
applicationDefaultJvmArgs = listOf("-Dio.ktor.development=$isDevelopment")
|
||||||
|
}
|
||||||
|
|
||||||
|
configure<KtlintExtension> {
|
||||||
|
version.set("1.8.0")
|
||||||
|
}
|
||||||
|
ktlint {
|
||||||
|
reporters {
|
||||||
|
reporter(org.jlleitschuh.gradle.ktlint.reporter.ReporterType.CHECKSTYLE)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
repositories {
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
|
||||||
|
java {
|
||||||
|
toolchain {
|
||||||
|
languageVersion = JavaLanguageVersion.of(21)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlin {
|
||||||
|
compilerOptions {
|
||||||
|
freeCompilerArgs.add("-opt-in=kotlin.uuid.ExperimentalUuidApi")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tasks.withType<Test>().configureEach {
|
||||||
|
useJUnitPlatform()
|
||||||
|
jvmArgs("-Djdk.attach.allowAttachSelf=true", "-XX:+EnableDynamicAgentLoading")
|
||||||
|
// Dynamic self-attach (used by MockK/ByteBuddy) times out in Docker containers because the
|
||||||
|
// SIGQUIT-triggered AttachListener handshake never completes there. Loading the byte-buddy
|
||||||
|
// agent jar statically via -javaagent avoids the attach handshake entirely: MockK detects the
|
||||||
|
// pre-installed Instrumentation instance and skips dynamic attach.
|
||||||
|
doFirst {
|
||||||
|
val agentJar =
|
||||||
|
classpath.files.firstOrNull { it.name.startsWith("byte-buddy-agent") }
|
||||||
|
?: error("byte-buddy-agent jar not found on test classpath")
|
||||||
|
jvmArgs("-javaagent:$agentJar")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation(project(":shared"))
|
||||||
|
implementation("io.ktor:ktor-server-core-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-auth-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-auth-jwt-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-auto-head-response-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-resources")
|
||||||
|
implementation("io.ktor:ktor-server-content-negotiation-jvm")
|
||||||
|
implementation("io.ktor:ktor-serialization-kotlinx-json-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-websockets-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-cors-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-host-common-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-status-pages-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-netty-jvm")
|
||||||
|
implementation("io.ktor:ktor-server-data-conversion")
|
||||||
|
implementation("io.ktor:ktor-client-content-negotiation")
|
||||||
|
implementation("io.ktor:ktor-client-auth")
|
||||||
|
implementation("ch.qos.logback:logback-classic:${logbackVersion.get()}")
|
||||||
|
implementation("io.insert-koin:koin-ktor:${koinVersion.get()}")
|
||||||
|
implementation("io.insert-koin:koin-logger-slf4j:${koinVersion.get()}")
|
||||||
|
implementation("io.github.oshai:kotlin-logging-jvm:${kotlinLoggingVersion.get()}")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json-jvm:${kotlinSerializationVersion.get()}")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.2")
|
||||||
|
implementation("org.postgresql:postgresql:42.7.13")
|
||||||
|
implementation("com.zaxxer:HikariCP:6.3.0")
|
||||||
|
implementation("com.rabbitmq:amqp-client:5.25.0")
|
||||||
|
implementation("com.password4j:password4j:1.8.4")
|
||||||
|
|
||||||
|
// Force version of sub library (for security)
|
||||||
|
implementation("commons-codec:commons-codec:1.13")
|
||||||
|
|
||||||
|
testImplementation("io.kotest:kotest-extensions-koin:${kotestVersion.get()}")
|
||||||
|
testImplementation("org.jetbrains.kotlin:kotlin-test-junit:${kotlinVersion.get()}")
|
||||||
|
testImplementation("io.ktor:ktor-server-test-host-jvm:${ktorVersion.get()}")
|
||||||
|
testImplementation("io.kotest:kotest-runner-junit5:${kotestVersion.get()}")
|
||||||
|
testImplementation("io.mockk:mockk:1.14.11")
|
||||||
|
testImplementation("com.tngtech.archunit:archunit-junit5:1.3.0")
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package eventDemo.configuration
|
||||||
|
|
||||||
|
import io.ktor.server.config.ApplicationConfig
|
||||||
|
|
||||||
|
data class Configuration(
|
||||||
|
val jwtSecret: String,
|
||||||
|
val postgresql: Postgresql,
|
||||||
|
val rabbitmq: RabbitMQ,
|
||||||
|
) {
|
||||||
|
data class Postgresql(
|
||||||
|
val url: String,
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class RabbitMQ(
|
||||||
|
val url: String,
|
||||||
|
val port: Int,
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val ApplicationConfig.configuration
|
||||||
|
get() =
|
||||||
|
Configuration(
|
||||||
|
jwtSecret = getProperty("jwt.secret"),
|
||||||
|
postgresql =
|
||||||
|
Configuration.Postgresql(
|
||||||
|
url = getProperty("postgresql.url"),
|
||||||
|
username = getProperty("postgresql.username"),
|
||||||
|
password = getProperty("postgresql.password"),
|
||||||
|
),
|
||||||
|
rabbitmq =
|
||||||
|
Configuration.RabbitMQ(
|
||||||
|
url = getProperty("rabbitmq.url"),
|
||||||
|
port = getProperty("rabbitmq.port").toInt(),
|
||||||
|
username = getProperty("rabbitmq.username"),
|
||||||
|
password = getProperty("rabbitmq.password"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun ApplicationConfig.getProperty(path: String): String =
|
||||||
|
propertyOrNull(path)?.getString() ?: error("You must set the $path")
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
package eventDemo.configuration
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.infrastructure.configure.configureAuthDi
|
||||||
|
import eventDemo.contexts.game.infrastructure.configuration.injections.application.configureGameDIApplication
|
||||||
|
import eventDemo.contexts.game.infrastructure.configuration.injections.infrastructure.configureGameDIInfrastructure
|
||||||
|
import org.koin.dsl.module
|
||||||
|
|
||||||
|
fun appKoinModule(config: Configuration) =
|
||||||
|
module {
|
||||||
|
configureDIDataSource(config)
|
||||||
|
configureAuthDi()
|
||||||
|
configureGameDIInfrastructure()
|
||||||
|
configureGameDIApplication()
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
package eventDemo.configuration
|
||||||
|
|
||||||
|
import com.rabbitmq.client.ConnectionFactory
|
||||||
|
import com.zaxxer.hikari.HikariConfig
|
||||||
|
import com.zaxxer.hikari.HikariDataSource
|
||||||
|
import org.koin.core.module.Module
|
||||||
|
import org.koin.core.scope.Scope
|
||||||
|
import org.koin.core.scope.ScopeCallback
|
||||||
|
import org.koin.dsl.bind
|
||||||
|
import javax.sql.DataSource
|
||||||
|
|
||||||
|
fun Module.configureDIDataSource(config: Configuration) {
|
||||||
|
// PostgreSQL (for EventStore)
|
||||||
|
single {
|
||||||
|
hikariDataSource(config)
|
||||||
|
.apply {
|
||||||
|
registerCallback(
|
||||||
|
object : ScopeCallback {
|
||||||
|
override fun onScopeClose(scope: Scope) {
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} bind DataSource::class
|
||||||
|
|
||||||
|
// RabbitMQ (for EventBus)
|
||||||
|
factory {
|
||||||
|
ConnectionFactory().apply {
|
||||||
|
host = config.rabbitmq.url
|
||||||
|
port = config.rabbitmq.port
|
||||||
|
username = config.rabbitmq.username
|
||||||
|
password = config.rabbitmq.password
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hikariDataSource(config: Configuration): HikariDataSource =
|
||||||
|
HikariConfig()
|
||||||
|
.apply {
|
||||||
|
jdbcUrl = config.postgresql.url
|
||||||
|
username = config.postgresql.username
|
||||||
|
password = config.postgresql.password
|
||||||
|
maximumPoolSize = 10
|
||||||
|
minimumIdle = 10
|
||||||
|
}.let {
|
||||||
|
HikariDataSource(it)
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package eventDemo.configuration
|
||||||
|
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
import io.ktor.server.application.install
|
||||||
|
import org.koin.ktor.plugin.Koin
|
||||||
|
import org.koin.logger.slf4jLogger
|
||||||
|
|
||||||
|
fun Application.configureKoin() {
|
||||||
|
install(Koin) {
|
||||||
|
slf4jLogger()
|
||||||
|
|
||||||
|
modules(
|
||||||
|
appKoinModule(environment.config.configuration),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
package eventDemo.configuration
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.infrastructure.configure.configureAuth
|
||||||
|
import eventDemo.contexts.game.infrastructure.configuration.ktor.configureUno
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
|
||||||
|
fun Application.configure() {
|
||||||
|
configureKoin()
|
||||||
|
configureAuth()
|
||||||
|
configureUno()
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package eventDemo.contexts.auth.application.eventStores
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserEventStore
|
||||||
|
import eventDemo.contexts.auth.domain.User
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
|
||||||
|
class UserEventStoreRepository(
|
||||||
|
val eventStore: UserEventStore,
|
||||||
|
) : UserRepository {
|
||||||
|
override fun get(id: UserId): User? {
|
||||||
|
val events =
|
||||||
|
eventStore
|
||||||
|
.getStream(id)
|
||||||
|
.readAll()
|
||||||
|
if (events.isEmpty()) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return events.let { User.loadFromHistory(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun save(user: User) {
|
||||||
|
eventStore.append(user.recordedEvents)
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
@@ -0,0 +1,10 @@
|
|||||||
|
package eventDemo.contexts.auth.application.eventStores
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.domain.User
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
|
||||||
|
interface UserRepository {
|
||||||
|
fun get(id: UserId): User?
|
||||||
|
|
||||||
|
fun save(user: User)
|
||||||
|
}
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package eventDemo.contexts.auth.application.ports
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.domain.events.UserEvent
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStore
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
|
||||||
|
interface UserEventStore : EventStore<UserEvent, UserId>
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package eventDemo.contexts.auth.application.ports
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.infrastructure.persistence.projection.UserProjection
|
||||||
|
|
||||||
|
interface UserProjectionRepository {
|
||||||
|
fun getByUsername(username: String): UserProjection?
|
||||||
|
|
||||||
|
fun save(user: UserProjection)
|
||||||
|
|
||||||
|
fun getUserIfPasswordIsValid(
|
||||||
|
username: String,
|
||||||
|
rawPassword: String,
|
||||||
|
): UserProjection?
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package eventDemo.contexts.auth.domain
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.domain.events.NewUserCreatedEvent
|
||||||
|
import eventDemo.contexts.auth.domain.events.UserEvent
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class User(
|
||||||
|
val id: UserId,
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
val version: Int,
|
||||||
|
val recordedEvents: Set<UserEvent>,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
fun createNewUser(
|
||||||
|
username: String,
|
||||||
|
password: String,
|
||||||
|
): User =
|
||||||
|
apply(NewUserCreatedEvent(username, password, version = 1))
|
||||||
|
|
||||||
|
fun apply(event: NewUserCreatedEvent): User =
|
||||||
|
User(
|
||||||
|
id = event.aggregateId,
|
||||||
|
username = event.username,
|
||||||
|
password = event.password,
|
||||||
|
version = event.version,
|
||||||
|
recordedEvents = setOf(event),
|
||||||
|
)
|
||||||
|
|
||||||
|
fun loadFromHistory(events: Set<UserEvent>): User? =
|
||||||
|
events.fold(null as User?) { acc, event ->
|
||||||
|
when (event) {
|
||||||
|
is NewUserCreatedEvent -> apply(event)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
package eventDemo.contexts.auth.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
class NewUserCreatedEvent(
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
override val version: Int,
|
||||||
|
override val createdAt: Instant = Clock.System.now(),
|
||||||
|
override val aggregateId: UserId = UserId(),
|
||||||
|
) : UserEvent {
|
||||||
|
override val eventId: EventId = EventId()
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
package eventDemo.contexts.auth.domain.events
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
sealed interface UserEvent : Event<UserId>
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure
|
||||||
|
|
||||||
|
import com.password4j.Hash
|
||||||
|
import com.password4j.Password
|
||||||
|
|
||||||
|
internal fun hashPassword(password: String): Hash =
|
||||||
|
Password.hash(password).addRandomSalt().withArgon2()
|
||||||
|
|
||||||
|
internal fun checkPassword(
|
||||||
|
password: String,
|
||||||
|
hash: Hash,
|
||||||
|
): Boolean =
|
||||||
|
Password.check(password, hash)
|
||||||
+8
@@ -0,0 +1,8 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.configure
|
||||||
|
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
|
||||||
|
fun Application.configureAuth() {
|
||||||
|
configureKtorAuth()
|
||||||
|
configureAuthRoutes()
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.configure
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.eventStores.UserEventStoreRepository
|
||||||
|
import eventDemo.contexts.auth.application.eventStores.UserRepository
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserEventStore
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserProjectionRepository
|
||||||
|
import eventDemo.contexts.auth.infrastructure.persistence.eventStore.UserEventStoreInPostgresql
|
||||||
|
import eventDemo.contexts.auth.infrastructure.persistence.projection.UserProjectionRepositoryInPostgresql
|
||||||
|
import org.koin.core.module.Module
|
||||||
|
import org.koin.core.module.dsl.singleOf
|
||||||
|
import org.koin.dsl.bind
|
||||||
|
|
||||||
|
fun Module.configureAuthDi() {
|
||||||
|
singleOf(::UserEventStoreRepository) bind UserRepository::class
|
||||||
|
singleOf(::UserEventStoreInPostgresql) bind UserEventStore::class
|
||||||
|
singleOf(::UserProjectionRepositoryInPostgresql) bind UserProjectionRepository::class
|
||||||
|
}
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.configure
|
||||||
|
|
||||||
|
import eventDemo.configuration.configuration
|
||||||
|
import eventDemo.contexts.auth.application.eventStores.UserEventStoreRepository
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserProjectionRepository
|
||||||
|
import eventDemo.contexts.auth.infrastructure.rest.createUserRoute
|
||||||
|
import eventDemo.contexts.auth.infrastructure.rest.loginRoute
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
import io.ktor.server.routing.routing
|
||||||
|
import org.koin.ktor.ext.get
|
||||||
|
|
||||||
|
fun Application.configureAuthRoutes() {
|
||||||
|
val userRepository = get<UserEventStoreRepository>()
|
||||||
|
val userProjectionRepository = get<UserProjectionRepository>()
|
||||||
|
routing {
|
||||||
|
createUserRoute(userRepository)
|
||||||
|
loginRoute(environment.config.configuration.jwtSecret, userProjectionRepository)
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
-23
@@ -1,24 +1,21 @@
|
|||||||
package eventDemo.configuration.ktor
|
package eventDemo.contexts.auth.infrastructure.configure
|
||||||
|
|
||||||
import com.auth0.jwt.JWT
|
import com.auth0.jwt.JWT
|
||||||
import com.auth0.jwt.algorithms.Algorithm
|
import com.auth0.jwt.algorithms.Algorithm
|
||||||
import eventDemo.domain.entity.Player
|
import eventDemo.configuration.configuration
|
||||||
|
import eventDemo.contexts.auth.domain.User
|
||||||
|
import eventDemo.contexts.auth.infrastructure.persistence.projection.UserProjection
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
import io.ktor.http.HttpStatusCode
|
import io.ktor.http.HttpStatusCode
|
||||||
import io.ktor.server.application.Application
|
import io.ktor.server.application.Application
|
||||||
import io.ktor.server.auth.authentication
|
import io.ktor.server.auth.authentication
|
||||||
import io.ktor.server.auth.jwt.JWTPrincipal
|
import io.ktor.server.auth.jwt.JWTPrincipal
|
||||||
import io.ktor.server.auth.jwt.jwt
|
import io.ktor.server.auth.jwt.jwt
|
||||||
import io.ktor.server.response.respond
|
import io.ktor.server.response.respond
|
||||||
import io.ktor.server.routing.post
|
|
||||||
import io.ktor.server.routing.routing
|
|
||||||
import kotlinx.serialization.json.Json
|
|
||||||
import java.util.Date
|
import java.util.Date
|
||||||
|
|
||||||
private const val JWT_ISSUER = "PlayCardGame"
|
fun Application.configureKtorAuth() {
|
||||||
|
val jwtSecret = environment.config.configuration.jwtSecret
|
||||||
fun Application.configureSecurity() {
|
|
||||||
val jwtSecret = environment.config.propertyOrNull("jwt.secret")?.getString() ?: error("You must set a jwt secret")
|
|
||||||
|
|
||||||
authentication {
|
authentication {
|
||||||
jwt {
|
jwt {
|
||||||
realm = "Play card game"
|
realm = "Play card game"
|
||||||
@@ -29,7 +26,11 @@ fun Application.configureSecurity() {
|
|||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
validate { credential ->
|
validate { credential ->
|
||||||
if (credential.payload.getClaim("username").asString() != "") {
|
if (credential.payload
|
||||||
|
.getClaim("username")
|
||||||
|
.asString()
|
||||||
|
.isNotEmpty()
|
||||||
|
) {
|
||||||
JWTPrincipal(credential.payload)
|
JWTPrincipal(credential.payload)
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
@@ -40,22 +41,25 @@ fun Application.configureSecurity() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
routing {
|
|
||||||
post("login/{username}") {
|
|
||||||
val username = call.parameters["username"]!!
|
|
||||||
val player = Player(name = username)
|
|
||||||
|
|
||||||
call.respond(hashMapOf("token" to player.makeJwt(jwtSecret)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun Player.makeJwt(jwtSecret: String): String =
|
private const val JWT_ISSUER = "PlayCardGame"
|
||||||
|
|
||||||
|
fun UserProjection.makeJwt(jwtSecret: String): String =
|
||||||
|
makeJwt(jwtSecret, id, username)
|
||||||
|
|
||||||
|
fun User.makeJwt(jwtSecret: String): String =
|
||||||
|
makeJwt(jwtSecret, id, username)
|
||||||
|
|
||||||
|
fun makeJwt(
|
||||||
|
jwtSecret: String,
|
||||||
|
id: UserId,
|
||||||
|
username: String,
|
||||||
|
): String =
|
||||||
JWT
|
JWT
|
||||||
.create()
|
.create()
|
||||||
.withIssuer(JWT_ISSUER)
|
.withIssuer(JWT_ISSUER)
|
||||||
.withClaim("username", name)
|
.withClaim("username", username)
|
||||||
.withPayload(Json.encodeToString(this))
|
.withClaim("userid", id.toString())
|
||||||
.withExpiresAt(Date(System.currentTimeMillis() + 60000))
|
.withExpiresAt(Date(System.currentTimeMillis() + 60000))
|
||||||
.sign(Algorithm.HMAC256(jwtSecret))
|
.sign(Algorithm.HMAC256(jwtSecret))
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.persistence.eventStore
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserEventStore
|
||||||
|
import eventDemo.contexts.auth.domain.events.UserEvent
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStore
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStoreInMemory
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A stream to publish and read the user events.
|
||||||
|
*/
|
||||||
|
class UserEventStoreInMemory :
|
||||||
|
UserEventStore,
|
||||||
|
EventStore<UserEvent, UserId> by EventStoreInMemory()
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.persistence.eventStore
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserEventStore
|
||||||
|
import eventDemo.contexts.auth.domain.events.UserEvent
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStore
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStoreInPostgresql
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import javax.sql.DataSource
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A stream to publish and read the user events.
|
||||||
|
*/
|
||||||
|
class UserEventStoreInPostgresql(
|
||||||
|
dataSource: DataSource,
|
||||||
|
) : UserEventStore,
|
||||||
|
EventStore<UserEvent, UserId> by EventStoreInPostgresql(
|
||||||
|
dataSource,
|
||||||
|
{ Json.encodeToString(it) },
|
||||||
|
{ Json.decodeFromString(it) },
|
||||||
|
"auth.user_event_stream",
|
||||||
|
)
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.persistence.projection
|
||||||
|
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
|
||||||
|
data class UserProjection(
|
||||||
|
val id: UserId,
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
)
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.persistence.projection
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserProjectionRepository
|
||||||
|
import eventDemo.contexts.auth.infrastructure.checkPassword
|
||||||
|
import eventDemo.contexts.auth.infrastructure.hashPassword
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import javax.sql.DataSource
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
import kotlin.uuid.toJavaUuid
|
||||||
|
|
||||||
|
class UserProjectionRepositoryInPostgresql(
|
||||||
|
val dataSource: DataSource,
|
||||||
|
) : UserProjectionRepository {
|
||||||
|
override fun getByUsername(username: String): UserProjection? =
|
||||||
|
dataSource.connection
|
||||||
|
.prepareStatement(
|
||||||
|
"""
|
||||||
|
select id, username
|
||||||
|
from auth."user"
|
||||||
|
where id = ?;
|
||||||
|
""".trimIndent(),
|
||||||
|
).use {
|
||||||
|
it.setObject(1, username)
|
||||||
|
it.executeQuery()
|
||||||
|
}.use { resultSet ->
|
||||||
|
if (resultSet.next()) {
|
||||||
|
UserProjection(
|
||||||
|
id = UserId(Uuid.parse(resultSet.getString("id"))),
|
||||||
|
username = resultSet.getString("username"),
|
||||||
|
password = resultSet.getString("password"),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun save(user: UserProjection) {
|
||||||
|
dataSource.connection.use { connection ->
|
||||||
|
connection
|
||||||
|
.prepareStatement(
|
||||||
|
"""
|
||||||
|
insert into auth.user (id, username)
|
||||||
|
values (?, ?)
|
||||||
|
""".trimIndent(),
|
||||||
|
).use {
|
||||||
|
it.setObject(1, user.id.id.toJavaUuid())
|
||||||
|
it.setString(2, user.username)
|
||||||
|
it.executeUpdate()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getUserIfPasswordIsValid(
|
||||||
|
username: String,
|
||||||
|
rawPassword: String,
|
||||||
|
): UserProjection? {
|
||||||
|
val user = getByUsername(username) ?: return null
|
||||||
|
val isValid = checkPassword(rawPassword, hashPassword(user.password))
|
||||||
|
if (!isValid) return null
|
||||||
|
return user
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.rest
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.ports.UserProjectionRepository
|
||||||
|
import eventDemo.contexts.auth.infrastructure.configure.makeJwt
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.routing.post
|
||||||
|
|
||||||
|
fun Route.loginRoute(
|
||||||
|
jwtSecret: String,
|
||||||
|
userProjectionRepository: UserProjectionRepository,
|
||||||
|
) {
|
||||||
|
post("login/{username}") {
|
||||||
|
val username = call.parameters["username"]!!
|
||||||
|
val rawPassword = call.parameters["password"]!!
|
||||||
|
|
||||||
|
val userProjection =
|
||||||
|
userProjectionRepository.getUserIfPasswordIsValid(username, rawPassword)
|
||||||
|
?: return@post call.respond(HttpStatusCode.BadRequest)
|
||||||
|
|
||||||
|
call.respond(hashMapOf("token" to userProjection.makeJwt(jwtSecret)))
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
@@ -0,0 +1,41 @@
|
|||||||
|
package eventDemo.contexts.auth.infrastructure.rest
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.eventStores.UserRepository
|
||||||
|
import eventDemo.contexts.auth.domain.User
|
||||||
|
import eventDemo.contexts.auth.infrastructure.hashPassword
|
||||||
|
import io.ktor.resources.Resource
|
||||||
|
import io.ktor.server.auth.authenticate
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.routing.post
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
@Resource("/users")
|
||||||
|
class Users {
|
||||||
|
@Serializable
|
||||||
|
@Resource("/create")
|
||||||
|
class Create(
|
||||||
|
val username: String,
|
||||||
|
val password: String,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API routes to show all games.
|
||||||
|
*/
|
||||||
|
fun Route.createUserRoute(userRepository: UserRepository) {
|
||||||
|
authenticate {
|
||||||
|
// Create a new User, and return there ID
|
||||||
|
post<Users.Create> {
|
||||||
|
val passwordHash = hashPassword(it.password)
|
||||||
|
val user = User.createNewUser(it.username, passwordHash.result)
|
||||||
|
userRepository.save(user)
|
||||||
|
call.respond(
|
||||||
|
object {
|
||||||
|
val id = user.id.toString()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package eventDemo.contexts.game.application.channels
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.notification.CommandSubscriber
|
||||||
|
import eventDemo.contexts.game.application.notification.EventToNotificationSubscriber
|
||||||
|
import eventDemo.shared.game.command.GameCommand
|
||||||
|
import eventDemo.shared.game.notification.Notification
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||||
|
import kotlinx.coroutines.channels.ReceiveChannel
|
||||||
|
import kotlinx.coroutines.channels.SendChannel
|
||||||
|
|
||||||
|
class GameChannelsSubscriber(
|
||||||
|
private val eventToNotificationSubscriber: EventToNotificationSubscriber,
|
||||||
|
private val commandSubscriber: CommandSubscriber,
|
||||||
|
) {
|
||||||
|
@DelicateCoroutinesApi
|
||||||
|
fun subscribePlayerToGameChannels(
|
||||||
|
gameId: GameId,
|
||||||
|
userId: UserId,
|
||||||
|
incomingCommandChannel: ReceiveChannel<GameCommand>,
|
||||||
|
sendNotificationChannel: SendChannel<Notification>,
|
||||||
|
) {
|
||||||
|
val sub =
|
||||||
|
eventToNotificationSubscriber.subscribeToEventsAndSendNotification(
|
||||||
|
gameId = gameId,
|
||||||
|
currentUserId = userId,
|
||||||
|
outgoingFrameChannel = sendNotificationChannel,
|
||||||
|
)
|
||||||
|
|
||||||
|
commandSubscriber
|
||||||
|
.subscribe(
|
||||||
|
currentUserId = userId,
|
||||||
|
incomingFrameChannel = incomingCommandChannel,
|
||||||
|
).invokeOnCompletion { sub.close() }
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package eventDemo.domain.command
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
class CommandException(
|
class CommandException(
|
||||||
override val message: String,
|
override val message: String,
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
|
import eventDemo.shared.game.command.GameCommand
|
||||||
|
import eventDemo.shared.game.command.JoinTheGameCommand
|
||||||
|
import eventDemo.shared.game.command.PlayCardCommand
|
||||||
|
import eventDemo.shared.game.command.ReadyToPlayCommand
|
||||||
|
import eventDemo.shared.game.command.TakeCartFromDrawPileCommand
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import java.util.Collections
|
||||||
|
|
||||||
|
class GameCommandHandlerDispatcher(
|
||||||
|
private val playCardHandler: PlayCardHandler,
|
||||||
|
private val readyToPlayHandler: ReadyToPlayHandler,
|
||||||
|
private val joinTheGameHandler: JoinTheGameHandler,
|
||||||
|
private val takeCartFromDrawPileHandler: TakeCartFromDrawPileHandler,
|
||||||
|
) {
|
||||||
|
companion object {
|
||||||
|
val lock: MutableMap<GameId, String> = Collections.synchronizedMap(mutableMapOf())
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dispatch(command: GameCommand) {
|
||||||
|
synchronized(lock.getOrPut(command.payload.aggregateId) { command.payload.aggregateId.toString() }) {
|
||||||
|
when (command) {
|
||||||
|
is JoinTheGameCommand -> joinTheGameHandler.handle(command)
|
||||||
|
is ReadyToPlayCommand -> readyToPlayHandler.handle(command)
|
||||||
|
is PlayCardCommand -> playCardHandler.handle(command)
|
||||||
|
is TakeCartFromDrawPileCommand -> takeCartFromDrawPileHandler.handle(command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+58
@@ -0,0 +1,58 @@
|
|||||||
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game
|
||||||
|
import eventDemo.libs.eventSource.eventStore.VersionConflictException
|
||||||
|
import eventDemo.shared.command.Command
|
||||||
|
import eventDemo.shared.game.command.GameCommand
|
||||||
|
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||||
|
import kotlin.reflect.KClass
|
||||||
|
|
||||||
|
sealed interface CommandHandler<C : Command> {
|
||||||
|
fun handle(command: C)
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract class GameEventManager(
|
||||||
|
private val gameRepository: GameRepository,
|
||||||
|
private val gameEventBus: GameEventBus,
|
||||||
|
) {
|
||||||
|
private val logger = KotlinLogging.logger {}
|
||||||
|
|
||||||
|
fun GameCommand.getGame(): Game =
|
||||||
|
gameRepository.get(payload.aggregateId) ?: error("Game not found")
|
||||||
|
|
||||||
|
fun GameEvent.getGame(): Game =
|
||||||
|
gameRepository.get(aggregateId) ?: error("Game not found")
|
||||||
|
|
||||||
|
@Throws(VersionConflictException::class)
|
||||||
|
protected fun Game.saveEvents(): Game {
|
||||||
|
gameRepository.save(this)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
protected fun Game.publishEvents(): Game {
|
||||||
|
gameEventBus.publish(recordedEvents)
|
||||||
|
return this
|
||||||
|
}
|
||||||
|
|
||||||
|
protected inline fun <reified G : Game> Game.isStatusOrFail(message: String): G =
|
||||||
|
this as? G ?: throw CommandException(message)
|
||||||
|
|
||||||
|
protected fun <T> retry(
|
||||||
|
mapAttempts: Int = 5,
|
||||||
|
block: () -> T,
|
||||||
|
): T =
|
||||||
|
try {
|
||||||
|
block()
|
||||||
|
} catch (e: VersionConflictException) {
|
||||||
|
if (mapAttempts > 0) {
|
||||||
|
logger.warn { "retry after version conflict (attempts left: $mapAttempts)" }
|
||||||
|
retry(mapAttempts - 1, block)
|
||||||
|
} else {
|
||||||
|
logger.error { "Version conflict retry failed" }
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
|
import eventDemo.contexts.auth.application.eventStores.UserRepository
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameCreated
|
||||||
|
import eventDemo.shared.game.command.JoinTheGameCommand
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A command to perform an action to play a new card
|
||||||
|
*/
|
||||||
|
class JoinTheGameHandler(
|
||||||
|
gameRepository: GameRepository,
|
||||||
|
gameEventBus: GameEventBus,
|
||||||
|
private val userRepository: UserRepository,
|
||||||
|
) : GameEventManager(gameRepository, gameEventBus),
|
||||||
|
CommandHandler<JoinTheGameCommand> {
|
||||||
|
override fun handle(command: JoinTheGameCommand) {
|
||||||
|
val user = userRepository.get(command.userId) ?: error("User with id ${command.userId} doesn't exist")
|
||||||
|
retry {
|
||||||
|
command
|
||||||
|
.getGame()
|
||||||
|
.isStatusOrFail<GameCreated>("The game is started")
|
||||||
|
.userJoinTheGame(
|
||||||
|
userId = command.userId,
|
||||||
|
name = user.username,
|
||||||
|
).saveEvents()
|
||||||
|
.publishEvents()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameStarted
|
||||||
|
import eventDemo.shared.game.command.PlayCardCommand
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A command to perform an action to play a new card
|
||||||
|
*/
|
||||||
|
class PlayCardHandler(
|
||||||
|
gameRepository: GameRepository,
|
||||||
|
gameEventBus: GameEventBus,
|
||||||
|
) : GameEventManager(gameRepository, gameEventBus),
|
||||||
|
CommandHandler<PlayCardCommand> {
|
||||||
|
override fun handle(command: PlayCardCommand) {
|
||||||
|
command
|
||||||
|
.getGame()
|
||||||
|
.isStatusOrFail<GameStarted>("The game is not started")
|
||||||
|
.playTheCard(
|
||||||
|
card = command.payload.card,
|
||||||
|
playerId = command.payload.playerId,
|
||||||
|
chosenColor = command.payload.chosenColor,
|
||||||
|
).saveEvents()
|
||||||
|
.publishEvents()
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameCreated
|
||||||
|
import eventDemo.shared.game.command.ReadyToPlayCommand
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A command to set as ready to play
|
||||||
|
*/
|
||||||
|
class ReadyToPlayHandler(
|
||||||
|
gameRepository: GameRepository,
|
||||||
|
gameEventBus: GameEventBus,
|
||||||
|
) : GameEventManager(gameRepository, gameEventBus),
|
||||||
|
CommandHandler<ReadyToPlayCommand> {
|
||||||
|
override fun handle(command: ReadyToPlayCommand) {
|
||||||
|
command
|
||||||
|
.getGame()
|
||||||
|
.isStatusOrFail<GameCreated>("The game is started")
|
||||||
|
.setReadyPlayer(command.payload.playerId)
|
||||||
|
.saveEvents()
|
||||||
|
.publishEvents()
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package eventDemo.contexts.game.application.command.handlers
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameStarted
|
||||||
|
import eventDemo.shared.game.command.TakeCartFromDrawPileCommand
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A command to draw card on draw pile.
|
||||||
|
*
|
||||||
|
* Is can be triggered when you cannot play any card in your hand.
|
||||||
|
*/
|
||||||
|
class TakeCartFromDrawPileHandler(
|
||||||
|
gameRepository: GameRepository,
|
||||||
|
gameEventBus: GameEventBus,
|
||||||
|
) : GameEventManager(gameRepository, gameEventBus),
|
||||||
|
CommandHandler<TakeCartFromDrawPileCommand> {
|
||||||
|
override fun handle(command: TakeCartFromDrawPileCommand) {
|
||||||
|
command
|
||||||
|
.getGame()
|
||||||
|
.isStatusOrFail<GameStarted>("The game is not started")
|
||||||
|
.playerTakeCartFromDrawPile(command.payload.playerId, 1)
|
||||||
|
.saveEvents()
|
||||||
|
.publishEvents()
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package eventDemo.contexts.game.application.eventStores
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventStore
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game
|
||||||
|
import eventDemo.libs.eventSource.eventStore.VersionConflictException
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
class GameEventStoreRepository(
|
||||||
|
val eventStore: GameEventStore,
|
||||||
|
) : GameRepository {
|
||||||
|
override fun get(id: GameId): Game? {
|
||||||
|
val events =
|
||||||
|
eventStore
|
||||||
|
.getStream(id)
|
||||||
|
.readAll()
|
||||||
|
if (events.isEmpty()) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return events.let { Game.loadFromHistory(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Throws(VersionConflictException::class)
|
||||||
|
override fun save(game: Game) {
|
||||||
|
eventStore.append(game.recordedEvents)
|
||||||
|
}
|
||||||
|
}
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
package eventDemo.contexts.game.application.eventStores
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameCreated
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameInit
|
||||||
|
import eventDemo.libs.eventSource.eventStore.VersionConflictException
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
interface GameRepository {
|
||||||
|
fun get(id: GameId): Game?
|
||||||
|
|
||||||
|
@Throws(VersionConflictException::class)
|
||||||
|
fun save(game: Game)
|
||||||
|
|
||||||
|
fun getOrCreate(gameId: GameId): Game =
|
||||||
|
get(gameId) ?: create(gameId)
|
||||||
|
|
||||||
|
fun create(gameId: GameId = GameId()): GameCreated =
|
||||||
|
GameInit.createNewGame(gameId).also { save(it) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package eventDemo.contexts.game.application.logging
|
||||||
|
|
||||||
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
|
|
||||||
|
inline fun <T> withLoggingContext(
|
||||||
|
vararg pair: Pair<LoggingContextKeys, *>,
|
||||||
|
body: () -> T,
|
||||||
|
): T =
|
||||||
|
withLoggingContext(
|
||||||
|
*pair
|
||||||
|
.map {
|
||||||
|
it.first.name to it.second.toString()
|
||||||
|
}.toTypedArray(),
|
||||||
|
restorePrevious = true,
|
||||||
|
body = body,
|
||||||
|
)
|
||||||
|
|
||||||
|
// inline fun withLoggingContext(
|
||||||
|
// vararg pair: Pair<LoggingContextKeys, *>,
|
||||||
|
// body: () -> Unit,
|
||||||
|
// ) =
|
||||||
|
// withLoggingContext(
|
||||||
|
// *pair
|
||||||
|
// .map {
|
||||||
|
// it.first.name to it.second.toString()
|
||||||
|
// }.toTypedArray(),
|
||||||
|
// restorePrevious = true,
|
||||||
|
// body = body,
|
||||||
|
// )
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package eventDemo.contexts.game.application.logging
|
||||||
|
|
||||||
|
enum class LoggingContextKeys {
|
||||||
|
CurrentUserId,
|
||||||
|
Notification,
|
||||||
|
Game,
|
||||||
|
Event,
|
||||||
|
Command,
|
||||||
|
}
|
||||||
+127
@@ -0,0 +1,127 @@
|
|||||||
|
package eventDemo.contexts.game.application.notification
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.CardIsPlayedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.DrawFilledWithDiscardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameCreatedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameStartedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.NewPlayerEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerActionEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerHaveDrawCardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerReadyEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerWinEvent
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameStarted
|
||||||
|
import eventDemo.shared.game.notification.ItsTheTurnOfNotification
|
||||||
|
import eventDemo.shared.game.notification.Notification
|
||||||
|
import eventDemo.shared.game.notification.PilesShuffledNotification
|
||||||
|
import eventDemo.shared.game.notification.PlayerAsJoinTheGameNotification
|
||||||
|
import eventDemo.shared.game.notification.PlayerAsPlayACardNotification
|
||||||
|
import eventDemo.shared.game.notification.PlayerHavePassNotification
|
||||||
|
import eventDemo.shared.game.notification.PlayerWasReadyNotification
|
||||||
|
import eventDemo.shared.game.notification.PlayerWinNotification
|
||||||
|
import eventDemo.shared.game.notification.TheGameWasStartedNotification
|
||||||
|
import eventDemo.shared.game.notification.WelcomeToTheGameNotification
|
||||||
|
import eventDemo.shared.game.notification.YourNewCardNotification
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||||
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
|
|
||||||
|
private val logger = KotlinLogging.logger {}
|
||||||
|
|
||||||
|
fun GameEvent.toNotification(
|
||||||
|
game: Game,
|
||||||
|
currentUserId: UserId,
|
||||||
|
): Iterable<Notification> =
|
||||||
|
Iterable {
|
||||||
|
iterator {
|
||||||
|
context(iterator: SequenceScope<Notification>)
|
||||||
|
suspend fun Notification.send() {
|
||||||
|
withLoggingContext("notification" to (this).toString()) {
|
||||||
|
logger.info { "Notification sent" }
|
||||||
|
iterator.yield(this)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun PlayerActionEvent.isFromCurrentUser(): Boolean =
|
||||||
|
game.players.get(currentUserId).id == playerId
|
||||||
|
|
||||||
|
when (this@toNotification) {
|
||||||
|
is GameCreatedEvent -> {
|
||||||
|
// Nothing to send
|
||||||
|
}
|
||||||
|
|
||||||
|
is DrawFilledWithDiscardEvent -> {
|
||||||
|
PilesShuffledNotification().send()
|
||||||
|
}
|
||||||
|
|
||||||
|
is NewPlayerEvent -> {
|
||||||
|
if (this@toNotification.player.userId != currentUserId) {
|
||||||
|
PlayerAsJoinTheGameNotification(
|
||||||
|
player = this@toNotification.player,
|
||||||
|
).send()
|
||||||
|
} else {
|
||||||
|
WelcomeToTheGameNotification(
|
||||||
|
players = game.players,
|
||||||
|
).send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is CardIsPlayedEvent -> {
|
||||||
|
PlayerAsPlayACardNotification(
|
||||||
|
playerId = this@toNotification.playerId,
|
||||||
|
card = this@toNotification.card,
|
||||||
|
).send()
|
||||||
|
|
||||||
|
if (game is GameStarted) {
|
||||||
|
ItsTheTurnOfNotification(
|
||||||
|
player = game.nextPlayer,
|
||||||
|
).send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is GameStartedEvent -> {
|
||||||
|
TheGameWasStartedNotification(
|
||||||
|
hand =
|
||||||
|
game.players
|
||||||
|
.get(currentUserId)
|
||||||
|
.hand.cards,
|
||||||
|
).send()
|
||||||
|
|
||||||
|
if (game is GameStarted) {
|
||||||
|
ItsTheTurnOfNotification(player = game.nextPlayer)
|
||||||
|
.send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is PlayerHaveDrawCardEvent -> {
|
||||||
|
if (this@toNotification.isFromCurrentUser()) {
|
||||||
|
YourNewCardNotification(
|
||||||
|
cards = this@toNotification.takenCards,
|
||||||
|
).send()
|
||||||
|
} else {
|
||||||
|
PlayerHavePassNotification(
|
||||||
|
playerId = this@toNotification.playerId,
|
||||||
|
).send()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (game is GameStarted) {
|
||||||
|
ItsTheTurnOfNotification(player = game.nextPlayer)
|
||||||
|
.send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is PlayerReadyEvent -> {
|
||||||
|
PlayerWasReadyNotification(
|
||||||
|
playerId = this@toNotification.playerId,
|
||||||
|
).send()
|
||||||
|
}
|
||||||
|
|
||||||
|
is PlayerWinEvent -> {
|
||||||
|
PlayerWinNotification(
|
||||||
|
playerId = this@toNotification.playerId,
|
||||||
|
).send()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+72
@@ -0,0 +1,72 @@
|
|||||||
|
package eventDemo.contexts.game.application.notification
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.GameCommandHandlerDispatcher
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.logging.LoggingContextKeys.Command
|
||||||
|
import eventDemo.contexts.game.application.logging.LoggingContextKeys.CurrentUserId
|
||||||
|
import eventDemo.contexts.game.application.logging.LoggingContextKeys.Event
|
||||||
|
import eventDemo.contexts.game.application.logging.LoggingContextKeys.Game
|
||||||
|
import eventDemo.contexts.game.application.logging.LoggingContextKeys.Notification
|
||||||
|
import eventDemo.contexts.game.application.logging.withLoggingContext
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.libs.bus.Bus
|
||||||
|
import eventDemo.libs.command.CommandUnicityChecker
|
||||||
|
import eventDemo.shared.game.command.GameCommand
|
||||||
|
import eventDemo.shared.game.notification.Notification
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||||
|
import kotlinx.coroutines.GlobalScope
|
||||||
|
import kotlinx.coroutines.Job
|
||||||
|
import kotlinx.coroutines.channels.ReceiveChannel
|
||||||
|
import kotlinx.coroutines.channels.SendChannel
|
||||||
|
import kotlinx.coroutines.channels.trySendBlocking
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
|
||||||
|
class EventToNotificationSubscriber(
|
||||||
|
private val gameEventBus: GameEventBus,
|
||||||
|
private val gameRepository: GameRepository,
|
||||||
|
) {
|
||||||
|
fun subscribeToEventsAndSendNotification(
|
||||||
|
gameId: GameId,
|
||||||
|
currentUserId: UserId,
|
||||||
|
outgoingFrameChannel: SendChannel<Notification>,
|
||||||
|
): Bus.Subscription =
|
||||||
|
withLoggingContext(CurrentUserId to currentUserId) {
|
||||||
|
gameEventBus.subscribe { event ->
|
||||||
|
val game = gameRepository.get(gameId) ?: error("Game not found")
|
||||||
|
withLoggingContext(Event to event, Game to game) {
|
||||||
|
event
|
||||||
|
.toNotification(
|
||||||
|
game = game,
|
||||||
|
currentUserId = currentUserId,
|
||||||
|
).forEach { notification ->
|
||||||
|
withLoggingContext(Notification to notification) {
|
||||||
|
outgoingFrameChannel.trySendBlocking(notification)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class CommandSubscriber(
|
||||||
|
private val gameCommandHandlerDispatcher: GameCommandHandlerDispatcher,
|
||||||
|
) {
|
||||||
|
private val controller = CommandUnicityChecker<GameCommand>()
|
||||||
|
|
||||||
|
@DelicateCoroutinesApi
|
||||||
|
fun subscribe(
|
||||||
|
currentUserId: UserId,
|
||||||
|
incomingFrameChannel: ReceiveChannel<GameCommand>,
|
||||||
|
): Job =
|
||||||
|
GlobalScope.launch {
|
||||||
|
for (command in incomingFrameChannel) {
|
||||||
|
withLoggingContext(CurrentUserId to currentUserId, Command to command) {
|
||||||
|
controller.runOnlyOnce(command) {
|
||||||
|
gameCommandHandlerDispatcher.dispatch(command)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package eventDemo.contexts.game.application.ports
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.libs.bus.Bus
|
||||||
|
|
||||||
|
interface GameEventBus : Bus<GameEvent>
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
package eventDemo.contexts.game.application.ports
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStore
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
interface GameEventStore : EventStore<GameEvent, GameId>
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package eventDemo.domain.event.projection
|
||||||
|
|
||||||
|
import eventDemo.shared.game.projection.GameList
|
||||||
|
|
||||||
|
interface GameListRepository {
|
||||||
|
fun getList(
|
||||||
|
limit: Int = 100,
|
||||||
|
offset: Int = 0,
|
||||||
|
): List<GameList>
|
||||||
|
|
||||||
|
fun save(gameList: GameList)
|
||||||
|
|
||||||
|
fun subscribeToBus()
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
package eventDemo.contexts.game.application.ports
|
||||||
|
|
||||||
|
import eventDemo.libs.bus.Bus
|
||||||
|
import eventDemo.shared.game.projection.GameProjection
|
||||||
|
|
||||||
|
interface GameProjectionBus : Bus<GameProjection>
|
||||||
+55
@@ -0,0 +1,55 @@
|
|||||||
|
package eventDemo.contexts.game.application.projections
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.CardIsPlayedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.DrawFilledWithDiscardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameCreatedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameStartedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.NewPlayerEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerHaveDrawCardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerReadyEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerWinEvent
|
||||||
|
import eventDemo.shared.game.projection.GameList
|
||||||
|
|
||||||
|
fun GameList.applyEvent(event: GameEvent): GameList =
|
||||||
|
when (event) {
|
||||||
|
is GameCreatedEvent -> {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
is NewPlayerEvent -> {
|
||||||
|
copy(
|
||||||
|
players = players + event.player,
|
||||||
|
status = GameList.Status.OPENING,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is GameStartedEvent -> {
|
||||||
|
copy(
|
||||||
|
status = GameList.Status.IS_STARTED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is PlayerWinEvent -> {
|
||||||
|
copy(
|
||||||
|
winners = winners,
|
||||||
|
status = GameList.Status.FINISH,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
is CardIsPlayedEvent -> {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
is PlayerHaveDrawCardEvent -> {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
is PlayerReadyEvent -> {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
|
||||||
|
is DrawFilledWithDiscardEvent -> {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
}
|
||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package eventDemo.contexts.game.application.reaction
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.GameEventManager
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.logging.LoggingContextKeys
|
||||||
|
import eventDemo.contexts.game.application.logging.withLoggingContext
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameCreated
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.GameStarted
|
||||||
|
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||||
|
import java.util.concurrent.ConcurrentSkipListSet
|
||||||
|
|
||||||
|
class ReactionListener(
|
||||||
|
gameRepository: GameRepository,
|
||||||
|
private val gameEventBus: GameEventBus,
|
||||||
|
) : GameEventManager(gameRepository, gameEventBus) {
|
||||||
|
private companion object Config {
|
||||||
|
val registeredListeners = ConcurrentSkipListSet<GameEventBus>()
|
||||||
|
}
|
||||||
|
|
||||||
|
private val logger = KotlinLogging.logger { }
|
||||||
|
|
||||||
|
fun subscribeToBus() {
|
||||||
|
if (registeredListeners.add(gameEventBus)) {
|
||||||
|
gameEventBus.subscribe { event ->
|
||||||
|
val game = event.getGame()
|
||||||
|
withLoggingContext(LoggingContextKeys.Game to game) {
|
||||||
|
sendStartGameEvent(game)
|
||||||
|
sendWinnerEvent(game)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
"${this::class.simpleName} is already init for this bus".let {
|
||||||
|
logger.error { it }
|
||||||
|
error(it)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendStartGameEvent(game: Game) {
|
||||||
|
if (game is GameCreated && game.allPlayerIsReady) {
|
||||||
|
game
|
||||||
|
.startGame()
|
||||||
|
.saveEvents()
|
||||||
|
.publishEvents()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendWinnerEvent(game: Game) {
|
||||||
|
if (game is GameStarted && game.lastPlayerId != null) {
|
||||||
|
val lastPlayerWin =
|
||||||
|
game
|
||||||
|
.players
|
||||||
|
.get(game.lastPlayerId)
|
||||||
|
.hand.size == 0
|
||||||
|
if (lastPlayerWin) {
|
||||||
|
game
|
||||||
|
.playerWin(game.lastPlayerId)
|
||||||
|
.saveEvents()
|
||||||
|
.publishEvents()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.Card
|
||||||
|
import eventDemo.shared.game.Card.Color
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An [GameEvent] to represent a played card.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class CardIsPlayedEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
val card: Card,
|
||||||
|
override val playerId: Player.PlayerId,
|
||||||
|
val chosenColor: Color? = null,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent,
|
||||||
|
PlayerActionEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
|
||||||
|
val theColorCard get() = if (card is Card.CardWithColor) card.color else chosenColor
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.DiscardPile
|
||||||
|
import eventDemo.shared.game.DrawPile
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When the Pile are shuffled after the draw pille was empty
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
class DrawFilledWithDiscardEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
val newDrawPile: DrawPile,
|
||||||
|
val newDiscardPile: DiscardPile,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This [GameEvent] is sent when all players are ready.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class GameCreatedEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import eventDemo.shared.serializers.GameIdSerializer
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An [Event] of a Game.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
sealed interface GameEvent : Event<GameId> {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId
|
||||||
|
|
||||||
|
@Serializable(with = GameIdSerializer::class)
|
||||||
|
override val aggregateId: GameId
|
||||||
|
override val version: Int
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.DiscardPile
|
||||||
|
import eventDemo.shared.game.DrawPile
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.game.PlayerHand
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import eventDemo.shared.serializers.PlayerIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This [GameEvent] is sent when all players are ready.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class GameStartedEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
@Serializable(with = PlayerIdSerializer::class)
|
||||||
|
val firstPlayer: Player.PlayerId,
|
||||||
|
val playersHans: Map<Player.PlayerId, PlayerHand>,
|
||||||
|
val drawPile: DrawPile,
|
||||||
|
val discardPile: DiscardPile,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An [GameEvent] to represent a new player joining the game.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class NewPlayerEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
val player: Player,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent,
|
||||||
|
PlayerActionEvent {
|
||||||
|
override val playerId: Player.PlayerId get() = player.id
|
||||||
|
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
sealed interface PlayerActionEvent : GameEvent {
|
||||||
|
val playerId: Player.PlayerId
|
||||||
|
}
|
||||||
+29
@@ -0,0 +1,29 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.Card
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import eventDemo.shared.serializers.PlayerIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This [GameEvent] is sent when a player can play.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class PlayerHaveDrawCardEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
@Serializable(with = PlayerIdSerializer::class)
|
||||||
|
override val playerId: Player.PlayerId,
|
||||||
|
val takenCards: Set<Card>,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent,
|
||||||
|
PlayerActionEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import eventDemo.shared.serializers.PlayerIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This [GameEvent] is sent when a player is ready.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class PlayerReadyEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
@Serializable(with = PlayerIdSerializer::class)
|
||||||
|
override val playerId: Player.PlayerId,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent,
|
||||||
|
PlayerActionEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package eventDemo.contexts.game.domain.events
|
||||||
|
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
|
import eventDemo.shared.serializers.PlayerIdSerializer
|
||||||
|
import kotlinx.datetime.Clock
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This [GameEvent] is sent when a player is ready.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
data class PlayerWinEvent(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
@Serializable(with = PlayerIdSerializer::class)
|
||||||
|
override val playerId: Player.PlayerId,
|
||||||
|
override val version: Int,
|
||||||
|
) : GameEvent,
|
||||||
|
PlayerActionEvent {
|
||||||
|
@Serializable(with = EventIdSerializer::class)
|
||||||
|
override val eventId: EventId = EventId(Uuid.random())
|
||||||
|
override val createdAt: Instant = Clock.System.now()
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
package eventDemo.contexts.game.domain.game.errors
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Deck
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game
|
||||||
|
import eventDemo.shared.game.Card
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.game.PlayerList
|
||||||
|
|
||||||
|
abstract class GameException(
|
||||||
|
message: String,
|
||||||
|
) : Exception(message)
|
||||||
|
|
||||||
|
abstract class IllegalActionException(
|
||||||
|
message: String,
|
||||||
|
) : GameException(message)
|
||||||
|
|
||||||
|
class ItsNotTheTurnException(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
) : IllegalActionException("It is not the turn of the player") {
|
||||||
|
constructor(playerId: Player.PlayerId, event: GameEvent) : this(playerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
class TheCardIsAColorCardException(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
) : IllegalActionException("The card is a color card")
|
||||||
|
|
||||||
|
class TheCardHasNoColorException(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
) : IllegalActionException("The card has no color, you must chose a color")
|
||||||
|
|
||||||
|
class ThePlayerHasRemainingCardsException(
|
||||||
|
val player: Player,
|
||||||
|
) : IllegalActionException("The player has remaining cards")
|
||||||
|
|
||||||
|
class ThePlayerHasAlreadyWinException(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
) : IllegalActionException("The player has already win")
|
||||||
|
|
||||||
|
class ThePlayerIsNotInTheGameException(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
) : IllegalActionException("The player is not in the game")
|
||||||
|
|
||||||
|
class ThePlayerMustPlayACardException(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
val playableCards: Set<Card>,
|
||||||
|
) : IllegalActionException("The player must be play a card")
|
||||||
|
|
||||||
|
class NeedMorePlayersToStartGameException(
|
||||||
|
val players: PlayerList,
|
||||||
|
) : IllegalActionException("You cannot start a game with less than 2 players!")
|
||||||
|
|
||||||
|
class AllPlayerNotReadyException(
|
||||||
|
val players: PlayerList,
|
||||||
|
) : IllegalActionException("All players not ready!")
|
||||||
|
|
||||||
|
class DeckMissingCardsException(
|
||||||
|
val players: PlayerList,
|
||||||
|
deck: Deck,
|
||||||
|
) : IllegalActionException("The deck missing cards")
|
||||||
|
|
||||||
|
class InconsistentGameException(
|
||||||
|
val game: Game,
|
||||||
|
) : GameException("Inconsistent game state")
|
||||||
|
|
||||||
|
class InconsistentEventVersionException(
|
||||||
|
val game: Set<GameEvent>,
|
||||||
|
) : GameException("Inconsistent event version")
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
package eventDemo.contexts.game.domain.game.gameState
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.CardIsPlayedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.DrawFilledWithDiscardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameCreatedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameStartedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.NewPlayerEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerHaveDrawCardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerReadyEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerWinEvent
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.GameException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.InconsistentEventVersionException
|
||||||
|
import eventDemo.shared.game.PlayerList
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
sealed interface Game {
|
||||||
|
val aggregateId: GameId
|
||||||
|
val players: PlayerList
|
||||||
|
|
||||||
|
/**
|
||||||
|
* On each modification, an event is put in their
|
||||||
|
*/
|
||||||
|
val recordedEvents: Set<GameEvent>
|
||||||
|
val version: Int
|
||||||
|
|
||||||
|
enum class Direction {
|
||||||
|
CLOCKWISE,
|
||||||
|
COUNTER_CLOCKWISE,
|
||||||
|
;
|
||||||
|
|
||||||
|
fun revert(): Direction =
|
||||||
|
if (this === CLOCKWISE) {
|
||||||
|
COUNTER_CLOCKWISE
|
||||||
|
} else {
|
||||||
|
CLOCKWISE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun loadFromHistory(events: Set<GameEvent>): Game =
|
||||||
|
events
|
||||||
|
.fold(GameInit(events.first().aggregateId)) { game: Game, event ->
|
||||||
|
game.run {
|
||||||
|
when (event) {
|
||||||
|
is GameCreatedEvent if this is GameInit -> applyEvent(event)
|
||||||
|
is GameCreatedEvent -> error("Game is already created")
|
||||||
|
is NewPlayerEvent if this is GameCreated -> applyEvent(event)
|
||||||
|
is NewPlayerEvent -> error("Game is already stared")
|
||||||
|
is PlayerReadyEvent if this is GameCreated -> applyEvent(event)
|
||||||
|
is PlayerReadyEvent -> error("Game is already stared")
|
||||||
|
is GameStartedEvent if this is GameCreated -> applyEvent(event)
|
||||||
|
is GameStartedEvent -> error("Game is already started")
|
||||||
|
is CardIsPlayedEvent if this is GameStarted -> applyEvent(event)
|
||||||
|
is CardIsPlayedEvent -> error("Game is end")
|
||||||
|
is PlayerHaveDrawCardEvent if this is GameStarted -> applyEvent(event)
|
||||||
|
is PlayerHaveDrawCardEvent -> error("Game is end")
|
||||||
|
is PlayerWinEvent if this is GameStarted -> applyEvent(event)
|
||||||
|
is PlayerWinEvent -> error("Game is end")
|
||||||
|
is DrawFilledWithDiscardEvent if this is GameStarted -> applyEvent(event)
|
||||||
|
is DrawFilledWithDiscardEvent -> error("Game is end")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.let {
|
||||||
|
when (it) {
|
||||||
|
is GameInit -> it
|
||||||
|
is GameCreated -> it.copy(recordedEvents = emptySet())
|
||||||
|
is GameEnded -> it.copy(recordedEvents = emptySet())
|
||||||
|
is GameStarted -> it.copy(recordedEvents = emptySet())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun <T : GameEvent> T.checkState(
|
||||||
|
block: (T) -> Boolean,
|
||||||
|
exception: (T) -> GameException,
|
||||||
|
): T {
|
||||||
|
if (!block(this)) throw exception(this)
|
||||||
|
return this
|
||||||
|
}
|
||||||
@@ -0,0 +1,179 @@
|
|||||||
|
package eventDemo.contexts.game.domain.game.gameState
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameStartedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.NewPlayerEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerReadyEvent
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.AllPlayerNotReadyException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.DeckMissingCardsException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.NeedMorePlayersToStartGameException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.ThePlayerIsNotInTheGameException
|
||||||
|
import eventDemo.shared.game.Card
|
||||||
|
import eventDemo.shared.game.DiscardPile
|
||||||
|
import eventDemo.shared.game.DrawPile
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.game.PlayerHand
|
||||||
|
import eventDemo.shared.game.PlayerList
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.ids.UserId
|
||||||
|
|
||||||
|
data class GameCreated(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
override val players: PlayerList = PlayerList(),
|
||||||
|
val playersStatus: Map<Player.PlayerId, PlayerStatus> = emptyMap(),
|
||||||
|
override val recordedEvents: Set<GameEvent>,
|
||||||
|
override val version: Int,
|
||||||
|
) : Game {
|
||||||
|
val allPlayerIsReady: Boolean
|
||||||
|
get() {
|
||||||
|
return playersStatus.isNotEmpty() && playersStatus.values.all { it == PlayerStatus.Ready }
|
||||||
|
}
|
||||||
|
|
||||||
|
fun startGame(deck: Deck = newDeck().shuffleDeck()): GameStarted {
|
||||||
|
val (drawPile, discardPile, playersHands) =
|
||||||
|
initPiles(deck)
|
||||||
|
.let { (drawPile, discardPile) ->
|
||||||
|
createHandsFromDrawPile(drawPile)
|
||||||
|
.let { (drawPile, playersHands) ->
|
||||||
|
Triple(drawPile, discardPile, playersHands)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return GameStartedEvent(
|
||||||
|
aggregateId = aggregateId,
|
||||||
|
firstPlayer = players.randomPlayer().id,
|
||||||
|
version = version + 1,
|
||||||
|
drawPile = drawPile,
|
||||||
|
discardPile = discardPile,
|
||||||
|
playersHans = playersHands,
|
||||||
|
).checkState(
|
||||||
|
{ players.size > 1 },
|
||||||
|
{ NeedMorePlayersToStartGameException(players) },
|
||||||
|
).checkState(
|
||||||
|
{ allPlayerIsReady },
|
||||||
|
{ AllPlayerNotReadyException(players) },
|
||||||
|
).checkState(
|
||||||
|
{ deck.size == 108 },
|
||||||
|
{ DeckMissingCardsException(players, deck) },
|
||||||
|
).also { if (it.drawPile.size + it.discardPile.size + playersHands.values.sumOf { it.size } != 108) error("missing cards!") }
|
||||||
|
.run(::applyEvent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initPiles(deck: Set<Card>): Pair<DrawPile, DiscardPile> =
|
||||||
|
DrawPile(deck)
|
||||||
|
.generateValidDrawPile()
|
||||||
|
.take(1)
|
||||||
|
.let { (draw, cards) ->
|
||||||
|
draw to DiscardPile(cards)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createHandsFromDrawPile(drawPile: DrawPile) =
|
||||||
|
players
|
||||||
|
.map { it.id }
|
||||||
|
.fold(Pair(drawPile, emptyMap<Player.PlayerId, PlayerHand>())) { (drawAcc, handsAcc), playerId ->
|
||||||
|
drawAcc
|
||||||
|
.take(7)
|
||||||
|
.let { (draw, hand) ->
|
||||||
|
Pair(
|
||||||
|
draw,
|
||||||
|
handsAcc + (playerId to PlayerHand(hand)),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun userJoinTheGame(
|
||||||
|
userId: UserId,
|
||||||
|
name: String,
|
||||||
|
): GameCreated {
|
||||||
|
if (players.map { it.userId }.contains(userId)) {
|
||||||
|
throw IllegalStateException("User $userId already in party")
|
||||||
|
}
|
||||||
|
|
||||||
|
val player = Player(name, userId)
|
||||||
|
|
||||||
|
return applyEvent(
|
||||||
|
NewPlayerEvent(
|
||||||
|
aggregateId = aggregateId,
|
||||||
|
player = player,
|
||||||
|
version = version + 1,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun setReadyPlayer(playerId: Player.PlayerId): GameCreated {
|
||||||
|
if (!players.map { it.id }.contains(playerId)) {
|
||||||
|
throw ThePlayerIsNotInTheGameException(playerId)
|
||||||
|
}
|
||||||
|
|
||||||
|
return PlayerReadyEvent(aggregateId, playerId, version + 1)
|
||||||
|
.run(::applyEvent)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun applyEvent(event: NewPlayerEvent): GameCreated =
|
||||||
|
copy(
|
||||||
|
players = players + (event.player),
|
||||||
|
playersStatus = playersStatus + (event.player.id to PlayerStatus.Waiting),
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
version = version + 1,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun applyEvent(event: PlayerReadyEvent): GameCreated =
|
||||||
|
copy(
|
||||||
|
playersStatus = playersStatus + (event.playerId to PlayerStatus.Ready),
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
version = version + 1,
|
||||||
|
)
|
||||||
|
|
||||||
|
internal fun applyEvent(event: GameStartedEvent): GameStarted =
|
||||||
|
GameStarted(
|
||||||
|
aggregateId = event.aggregateId,
|
||||||
|
players =
|
||||||
|
players
|
||||||
|
.map {
|
||||||
|
it.copy(hand = event.playersHans[it.id] ?: error("Player ${it.id} not found"))
|
||||||
|
}.let { PlayerList(it.toSet()) },
|
||||||
|
lastPlayerId = null,
|
||||||
|
nextPlayerId = event.firstPlayer,
|
||||||
|
drawPile = event.drawPile,
|
||||||
|
discardPile = event.discardPile,
|
||||||
|
version = event.version + 1,
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
currentColor = event.discardPile.topCardColor ?: error("The discard pile was not initialized!"),
|
||||||
|
)
|
||||||
|
|
||||||
|
enum class PlayerStatus {
|
||||||
|
Ready,
|
||||||
|
Waiting,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
typealias Deck = Set<Card>
|
||||||
|
|
||||||
|
fun newDeck(): Deck =
|
||||||
|
listOf(Card.Color.Red, Card.Color.Blue, Card.Color.Yellow, Card.Color.Green)
|
||||||
|
.flatMap { color ->
|
||||||
|
((0..9) + (1..9)).map { Card.NumericCard(it, color) } +
|
||||||
|
(1..2).map { Card.Plus2Card(color) } +
|
||||||
|
(1..2).map { Card.ReverseCard(color) } +
|
||||||
|
(1..2).map { Card.PassCard(color) }
|
||||||
|
}.let {
|
||||||
|
it + (1..4).map { Card.Plus4Card() }
|
||||||
|
}.let {
|
||||||
|
it + (1..4).map { Card.ChangeColorCard() }
|
||||||
|
}.toSet()
|
||||||
|
|
||||||
|
fun Set<Card>.shuffleDeck(): Set<Card> {
|
||||||
|
if (isDisabled) return this
|
||||||
|
return shuffled().toSet()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun PlayerList.randomPlayer(): Player {
|
||||||
|
if (isDisabled) return first()
|
||||||
|
return random()
|
||||||
|
}
|
||||||
|
|
||||||
|
private var isDisabled = false
|
||||||
|
|
||||||
|
fun disableRandomForTest() {
|
||||||
|
isDisabled = true
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
package eventDemo.contexts.game.domain.game.gameState
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.game.PlayerList
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
data class GameEnded(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
override val players: PlayerList,
|
||||||
|
val playerWins: Set<Player.PlayerId> = emptySet(),
|
||||||
|
override val version: Int,
|
||||||
|
override val recordedEvents: Set<GameEvent>,
|
||||||
|
) : Game {
|
||||||
|
init {
|
||||||
|
if (!players.map { it.id }.containsAll(playerWins)) {
|
||||||
|
throw IllegalArgumentException("Player ${players.map { it.id }} were not in players")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package eventDemo.contexts.game.domain.game.gameState
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.GameCreatedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.shared.game.PlayerList
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
data class GameInit(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
) : Game {
|
||||||
|
override val players: PlayerList = PlayerList()
|
||||||
|
override var recordedEvents: Set<GameEvent> = emptySet()
|
||||||
|
|
||||||
|
// 0 = no events; not persisted; not really exist.
|
||||||
|
override var version: Int = 0
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
fun createNewGame(gameId: GameId = GameId()): GameCreated {
|
||||||
|
val event = GameCreatedEvent(gameId, 1)
|
||||||
|
return GameInit(event.aggregateId).run {
|
||||||
|
event.run(::applyEvent)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun applyEvent(event: GameCreatedEvent): GameCreated =
|
||||||
|
GameCreated(aggregateId, recordedEvents = setOf(event), version = event.version)
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
package eventDemo.contexts.game.domain.game.gameState
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.domain.events.CardIsPlayedEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.DrawFilledWithDiscardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerActionEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerHaveDrawCardEvent
|
||||||
|
import eventDemo.contexts.game.domain.events.PlayerWinEvent
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.InconsistentGameException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.ItsNotTheTurnException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.TheCardHasNoColorException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.TheCardIsAColorCardException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.ThePlayerHasAlreadyWinException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.ThePlayerHasRemainingCardsException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.ThePlayerIsNotInTheGameException
|
||||||
|
import eventDemo.contexts.game.domain.game.errors.ThePlayerMustPlayACardException
|
||||||
|
import eventDemo.contexts.game.domain.game.gameState.Game.Direction
|
||||||
|
import eventDemo.shared.game.Card
|
||||||
|
import eventDemo.shared.game.Card.Color
|
||||||
|
import eventDemo.shared.game.DiscardPile
|
||||||
|
import eventDemo.shared.game.DrawPile
|
||||||
|
import eventDemo.shared.game.Player
|
||||||
|
import eventDemo.shared.game.PlayerList
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
fun PlayerList.nextPlayerTurn(
|
||||||
|
lastPlayerId: Player.PlayerId,
|
||||||
|
direction: Direction,
|
||||||
|
): Player.PlayerId {
|
||||||
|
val lastPlayer = get(lastPlayerId)
|
||||||
|
val playersLastTurn = filter { it.hand.cards.isNotEmpty() || it == lastPlayer }
|
||||||
|
|
||||||
|
return playersLastTurn
|
||||||
|
.indexOf(lastPlayer)
|
||||||
|
.let { lastPlayerIndex ->
|
||||||
|
if (direction == Direction.CLOCKWISE) {
|
||||||
|
if (lastPlayerIndex == playersLastTurn.size - 1) {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
lastPlayerIndex + 1
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (lastPlayerIndex == 0) {
|
||||||
|
playersLastTurn.size - 1
|
||||||
|
} else {
|
||||||
|
lastPlayerIndex - 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}.let { nextPlayerIndex -> elementAt(nextPlayerIndex).id }
|
||||||
|
}
|
||||||
|
|
||||||
|
data class GameStarted(
|
||||||
|
override val aggregateId: GameId,
|
||||||
|
override val players: PlayerList,
|
||||||
|
val drawPile: DrawPile,
|
||||||
|
val discardPile: DiscardPile,
|
||||||
|
val lastPlayerId: Player.PlayerId?,
|
||||||
|
val nextPlayerId: Player.PlayerId,
|
||||||
|
val currentColor: Color,
|
||||||
|
val playedTurnHistory: List<History> = emptyList(),
|
||||||
|
val direction: Direction = Direction.CLOCKWISE,
|
||||||
|
val playerWins: Set<Player.PlayerId> = emptySet(),
|
||||||
|
override val version: Int,
|
||||||
|
override val recordedEvents: Set<GameEvent>,
|
||||||
|
) : Game {
|
||||||
|
val playersInGame by lazy { players.filter { it.hand.cards.isNotEmpty() } }
|
||||||
|
|
||||||
|
val lastPlayedCard: Card? by lazy { discardPile.topCard }
|
||||||
|
|
||||||
|
data class History(
|
||||||
|
val playerId: Player.PlayerId,
|
||||||
|
val event: GameEvent,
|
||||||
|
val direction: Direction,
|
||||||
|
)
|
||||||
|
|
||||||
|
val lastPlayer: Player? by lazy { lastPlayerId?.let { players.get(it) } }
|
||||||
|
|
||||||
|
val nextPlayer: Player by lazy { players.get(nextPlayerId) }
|
||||||
|
|
||||||
|
fun canBePlayThisCard(card: Card): Boolean {
|
||||||
|
val cardOnBoard = discardPile.topCard ?: return false
|
||||||
|
return when (cardOnBoard) {
|
||||||
|
is Card.NumericCard -> {
|
||||||
|
when (card) {
|
||||||
|
is Card.CardWith4Color -> true
|
||||||
|
is Card.NumericCard -> card.number == cardOnBoard.number || card.color == cardOnBoard.color
|
||||||
|
is Card.CardWithColor -> card.color == cardOnBoard.color
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is Card.ReverseCard -> {
|
||||||
|
when (card) {
|
||||||
|
is Card.ReverseCard -> true
|
||||||
|
is Card.CardWith4Color -> true
|
||||||
|
is Card.CardWithColor -> card.color == cardOnBoard.color
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is Card.PassCard -> {
|
||||||
|
when (card) {
|
||||||
|
is Card.CardWith4Color -> true
|
||||||
|
is Card.CardWithColor -> card.color == cardOnBoard.color
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is Card.ChangeColorCard -> {
|
||||||
|
when (card) {
|
||||||
|
is Card.CardWith4Color -> true
|
||||||
|
is Card.CardWithColor -> card.color == currentColor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is Card.Plus2Card -> {
|
||||||
|
when (card) {
|
||||||
|
is Card.Plus2Card -> true
|
||||||
|
::isPlayedLastTurn -> false
|
||||||
|
is Card.CardWith4Color -> true
|
||||||
|
is Card.CardWithColor -> card.color == currentColor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
is Card.Plus4Card -> {
|
||||||
|
when (card) {
|
||||||
|
is Card.Plus4Card -> true
|
||||||
|
::isPlayedLastTurn -> false
|
||||||
|
is Card.CardWith4Color -> true
|
||||||
|
is Card.CardWithColor -> card.color == currentColor
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun playableCards(playerId: Player.PlayerId): Set<Card> =
|
||||||
|
players
|
||||||
|
.get(playerId)
|
||||||
|
.hand
|
||||||
|
.cards
|
||||||
|
.filter(::canBePlayThisCard)
|
||||||
|
.toSet()
|
||||||
|
|
||||||
|
fun playTheCard(
|
||||||
|
playerId: Player.PlayerId,
|
||||||
|
card: Card,
|
||||||
|
chosenColor: Color? = null,
|
||||||
|
): GameStarted =
|
||||||
|
CardIsPlayedEvent(aggregateId, card, playerId, chosenColor, version + 1)
|
||||||
|
.checkPlayerTurn()
|
||||||
|
.checkState({
|
||||||
|
(card is Card.CardWithColor && chosenColor == null) || card is Card.CardWith4Color
|
||||||
|
}, { TheCardIsAColorCardException(playerId) })
|
||||||
|
.checkState({
|
||||||
|
(card is Card.CardWith4Color && chosenColor != null) || card is Card.CardWithColor
|
||||||
|
}, { TheCardHasNoColorException(playerId) })
|
||||||
|
.run(::applyEvent)
|
||||||
|
|
||||||
|
internal fun applyEvent(event: CardIsPlayedEvent): GameStarted =
|
||||||
|
run {
|
||||||
|
val nextDirectionAfterPlay =
|
||||||
|
when (event.card) {
|
||||||
|
is Card.ReverseCard -> direction.revert()
|
||||||
|
else -> direction
|
||||||
|
}
|
||||||
|
|
||||||
|
val color =
|
||||||
|
when (event.card) {
|
||||||
|
is Card.CardWithColor -> event.card.color
|
||||||
|
is Card.CardWith4Color -> event.chosenColor!!
|
||||||
|
}
|
||||||
|
|
||||||
|
copy(
|
||||||
|
players = players.withDropCardOnPlayerHand(event.playerId, event.card),
|
||||||
|
discardPile = discardPile.withNewCard(card = event.card),
|
||||||
|
currentColor = color,
|
||||||
|
lastPlayerId = event.playerId,
|
||||||
|
nextPlayerId = players.nextPlayerTurn(event.playerId, nextDirectionAfterPlay),
|
||||||
|
playedTurnHistory = playedTurnHistory - History(event.playerId, event, direction),
|
||||||
|
direction = nextDirectionAfterPlay,
|
||||||
|
version = event.version,
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun playerTakeCartFromDrawPile(
|
||||||
|
playerId: Player.PlayerId,
|
||||||
|
number: Int,
|
||||||
|
): GameStarted {
|
||||||
|
val takenCards = drawPile.take(number).second
|
||||||
|
return PlayerHaveDrawCardEvent(aggregateId, playerId, takenCards, version + 1)
|
||||||
|
.checkPlayerTurn()
|
||||||
|
.checkState({
|
||||||
|
playableCards(playerId).isEmpty()
|
||||||
|
}, {
|
||||||
|
ThePlayerMustPlayACardException(playerId, playableCards(playerId))
|
||||||
|
})
|
||||||
|
.run(::applyEvent)
|
||||||
|
.run {
|
||||||
|
val missingCardsCount = number - takenCards.size
|
||||||
|
if (missingCardsCount > 0) {
|
||||||
|
fillDrawWithDiscard()
|
||||||
|
.playerTakeCartFromDrawPile(playerId, missingCardsCount)
|
||||||
|
} else {
|
||||||
|
this
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun applyEvent(event: PlayerHaveDrawCardEvent): GameStarted =
|
||||||
|
copy(
|
||||||
|
players = players.withNewCardOnPlayerHand(event.playerId, event.takenCards),
|
||||||
|
drawPile = drawPile.take(event.takenCards.size).first,
|
||||||
|
lastPlayerId = event.playerId,
|
||||||
|
nextPlayerId = players.nextPlayerTurn(event.playerId, direction),
|
||||||
|
version = event.version,
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filling the draw pile with the discard pile while excluding the top card
|
||||||
|
*/
|
||||||
|
private fun fillDrawWithDiscard(): GameStarted =
|
||||||
|
run {
|
||||||
|
val topCard = discardPile.topCard ?: throw InconsistentGameException(this)
|
||||||
|
DrawPile(discardPile.cards - topCard).shuffled() to DiscardPile(setOf(topCard))
|
||||||
|
}.let { (newDrawPile, newDiscardPile) ->
|
||||||
|
DrawFilledWithDiscardEvent(aggregateId, newDrawPile, newDiscardPile, version + 1)
|
||||||
|
.run(::applyEvent)
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun applyEvent(event: DrawFilledWithDiscardEvent): GameStarted =
|
||||||
|
copy(
|
||||||
|
drawPile = event.newDrawPile,
|
||||||
|
discardPile = event.newDiscardPile,
|
||||||
|
version = event.version,
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
)
|
||||||
|
|
||||||
|
fun playerWin(playerId: Player.PlayerId): GameStarted =
|
||||||
|
PlayerWinEvent(aggregateId, playerId, version + 1)
|
||||||
|
.checkState({
|
||||||
|
players
|
||||||
|
.get(playerId)
|
||||||
|
.hand.cards
|
||||||
|
.isEmpty()
|
||||||
|
}, { ThePlayerHasRemainingCardsException(players.get(playerId)) })
|
||||||
|
.checkState({ playerWins.contains(playerId) }, { ThePlayerHasAlreadyWinException(playerId) })
|
||||||
|
.checkState({ !players.map { it.id }.contains(playerId) }, { ThePlayerIsNotInTheGameException(playerId) })
|
||||||
|
.run(::applyEvent)
|
||||||
|
|
||||||
|
internal fun applyEvent(event: PlayerWinEvent): GameStarted =
|
||||||
|
copy(
|
||||||
|
playerWins = playerWins + event.playerId,
|
||||||
|
version = event.version,
|
||||||
|
recordedEvents = recordedEvents + event,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun <T : PlayerActionEvent> T.checkPlayerTurn(): T =
|
||||||
|
checkState(
|
||||||
|
{ nextPlayer.id == playerId },
|
||||||
|
{ ItsNotTheTurnException(playerId, this) },
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun isPlayedLastTurn(card: Card): Boolean =
|
||||||
|
(playedTurnHistory.last().event as? CardIsPlayedEvent)?.card == card
|
||||||
|
}
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.injections.application
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameEventStoreRepository
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.notification.EventToNotificationSubscriber
|
||||||
|
import eventDemo.contexts.game.application.reaction.ReactionListener
|
||||||
|
import org.koin.core.module.Module
|
||||||
|
import org.koin.core.module.dsl.singleOf
|
||||||
|
import org.koin.dsl.bind
|
||||||
|
|
||||||
|
fun Module.configureGameDIApplication() {
|
||||||
|
configureDICommandHandlers()
|
||||||
|
|
||||||
|
singleOf(::ReactionListener)
|
||||||
|
singleOf(::EventToNotificationSubscriber)
|
||||||
|
singleOf(::GameEventStoreRepository) bind GameRepository::class
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.injections.application
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.JoinTheGameHandler
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.PlayCardHandler
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.ReadyToPlayHandler
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.TakeCartFromDrawPileHandler
|
||||||
|
import org.koin.core.module.Module
|
||||||
|
import org.koin.core.module.dsl.singleOf
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure all actions
|
||||||
|
*/
|
||||||
|
fun Module.configureDICommandHandlers() {
|
||||||
|
singleOf(::PlayCardHandler)
|
||||||
|
singleOf(::ReadyToPlayHandler)
|
||||||
|
singleOf(::JoinTheGameHandler)
|
||||||
|
singleOf(::TakeCartFromDrawPileHandler)
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.injections.infrastructure
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.channels.GameChannelsSubscriber
|
||||||
|
import eventDemo.contexts.game.application.command.handlers.GameCommandHandlerDispatcher
|
||||||
|
import eventDemo.contexts.game.application.notification.CommandSubscriber
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventStore
|
||||||
|
import eventDemo.contexts.game.application.ports.GameProjectionBus
|
||||||
|
import eventDemo.contexts.game.infrastructure.persistence.eventBus.GameEventBusInRabbinMQ
|
||||||
|
import eventDemo.contexts.game.infrastructure.persistence.eventStore.GameEventStoreInPostgresql
|
||||||
|
import eventDemo.contexts.game.infrastructure.persistence.projections.GameListRepositoryInMemory
|
||||||
|
import eventDemo.contexts.game.infrastructure.persistence.projections.bus.GameProjectionBusInRabbitMQ
|
||||||
|
import eventDemo.domain.event.projection.GameListRepository
|
||||||
|
import org.koin.core.module.Module
|
||||||
|
import org.koin.core.module.dsl.singleOf
|
||||||
|
import org.koin.dsl.bind
|
||||||
|
|
||||||
|
fun Module.configureGameDIInfrastructure() {
|
||||||
|
singleOf(::GameEventStoreInPostgresql) bind GameEventStore::class
|
||||||
|
singleOf(::GameEventBusInRabbinMQ) bind GameEventBus::class
|
||||||
|
singleOf(::GameProjectionBusInRabbitMQ) bind GameProjectionBus::class
|
||||||
|
singleOf(::CommandSubscriber)
|
||||||
|
singleOf(::GameChannelsSubscriber)
|
||||||
|
singleOf(::GameCommandHandlerDispatcher)
|
||||||
|
singleOf(::GameListRepositoryInMemory) bind GameListRepository::class
|
||||||
|
}
|
||||||
+2
-16
@@ -1,5 +1,6 @@
|
|||||||
package eventDemo.configuration.ktor
|
package eventDemo.contexts.game.infrastructure.configuration.ktor
|
||||||
|
|
||||||
|
import eventDemo.shared.http.HttpErrorBadRequest
|
||||||
import io.ktor.http.HttpHeaders
|
import io.ktor.http.HttpHeaders
|
||||||
import io.ktor.http.HttpMethod
|
import io.ktor.http.HttpMethod
|
||||||
import io.ktor.http.HttpStatusCode
|
import io.ktor.http.HttpStatusCode
|
||||||
@@ -10,7 +11,6 @@ import io.ktor.server.plugins.cors.routing.CORS
|
|||||||
import io.ktor.server.plugins.statuspages.StatusPages
|
import io.ktor.server.plugins.statuspages.StatusPages
|
||||||
import io.ktor.server.resources.Resources
|
import io.ktor.server.resources.Resources
|
||||||
import io.ktor.server.response.respondText
|
import io.ktor.server.response.respondText
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
|
|
||||||
fun Application.configureHttpRouting() {
|
fun Application.configureHttpRouting() {
|
||||||
install(CORS) {
|
install(CORS) {
|
||||||
@@ -38,17 +38,3 @@ fun Application.configureHttpRouting() {
|
|||||||
class BadRequestException(
|
class BadRequestException(
|
||||||
val httpError: HttpErrorBadRequest,
|
val httpError: HttpErrorBadRequest,
|
||||||
) : Exception()
|
) : Exception()
|
||||||
|
|
||||||
@Serializable
|
|
||||||
class HttpErrorBadRequest(
|
|
||||||
val title: String = HttpStatusCode.BadRequest.description,
|
|
||||||
val invalidParams: List<InvalidParam> = emptyList(),
|
|
||||||
) {
|
|
||||||
val statusCode: Int = HttpStatusCode.BadRequest.value
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class InvalidParam(
|
|
||||||
val name: String,
|
|
||||||
val reason: String,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
+13
-10
@@ -1,19 +1,21 @@
|
|||||||
package eventDemo.configuration.ktor
|
package eventDemo.contexts.game.infrastructure.configuration.ktor
|
||||||
|
|
||||||
import eventDemo.domain.entity.GameId
|
import eventDemo.shared.game.Player
|
||||||
import eventDemo.domain.entity.Player
|
import eventDemo.shared.ids.CommandId
|
||||||
import eventDemo.configuration.serializer.CommandIdSerializer
|
import eventDemo.shared.ids.EventId
|
||||||
import eventDemo.configuration.serializer.GameIdSerializer
|
import eventDemo.shared.ids.GameId
|
||||||
import eventDemo.configuration.serializer.PlayerIdSerializer
|
import eventDemo.shared.serializers.CommandIdSerializer
|
||||||
import eventDemo.configuration.serializer.UUIDSerializer
|
import eventDemo.shared.serializers.EventIdSerializer
|
||||||
import eventDemo.libs.command.CommandId
|
import eventDemo.shared.serializers.GameIdSerializer
|
||||||
|
import eventDemo.shared.serializers.PlayerIdSerializer
|
||||||
|
import eventDemo.shared.serializers.UUIDSerializer
|
||||||
import io.ktor.serialization.kotlinx.json.json
|
import io.ktor.serialization.kotlinx.json.json
|
||||||
import io.ktor.server.application.Application
|
import io.ktor.server.application.Application
|
||||||
import io.ktor.server.application.install
|
import io.ktor.server.application.install
|
||||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import kotlinx.serialization.modules.SerializersModule
|
import kotlinx.serialization.modules.SerializersModule
|
||||||
import java.util.UUID
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
fun Application.configureSerialization() {
|
fun Application.configureSerialization() {
|
||||||
install(ContentNegotiation) {
|
install(ContentNegotiation) {
|
||||||
@@ -27,8 +29,9 @@ fun defaultJsonSerializer(): Json =
|
|||||||
Json {
|
Json {
|
||||||
serializersModule =
|
serializersModule =
|
||||||
SerializersModule {
|
SerializersModule {
|
||||||
contextual(UUID::class) { UUIDSerializer }
|
contextual(Uuid::class) { UUIDSerializer }
|
||||||
contextual(GameId::class) { GameIdSerializer }
|
contextual(GameId::class) { GameIdSerializer }
|
||||||
|
contextual(EventId::class) { EventIdSerializer }
|
||||||
contextual(CommandId::class) { CommandIdSerializer }
|
contextual(CommandId::class) { CommandIdSerializer }
|
||||||
contextual(Player.PlayerId::class) { PlayerIdSerializer }
|
contextual(Player.PlayerId::class) { PlayerIdSerializer }
|
||||||
}
|
}
|
||||||
+21
@@ -0,0 +1,21 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.ktor
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.infrastructure.configuration.listener.configureProjectionListener
|
||||||
|
import eventDemo.contexts.game.infrastructure.configuration.listener.configureReactionListener
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
import org.koin.ktor.plugin.koin
|
||||||
|
|
||||||
|
fun Application.configureUno() {
|
||||||
|
configureSerialization()
|
||||||
|
|
||||||
|
configureWebSockets()
|
||||||
|
declareWebSocketsRoute()
|
||||||
|
|
||||||
|
configureHttpRouting()
|
||||||
|
declareHttpGameRoute()
|
||||||
|
|
||||||
|
koin().run {
|
||||||
|
configureProjectionListener()
|
||||||
|
configureReactionListener()
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
package eventDemo.configuration.ktor
|
package eventDemo.contexts.game.infrastructure.configuration.ktor
|
||||||
|
|
||||||
import io.ktor.server.application.Application
|
import io.ktor.server.application.Application
|
||||||
import io.ktor.server.application.install
|
import io.ktor.server.application.install
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.ktor
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.infrastructure.rest.gamesListRoute
|
||||||
|
import eventDemo.contexts.game.infrastructure.rest.getFullNotificationsRoute
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
import io.ktor.server.routing.routing
|
||||||
|
import org.koin.ktor.ext.get as getDi
|
||||||
|
|
||||||
|
fun Application.declareHttpGameRoute() {
|
||||||
|
routing {
|
||||||
|
gamesListRoute(getDi())
|
||||||
|
getFullNotificationsRoute(getDi(), getDi())
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
@@ -0,0 +1,16 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.ktor
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.infrastructure.websocket.gameWebSocket
|
||||||
|
import io.ktor.server.application.Application
|
||||||
|
import io.ktor.server.routing.routing
|
||||||
|
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||||
|
import org.koin.ktor.ext.get as getDi
|
||||||
|
|
||||||
|
@OptIn(DelicateCoroutinesApi::class)
|
||||||
|
fun Application.declareWebSocketsRoute() {
|
||||||
|
routing {
|
||||||
|
gameWebSocket(
|
||||||
|
getDi(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.listener
|
||||||
|
|
||||||
|
import eventDemo.domain.event.projection.GameListRepository
|
||||||
|
import org.koin.core.Koin
|
||||||
|
|
||||||
|
fun Koin.configureProjectionListener() {
|
||||||
|
get<GameListRepository>()
|
||||||
|
.subscribeToBus()
|
||||||
|
}
|
||||||
+9
@@ -0,0 +1,9 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.configuration.listener
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.reaction.ReactionListener
|
||||||
|
import org.koin.core.Koin
|
||||||
|
|
||||||
|
fun Koin.configureReactionListener() {
|
||||||
|
get<ReactionListener>()
|
||||||
|
.subscribeToBus()
|
||||||
|
}
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
package eventDemo.adapter.infrastructure.event
|
package eventDemo.contexts.game.infrastructure.persistence.eventBus
|
||||||
|
|
||||||
import eventDemo.domain.event.GameEventBus
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
import eventDemo.domain.event.event.GameEvent
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
import eventDemo.libs.bus.Bus
|
import eventDemo.libs.bus.Bus
|
||||||
import eventDemo.libs.bus.BusInMemory
|
import eventDemo.libs.bus.BusInMemory
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
+3
-3
@@ -1,8 +1,8 @@
|
|||||||
package eventDemo.adapter.infrastructure.event
|
package eventDemo.contexts.game.infrastructure.persistence.eventBus
|
||||||
|
|
||||||
import com.rabbitmq.client.ConnectionFactory
|
import com.rabbitmq.client.ConnectionFactory
|
||||||
import eventDemo.domain.event.GameEventBus
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
import eventDemo.domain.event.event.GameEvent
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
import eventDemo.libs.bus.Bus
|
import eventDemo.libs.bus.Bus
|
||||||
import eventDemo.libs.bus.BusInRabbitMQ
|
import eventDemo.libs.bus.BusInRabbitMQ
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.persistence.eventStore
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventStore
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStore
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStoreInMemory
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A stream to publish and read the played card event.
|
||||||
|
*/
|
||||||
|
class GameEventStoreInMemory :
|
||||||
|
GameEventStore,
|
||||||
|
EventStore<GameEvent, GameId> by EventStoreInMemory()
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.persistence.eventStore
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventStore
|
||||||
|
import eventDemo.contexts.game.domain.events.GameEvent
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStore
|
||||||
|
import eventDemo.libs.eventSource.eventStore.EventStoreInPostgresql
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import kotlinx.serialization.json.Json
|
||||||
|
import javax.sql.DataSource
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A stream to publish and read the played card event.
|
||||||
|
*/
|
||||||
|
class GameEventStoreInPostgresql(
|
||||||
|
dataSource: DataSource,
|
||||||
|
) : GameEventStore,
|
||||||
|
EventStore<GameEvent, GameId> by EventStoreInPostgresql(
|
||||||
|
dataSource,
|
||||||
|
{ Json.encodeToString(it) },
|
||||||
|
{ Json.decodeFromString(it) },
|
||||||
|
"game.game_event_stream",
|
||||||
|
)
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.persistence.projections
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventBus
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventStore
|
||||||
|
import eventDemo.contexts.game.application.ports.GameProjectionBus
|
||||||
|
import eventDemo.contexts.game.application.projections.applyEvent
|
||||||
|
import eventDemo.domain.event.projection.GameListRepository
|
||||||
|
import eventDemo.shared.game.projection.GameList
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages [projections][GameList], their building and publication in the [bus][GameProjectionBus].
|
||||||
|
*/
|
||||||
|
class GameListRepositoryInMemory(
|
||||||
|
val gameEventStore: GameEventStore,
|
||||||
|
val projectionBus: GameProjectionBus,
|
||||||
|
val eventBus: GameEventBus,
|
||||||
|
) : GameListRepository {
|
||||||
|
val projections: MutableMap<GameId, GameList> = mutableMapOf()
|
||||||
|
|
||||||
|
override fun getList(
|
||||||
|
limit: Int,
|
||||||
|
offset: Int,
|
||||||
|
): List<GameList> =
|
||||||
|
projections
|
||||||
|
.values
|
||||||
|
.drop(offset)
|
||||||
|
.take(limit)
|
||||||
|
|
||||||
|
override fun save(gameList: GameList) {
|
||||||
|
projections[gameList.aggregateId] = gameList
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun subscribeToBus() {
|
||||||
|
// On new event was received, build projection and publish it to the projection bus
|
||||||
|
eventBus.subscribe { event ->
|
||||||
|
withLoggingContext("event" to event.toString()) {
|
||||||
|
gameEventStore
|
||||||
|
.getStream(event.aggregateId)
|
||||||
|
.readAll()
|
||||||
|
.fold(GameList(event.aggregateId)) { acc, event ->
|
||||||
|
acc.applyEvent(event)
|
||||||
|
}.also { save(it) }
|
||||||
|
.also { projectionBus.publish(it) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+3
-3
@@ -1,9 +1,9 @@
|
|||||||
package eventDemo.adapter.infrastructure.event.projection
|
package eventDemo.contexts.game.infrastructure.persistence.projections.bus
|
||||||
|
|
||||||
import eventDemo.domain.event.projection.GameProjection
|
import eventDemo.contexts.game.application.ports.GameProjectionBus
|
||||||
import eventDemo.domain.event.projection.GameProjectionBus
|
|
||||||
import eventDemo.libs.bus.Bus
|
import eventDemo.libs.bus.Bus
|
||||||
import eventDemo.libs.bus.BusInMemory
|
import eventDemo.libs.bus.BusInMemory
|
||||||
|
import eventDemo.shared.game.projection.GameProjection
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
class GameProjectionBusInMemory :
|
class GameProjectionBusInMemory :
|
||||||
+3
-3
@@ -1,10 +1,10 @@
|
|||||||
package eventDemo.adapter.infrastructure.event.projection
|
package eventDemo.contexts.game.infrastructure.persistence.projections.bus
|
||||||
|
|
||||||
import com.rabbitmq.client.ConnectionFactory
|
import com.rabbitmq.client.ConnectionFactory
|
||||||
import eventDemo.domain.event.projection.GameProjection
|
import eventDemo.contexts.game.application.ports.GameProjectionBus
|
||||||
import eventDemo.domain.event.projection.GameProjectionBus
|
|
||||||
import eventDemo.libs.bus.Bus
|
import eventDemo.libs.bus.Bus
|
||||||
import eventDemo.libs.bus.BusInRabbitMQ
|
import eventDemo.libs.bus.BusInRabbitMQ
|
||||||
|
import eventDemo.shared.game.projection.GameProjection
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import java.util.UUID
|
import java.util.UUID
|
||||||
|
|
||||||
+2
-2
@@ -1,4 +1,4 @@
|
|||||||
package eventDemo.adapter.presenter.query
|
package eventDemo.contexts.game.infrastructure.rest
|
||||||
|
|
||||||
import eventDemo.domain.event.projection.GameListRepository
|
import eventDemo.domain.event.projection.GameListRepository
|
||||||
import io.ktor.resources.Resource
|
import io.ktor.resources.Resource
|
||||||
@@ -15,7 +15,7 @@ class Games
|
|||||||
/**
|
/**
|
||||||
* API routes to show all games.
|
* API routes to show all games.
|
||||||
*/
|
*/
|
||||||
fun Route.readGamesList(gameListRepository: GameListRepository) {
|
fun Route.gamesListRoute(gameListRepository: GameListRepository) {
|
||||||
authenticate {
|
authenticate {
|
||||||
// Read the last played card on the game.
|
// Read the last played card on the game.
|
||||||
get<Games> {
|
get<Games> {
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.rest
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.eventStores.GameRepository
|
||||||
|
import eventDemo.contexts.game.application.notification.toNotification
|
||||||
|
import eventDemo.contexts.game.application.ports.GameEventStore
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.shared.serializers.GameIdSerializer
|
||||||
|
import eventDemo.sharedKernel.currentUserId
|
||||||
|
import io.ktor.http.HttpStatusCode
|
||||||
|
import io.ktor.resources.Resource
|
||||||
|
import io.ktor.server.auth.authenticate
|
||||||
|
import io.ktor.server.resources.get
|
||||||
|
import io.ktor.server.response.respond
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
@Resource("/games/{id}")
|
||||||
|
class Game(
|
||||||
|
@Serializable(with = GameIdSerializer::class)
|
||||||
|
val id: GameId,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* API routes to read the game state.
|
||||||
|
*/
|
||||||
|
fun Route.getFullNotificationsRoute(
|
||||||
|
gameRepository: GameRepository,
|
||||||
|
gameEventStore: GameEventStore,
|
||||||
|
) {
|
||||||
|
authenticate {
|
||||||
|
get<Game> { body ->
|
||||||
|
val game =
|
||||||
|
gameRepository.get(body.id)
|
||||||
|
?: return@get call.respond(HttpStatusCode.NotFound)
|
||||||
|
val notifications =
|
||||||
|
gameEventStore
|
||||||
|
.getStream(body.id)
|
||||||
|
.readAll()
|
||||||
|
.flatMap { it.toNotification(game, call.currentUserId) }
|
||||||
|
|
||||||
|
call.respond(notifications)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package eventDemo.contexts.game.infrastructure.websocket
|
||||||
|
|
||||||
|
import eventDemo.contexts.game.application.channels.GameChannelsSubscriber
|
||||||
|
import eventDemo.libs.helpers.fromFrameChannel
|
||||||
|
import eventDemo.libs.helpers.toObjectChannel
|
||||||
|
import eventDemo.shared.ids.GameId
|
||||||
|
import eventDemo.sharedKernel.currentUserId
|
||||||
|
import io.ktor.server.auth.authenticate
|
||||||
|
import io.ktor.server.routing.Route
|
||||||
|
import io.ktor.server.websocket.webSocket
|
||||||
|
import kotlinx.coroutines.DelicateCoroutinesApi
|
||||||
|
import kotlin.uuid.Uuid
|
||||||
|
|
||||||
|
@DelicateCoroutinesApi
|
||||||
|
fun Route.gameWebSocket(channelSubscriber: GameChannelsSubscriber) {
|
||||||
|
authenticate {
|
||||||
|
webSocket("/games/{id}") {
|
||||||
|
channelSubscriber.subscribePlayerToGameChannels(
|
||||||
|
gameId = GameId(Uuid.parse(call.parameters["id"]!!)),
|
||||||
|
userId = call.currentUserId,
|
||||||
|
incomingCommandChannel = toObjectChannel(incoming),
|
||||||
|
sendNotificationChannel = fromFrameChannel(outgoing),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
@@ -6,6 +6,10 @@ interface Bus<T> {
|
|||||||
*/
|
*/
|
||||||
fun publish(item: T)
|
fun publish(item: T)
|
||||||
|
|
||||||
|
fun publish(items: Collection<T>) {
|
||||||
|
items.forEach { publish(it) }
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Subscribe a [lambda][block] to the bus.
|
* Subscribe a [lambda][block] to the bus.
|
||||||
*
|
*
|
||||||
+17
-10
@@ -7,6 +7,7 @@ import com.rabbitmq.client.ConnectionFactory
|
|||||||
import com.rabbitmq.client.DefaultConsumer
|
import com.rabbitmq.client.DefaultConsumer
|
||||||
import com.rabbitmq.client.Envelope
|
import com.rabbitmq.client.Envelope
|
||||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||||
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
import io.ktor.utils.io.core.toByteArray
|
import io.ktor.utils.io.core.toByteArray
|
||||||
import kotlinx.coroutines.runBlocking
|
import kotlinx.coroutines.runBlocking
|
||||||
|
|
||||||
@@ -43,15 +44,17 @@ class BusInRabbitMQ<E>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun publish(item: E) {
|
override fun publish(item: E) {
|
||||||
connection
|
withLoggingContext("item" to item.toString()) {
|
||||||
.createChannel()
|
connection
|
||||||
.basicPublish(
|
.createChannel()
|
||||||
exchangeName,
|
.basicPublish(
|
||||||
routingKey,
|
exchangeName,
|
||||||
AMQP.BasicProperties(),
|
routingKey,
|
||||||
objectToString(item).toByteArray(),
|
AMQP.BasicProperties(),
|
||||||
)
|
objectToString(item).toByteArray(),
|
||||||
logger.info { "Item sent to the bus" }
|
)
|
||||||
|
logger.info { "Item sent to the bus" }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun subscribe(block: (E) -> Unit): Bus.Subscription {
|
override fun subscribe(block: (E) -> Unit): Bus.Subscription {
|
||||||
@@ -75,7 +78,11 @@ class BusInRabbitMQ<E>(
|
|||||||
body: ByteArray,
|
body: ByteArray,
|
||||||
) {
|
) {
|
||||||
runBlocking {
|
runBlocking {
|
||||||
block(stringToObject(body.toString(Charsets.UTF_8)))
|
val obj = stringToObject(body.toString(Charsets.UTF_8))
|
||||||
|
withLoggingContext("item" to obj.toString()) {
|
||||||
|
logger.info { "Received delivery of $exchangeName" }
|
||||||
|
}
|
||||||
|
block(obj)
|
||||||
}
|
}
|
||||||
channel.basicAck(envelope.deliveryTag, false)
|
channel.basicAck(envelope.deliveryTag, false)
|
||||||
}
|
}
|
||||||
+9
-7
@@ -1,5 +1,7 @@
|
|||||||
package eventDemo.libs.command
|
package eventDemo.libs.command
|
||||||
|
|
||||||
|
import eventDemo.shared.command.Command
|
||||||
|
import eventDemo.shared.ids.CommandId
|
||||||
import kotlinx.datetime.Clock
|
import kotlinx.datetime.Clock
|
||||||
import kotlinx.datetime.Instant
|
import kotlinx.datetime.Instant
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
@@ -9,32 +11,32 @@ import kotlin.time.Duration.Companion.minutes
|
|||||||
/**
|
/**
|
||||||
* Controls the execution of a command to prevent it from being executed more than once.
|
* Controls the execution of a command to prevent it from being executed more than once.
|
||||||
*/
|
*/
|
||||||
class CommandRunnerController<C : Command>(
|
class CommandUnicityChecker<C : Command>(
|
||||||
private val maxCacheTime: Duration = 10.minutes,
|
private val maxCacheTime: Duration = 10.minutes,
|
||||||
) {
|
) {
|
||||||
private val executedCommand: ConcurrentHashMap<CommandId, Pair<Boolean, Instant>> = ConcurrentHashMap()
|
private val executedCommand: ConcurrentHashMap<CommandId, Pair<Boolean, Instant>> = ConcurrentHashMap()
|
||||||
|
|
||||||
fun runOnlyOnce(
|
fun runOnlyOnce(
|
||||||
command: C,
|
command: C,
|
||||||
action: CommandBlock<C>,
|
action: (C) -> Unit,
|
||||||
) {
|
) {
|
||||||
if (!isAlreadyExecuted(command)) {
|
if (!isAlreadyExecuted(command)) {
|
||||||
action(command)
|
action(command)
|
||||||
setAsExecuted(command)
|
setAsExecuted(command)
|
||||||
removeOldCache()
|
removeOldCache()
|
||||||
} else {
|
} else {
|
||||||
throw Exception("Command already executed", command)
|
throw UnicityException("Command already executed", command)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun setAsExecuted(command: C) {
|
private fun setAsExecuted(command: C) {
|
||||||
executedCommand.computeIfAbsent(command.id) { Pair(false, Clock.System.now()) }
|
executedCommand.computeIfAbsent(command.id) { Pair(true, Clock.System.now()) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun removeOldCache() {
|
private fun removeOldCache() {
|
||||||
executedCommand
|
executedCommand
|
||||||
.filterValues { (_, date) ->
|
.filterValues { (_, date) ->
|
||||||
(date + maxCacheTime) > Clock.System.now()
|
(date + maxCacheTime) < Clock.System.now()
|
||||||
}.keys
|
}.keys
|
||||||
.forEach {
|
.forEach {
|
||||||
executedCommand.remove(it)
|
executedCommand.remove(it)
|
||||||
@@ -44,8 +46,8 @@ class CommandRunnerController<C : Command>(
|
|||||||
private fun isAlreadyExecuted(command: C): Boolean =
|
private fun isAlreadyExecuted(command: C): Boolean =
|
||||||
executedCommand[command.id]?.first ?: false
|
executedCommand[command.id]?.first ?: false
|
||||||
|
|
||||||
class Exception(
|
class UnicityException(
|
||||||
override val message: String,
|
override val message: String,
|
||||||
val command: Command,
|
val command: Command,
|
||||||
) : kotlin.Exception(message)
|
) : Exception(message)
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
package eventDemo.libs.eventSource
|
||||||
|
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
|
import eventDemo.shared.ids.EventId
|
||||||
|
import kotlinx.datetime.Instant
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The basic interface for an Event
|
||||||
|
* @see eventDemo.libs.eventSource.eventStore.EventStream
|
||||||
|
*/
|
||||||
|
interface Event<ID : AggregateId> {
|
||||||
|
val eventId: EventId
|
||||||
|
val aggregateId: ID
|
||||||
|
val createdAt: Instant
|
||||||
|
val version: Int
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
package eventDemo.libs.eventSource.eventStore
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
|
|
||||||
|
interface EventStore<E : Event<ID>, ID : AggregateId> {
|
||||||
|
fun getStream(aggregateId: ID): EventStream<E, ID>
|
||||||
|
|
||||||
|
@Throws(VersionConflictException::class)
|
||||||
|
fun append(event: E) =
|
||||||
|
withLoggingContext("event" to event.toString()) {
|
||||||
|
getStream(event.aggregateId).append(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Throws(VersionConflictException::class)
|
||||||
|
fun append(events: Set<E>) =
|
||||||
|
events.forEach { append(it) }
|
||||||
|
}
|
||||||
+3
-1
@@ -1,5 +1,7 @@
|
|||||||
package eventDemo.libs.event
|
package eventDemo.libs.eventSource.eventStore
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.concurrent.ConcurrentMap
|
import java.util.concurrent.ConcurrentMap
|
||||||
|
|
||||||
+5
-2
@@ -1,12 +1,15 @@
|
|||||||
package eventDemo.libs.event
|
package eventDemo.libs.eventSource.eventStore
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
import javax.sql.DataSource
|
import javax.sql.DataSource
|
||||||
|
|
||||||
class EventStoreInPostgresql<E : Event<ID>, ID : AggregateId>(
|
class EventStoreInPostgresql<E : Event<ID>, ID : AggregateId>(
|
||||||
private val dataSource: DataSource,
|
private val dataSource: DataSource,
|
||||||
private val objectToString: (E) -> String,
|
private val objectToString: (E) -> String,
|
||||||
private val stringToObject: (String) -> E,
|
private val stringToObject: (String) -> E,
|
||||||
|
private val tableName: String,
|
||||||
) : EventStore<E, ID> {
|
) : EventStore<E, ID> {
|
||||||
override fun getStream(aggregateId: ID): EventStream<E, ID> =
|
override fun getStream(aggregateId: ID): EventStream<E, ID> =
|
||||||
EventStreamInPostgresql(aggregateId, dataSource, objectToString, stringToObject)
|
EventStreamInPostgresql(aggregateId, dataSource, objectToString, stringToObject, tableName)
|
||||||
}
|
}
|
||||||
+13
-11
@@ -1,6 +1,7 @@
|
|||||||
package eventDemo.libs.event
|
package eventDemo.libs.eventSource.eventStore
|
||||||
|
|
||||||
import eventDemo.libs.event.projection.Projection
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
import io.github.oshai.kotlinlogging.withLoggingContext
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -10,13 +11,14 @@ interface EventStream<E : Event<ID>, ID : AggregateId> {
|
|||||||
val aggregateId: ID
|
val aggregateId: ID
|
||||||
|
|
||||||
/** Publishes a single event to the event stream */
|
/** Publishes a single event to the event stream */
|
||||||
fun publish(event: E)
|
@Throws(VersionConflictException::class)
|
||||||
|
fun append(event: E)
|
||||||
|
|
||||||
/** Publishes multiple events to the event stream */
|
/** Publishes multiple events to the event stream */
|
||||||
fun publish(vararg events: E) {
|
fun append(vararg events: E) {
|
||||||
events.forEach {
|
events.forEach {
|
||||||
withLoggingContext("event" to it.toString()) {
|
withLoggingContext("event" to it.toString()) {
|
||||||
publish(it)
|
append(it)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -29,12 +31,12 @@ interface EventStream<E : Event<ID>, ID : AggregateId> {
|
|||||||
|
|
||||||
fun readVersionBetween(version: IntRange): Set<E>
|
fun readVersionBetween(version: IntRange): Set<E>
|
||||||
|
|
||||||
fun <P : Projection<*>> readVersionBetween(
|
|
||||||
projection: P?,
|
|
||||||
event: E,
|
|
||||||
): Set<E> =
|
|
||||||
readVersionBetween(((projection?.lastEventVersion ?: 0) + 1)..event.version)
|
|
||||||
|
|
||||||
fun getByVersion(version: Int): E? =
|
fun getByVersion(version: Int): E? =
|
||||||
readVersionBetween(version..version).firstOrNull()
|
readVersionBetween(version..version).firstOrNull()
|
||||||
|
|
||||||
|
fun exist(): Boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
|
class VersionConflictException(
|
||||||
|
event: Event<*>,
|
||||||
|
) : RuntimeException("Version conflict: ${event.version}")
|
||||||
+7
-2
@@ -1,5 +1,7 @@
|
|||||||
package eventDemo.libs.event
|
package eventDemo.libs.eventSource.eventStore
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||||
import java.util.Queue
|
import java.util.Queue
|
||||||
import java.util.concurrent.ConcurrentLinkedQueue
|
import java.util.concurrent.ConcurrentLinkedQueue
|
||||||
@@ -15,7 +17,7 @@ class EventStreamInMemory<E : Event<ID>, ID : AggregateId>(
|
|||||||
private val logger = KotlinLogging.logger {}
|
private val logger = KotlinLogging.logger {}
|
||||||
private val events: Queue<E> = ConcurrentLinkedQueue()
|
private val events: Queue<E> = ConcurrentLinkedQueue()
|
||||||
|
|
||||||
override fun publish(event: E) {
|
override fun append(event: E) {
|
||||||
if (event.aggregateId != aggregateId) {
|
if (event.aggregateId != aggregateId) {
|
||||||
throw EventStreamPublishException(
|
throw EventStreamPublishException(
|
||||||
"You cannot publish this event in this stream because it has a different aggregateId!",
|
"You cannot publish this event in this stream because it has a different aggregateId!",
|
||||||
@@ -34,4 +36,7 @@ class EventStreamInMemory<E : Event<ID>, ID : AggregateId>(
|
|||||||
events
|
events
|
||||||
.filter { version.contains(it.version) }
|
.filter { version.contains(it.version) }
|
||||||
.toSet()
|
.toSet()
|
||||||
|
|
||||||
|
override fun exist(): Boolean =
|
||||||
|
events.isNotEmpty()
|
||||||
}
|
}
|
||||||
+63
-26
@@ -1,8 +1,13 @@
|
|||||||
package eventDemo.libs.event
|
package eventDemo.libs.eventSource.eventStore
|
||||||
|
|
||||||
|
import eventDemo.libs.eventSource.Event
|
||||||
|
import eventDemo.shared.ids.AggregateId
|
||||||
import io.github.oshai.kotlinlogging.KotlinLogging
|
import io.github.oshai.kotlinlogging.KotlinLogging
|
||||||
|
import io.github.oshai.kotlinlogging.withLoggingContext
|
||||||
import org.postgresql.util.PGobject
|
import org.postgresql.util.PGobject
|
||||||
|
import org.postgresql.util.PSQLException
|
||||||
import javax.sql.DataSource
|
import javax.sql.DataSource
|
||||||
|
import kotlin.uuid.toJavaUuid
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An In-Memory implementation of an event stream.
|
* An In-Memory implementation of an event stream.
|
||||||
@@ -14,31 +19,44 @@ class EventStreamInPostgresql<E : Event<ID>, ID : AggregateId>(
|
|||||||
private val dataSource: DataSource,
|
private val dataSource: DataSource,
|
||||||
private val objectToString: (E) -> String,
|
private val objectToString: (E) -> String,
|
||||||
private val stringToObject: (String) -> E,
|
private val stringToObject: (String) -> E,
|
||||||
|
private val tableName: String,
|
||||||
) : EventStream<E, ID> {
|
) : EventStream<E, ID> {
|
||||||
private val logger = KotlinLogging.logger {}
|
private val logger = KotlinLogging.logger {}
|
||||||
|
|
||||||
override fun publish(event: E) {
|
override fun append(event: E) {
|
||||||
if (event.aggregateId != aggregateId) {
|
withLoggingContext("event" to event.toString()) {
|
||||||
throw EventStreamPublishException(
|
if (event.aggregateId != aggregateId) {
|
||||||
"You cannot publish this event in this stream because it has a different aggregateId!",
|
throw EventStreamPublishException(
|
||||||
)
|
"You cannot publish this event in this stream because it has a different aggregateId!",
|
||||||
}
|
)
|
||||||
dataSource.connection.use { connection ->
|
}
|
||||||
connection
|
try {
|
||||||
.prepareStatement(
|
dataSource.connection.use { connection ->
|
||||||
"""
|
connection
|
||||||
insert into event_stream(id, aggregate_id, version, data)
|
.prepareStatement(
|
||||||
values (?, ?, ?, ?)
|
"""
|
||||||
""".trimIndent(),
|
insert into $tableName (id, aggregate_id, version, data)
|
||||||
).use {
|
values (?, ?, ?, ?)
|
||||||
it.setObject(1, event.eventId)
|
on conflict (id) do nothing
|
||||||
it.setObject(2, event.aggregateId.id)
|
""".trimIndent(),
|
||||||
it.setInt(3, event.version)
|
).use {
|
||||||
it.setObject(4, PGJsonb(objectToString(event)))
|
it.setObject(1, event.eventId.id.toJavaUuid())
|
||||||
it.executeUpdate()
|
it.setObject(2, event.aggregateId.id.toJavaUuid())
|
||||||
|
it.setInt(3, event.version)
|
||||||
|
it.setObject(4, PGJsonb(objectToString(event)))
|
||||||
|
it.executeUpdate()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} catch (e: PSQLException) {
|
||||||
|
if (e.serverErrorMessage?.constraint == "game_event_stream_aggregate_id_version_key") {
|
||||||
|
logger.warn { "duplicate version" }
|
||||||
|
throw VersionConflictException(event)
|
||||||
|
} else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
logger.info { "Event appended" }
|
||||||
}
|
}
|
||||||
logger.info { "Event published" }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun readAll(): Set<E> =
|
override fun readAll(): Set<E> =
|
||||||
@@ -46,13 +64,13 @@ class EventStreamInPostgresql<E : Event<ID>, ID : AggregateId>(
|
|||||||
connection
|
connection
|
||||||
.prepareStatement(
|
.prepareStatement(
|
||||||
"""
|
"""
|
||||||
select data
|
select data
|
||||||
from event_stream
|
from $tableName
|
||||||
where aggregate_id = ?
|
where aggregate_id = ?
|
||||||
order by version asc
|
order by version asc
|
||||||
""".trimIndent(),
|
""".trimIndent(),
|
||||||
).use {
|
).use {
|
||||||
it.setObject(1, aggregateId.id)
|
it.setObject(1, aggregateId.id.toJavaUuid())
|
||||||
it.executeQuery().use { resultSet ->
|
it.executeQuery().use { resultSet ->
|
||||||
buildSet {
|
buildSet {
|
||||||
while (resultSet.next()) {
|
while (resultSet.next()) {
|
||||||
@@ -66,13 +84,32 @@ class EventStreamInPostgresql<E : Event<ID>, ID : AggregateId>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun exist(): Boolean =
|
||||||
|
dataSource.connection.use { connection ->
|
||||||
|
connection
|
||||||
|
.prepareStatement(
|
||||||
|
"""
|
||||||
|
select 1
|
||||||
|
from $tableName
|
||||||
|
where aggregate_id = ?
|
||||||
|
limit 1
|
||||||
|
order by version asc
|
||||||
|
""".trimIndent(),
|
||||||
|
).use {
|
||||||
|
it.setObject(1, aggregateId.id.toJavaUuid())
|
||||||
|
it.executeQuery().use { resultSet ->
|
||||||
|
resultSet.next()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun readVersionBetween(version: IntRange): Set<E> =
|
override fun readVersionBetween(version: IntRange): Set<E> =
|
||||||
dataSource.connection.use { connection ->
|
dataSource.connection.use { connection ->
|
||||||
connection
|
connection
|
||||||
.prepareStatement(
|
.prepareStatement(
|
||||||
"""
|
"""
|
||||||
select data
|
select data
|
||||||
from event_stream
|
from $tableName
|
||||||
where version between ? and ?
|
where version between ? and ?
|
||||||
and aggregate_id = ?
|
and aggregate_id = ?
|
||||||
order by version asc
|
order by version asc
|
||||||
@@ -80,7 +117,7 @@ class EventStreamInPostgresql<E : Event<ID>, ID : AggregateId>(
|
|||||||
).use { stmt ->
|
).use { stmt ->
|
||||||
stmt.setInt(1, version.first)
|
stmt.setInt(1, version.first)
|
||||||
stmt.setInt(2, version.last)
|
stmt.setInt(2, version.last)
|
||||||
stmt.setObject(3, aggregateId.id)
|
stmt.setObject(3, aggregateId.id.toJavaUuid())
|
||||||
stmt.executeQuery().use { resultSet ->
|
stmt.executeQuery().use { resultSet ->
|
||||||
buildSet {
|
buildSet {
|
||||||
while (resultSet.next()) {
|
while (resultSet.next()) {
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user