From a4d807e96488a274c44d6bfe4196a1cfbb7a7ca9 Mon Sep 17 00:00:00 2001 From: Matthew Duffin Date: Sun, 9 Jun 2024 17:18:06 +0100 Subject: [PATCH] add lambda function (#8) * add lambda function * refactoring * gitignore --- .gitignore | 3 + pom.xml | 3 +- risk-lambda-sam/README.md | 127 ++++++++++++++++++ risk-lambda-sam/events/event.json | 63 +++++++++ risk-lambda-sam/samconfig.toml | 31 +++++ risk-lambda-sam/template.yaml | 65 +++++++++ risk-lambda/pom.xml | 122 +++++++++++++++++ .../kotlin/net/mjduffin/risk/lambda/App.kt | 57 ++++++++ .../net/mjduffin/risk/lib/GameContainer.kt | 14 ++ .../net/mjduffin/risk/lib}/ViewModel.kt | 2 +- .../risk/web/controller/LocalGameContainer.kt | 121 +++++++++++++++++ .../risk/web/controller/RestController.kt | 118 +--------------- .../risk/web/service/TerritoryService.kt | 1 + 13 files changed, 610 insertions(+), 117 deletions(-) create mode 100644 risk-lambda-sam/README.md create mode 100644 risk-lambda-sam/events/event.json create mode 100644 risk-lambda-sam/samconfig.toml create mode 100644 risk-lambda-sam/template.yaml create mode 100644 risk-lambda/pom.xml create mode 100644 risk-lambda/src/main/kotlin/net/mjduffin/risk/lambda/App.kt create mode 100644 risk-lib/src/main/kotlin/net/mjduffin/risk/lib/GameContainer.kt rename {risk-web/src/main/kotlin/net/mjduffin/risk/web/service => risk-lib/src/main/kotlin/net/mjduffin/risk/lib}/ViewModel.kt (96%) create mode 100644 risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/LocalGameContainer.kt diff --git a/.gitignore b/.gitignore index 9d6ebd2..f6b5bed 100644 --- a/.gitignore +++ b/.gitignore @@ -71,4 +71,7 @@ fabric.properties .idea/caches/build_file_checksums.ser .idea/ +#AWS +risk-lambda-sam/.aws-sam/ + target diff --git a/pom.xml b/pom.xml index 04b7477..1596d98 100644 --- a/pom.xml +++ b/pom.xml @@ -7,7 +7,8 @@ risk-lib risk-cli risk-web - + risk-lambda + org.springframework.boot spring-boot-starter-parent diff --git a/risk-lambda-sam/README.md b/risk-lambda-sam/README.md new file mode 100644 index 0000000..4b453b5 --- /dev/null +++ b/risk-lambda-sam/README.md @@ -0,0 +1,127 @@ +# risk-lambda-sam + +This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders. + +- HelloWorldFunction/src/main - Code for the application's Lambda function. +- events - Invocation events that you can use to invoke the function. +- HelloWorldFunction/src/test - Unit tests for the application code. +- template.yaml - A template that defines the application's AWS resources. + +The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code. + +If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit. +The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started. + +* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html) +* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html) +* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html) + +## Deploy the sample application + +The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API. + +To use the SAM CLI, you need the following tools. + +* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html) +* java21 - [Install the Java 21](https://docs.aws.amazon.com/corretto/latest/corretto-21-ug/downloads-list.html) +* Maven - [Install Maven](https://maven.apache.org/install.html) +* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community) + +To build and deploy your application for the first time, run the following in your shell: + +```bash +sam build +sam deploy --guided +``` + +The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts: + +* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name. +* **AWS Region**: The AWS region you want to deploy your app to. +* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes. +* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command. +* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application. + +You can find your API Gateway Endpoint URL in the output values displayed after deployment. + +## Use the SAM CLI to build and test locally + +Build your application with the `sam build` command. + +```bash +risk-lambda-sam$ sam build +``` + +The SAM CLI installs dependencies defined in `HelloWorldFunction/pom.xml`, creates a deployment package, and saves it in the `.aws-sam/build` folder. + +Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project. + +Run functions locally and invoke them with the `sam local invoke` command. + +```bash +risk-lambda-sam$ sam local invoke HelloWorldFunction --event events/event.json +``` + +The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000. + +```bash +risk-lambda-sam$ sam local start-api +risk-lambda-sam$ curl http://localhost:3000/ +``` + +The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path. + +```yaml + Events: + HelloWorld: + Type: Api + Properties: + Path: /hello + Method: get +``` + +## Add a resource to your application +The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types. + +## Fetch, tail, and filter Lambda function logs + +To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug. + +`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM. + +```bash +risk-lambda-sam$ sam logs -n HelloWorldFunction --stack-name risk-lambda-sam --tail +``` + +You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html). + +## Unit tests + +Tests are defined in the `HelloWorldFunction/src/test` folder in this project. + +```bash +risk-lambda-sam$ cd HelloWorldFunction +HelloWorldFunction$ mvn test +``` + +## Cleanup + +To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following: + +```bash +sam delete --stack-name risk-lambda-sam +``` + +## Resources + +See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts. + +Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/) diff --git a/risk-lambda-sam/events/event.json b/risk-lambda-sam/events/event.json new file mode 100644 index 0000000..3822fad --- /dev/null +++ b/risk-lambda-sam/events/event.json @@ -0,0 +1,63 @@ +{ + "body": "{\"message\": \"hello world\"}", + "resource": "/{proxy+}", + "path": "/path/to/resource", + "httpMethod": "POST", + "isBase64Encoded": false, + "queryStringParameters": { + "foo": "bar" + }, + "pathParameters": { + "proxy": "/path/to/resource" + }, + "stageVariables": { + "baz": "qux" + }, + "headers": { + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", + "Accept-Encoding": "gzip, deflate, sdch", + "Accept-Language": "en-US,en;q=0.8", + "Cache-Control": "max-age=0", + "CloudFront-Forwarded-Proto": "https", + "CloudFront-Is-Desktop-Viewer": "true", + "CloudFront-Is-Mobile-Viewer": "false", + "CloudFront-Is-SmartTV-Viewer": "false", + "CloudFront-Is-Tablet-Viewer": "false", + "CloudFront-Viewer-Country": "US", + "Host": "1234567890.execute-api.us-east-1.amazonaws.com", + "Upgrade-Insecure-Requests": "1", + "User-Agent": "Custom User Agent String", + "Via": "1.1 08f323deadbeefa7af34d5feb414ce27.cloudfront.net (CloudFront)", + "X-Amz-Cf-Id": "cDehVQoZnx43VYQb9j2-nvCh-9z396Uhbp027Y2JvkCPNLmGJHqlaA==", + "X-Forwarded-For": "127.0.0.1, 127.0.0.2", + "X-Forwarded-Port": "443", + "X-Forwarded-Proto": "https" + }, + "requestContext": { + "accountId": "123456789012", + "resourceId": "123456", + "stage": "prod", + "requestId": "c6af9ac6-7b61-11e6-9a41-93e8deadbeef", + "requestTime": "09/Apr/2015:12:34:56 +0000", + "requestTimeEpoch": 1428582896000, + "identity": { + "cognitoIdentityPoolId": null, + "accountId": null, + "cognitoIdentityId": null, + "caller": null, + "accessKey": null, + "sourceIp": "127.0.0.1", + "cognitoAuthenticationType": null, + "cognitoAuthenticationProvider": null, + "userArn": null, + "userAgent": "Custom User Agent String", + "user": null + }, + "path": "/prod/path/to/resource", + "resourcePath": "/{proxy+}", + "httpMethod": "POST", + "apiId": "1234567890", + "protocol": "HTTP/1.1" + } + } + \ No newline at end of file diff --git a/risk-lambda-sam/samconfig.toml b/risk-lambda-sam/samconfig.toml new file mode 100644 index 0000000..b554469 --- /dev/null +++ b/risk-lambda-sam/samconfig.toml @@ -0,0 +1,31 @@ +# More information about the configuration file can be found here: +# https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html +version = 0.1 + +[default] +[default.global.parameters] +stack_name = "risk-lambda-sam" + +[default.build.parameters] +cached = true +parallel = true + +[default.validate.parameters] +lint = true + +[default.deploy.parameters] +capabilities = "CAPABILITY_IAM" +confirm_changeset = true +resolve_s3 = true + +[default.package.parameters] +resolve_s3 = true + +[default.sync.parameters] +watch = true + +[default.local_start_api.parameters] +warm_containers = "EAGER" + +[default.local_start_lambda.parameters] +warm_containers = "EAGER" diff --git a/risk-lambda-sam/template.yaml b/risk-lambda-sam/template.yaml new file mode 100644 index 0000000..a3b55ee --- /dev/null +++ b/risk-lambda-sam/template.yaml @@ -0,0 +1,65 @@ +AWSTemplateFormatVersion: '2010-09-09' +Transform: AWS::Serverless-2016-10-31 +Description: > + risk-lambda-sam + + Sample SAM Template for risk-lambda-sam + +# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst +Globals: + Function: + Timeout: 20 + MemorySize: 512 + + Tracing: Active + # You can add LoggingConfig parameters such as the Logformat, Log Group, and SystemLogLevel or ApplicationLogLevel. Learn more here https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-loggingconfig. + LoggingConfig: + LogFormat: JSON + Api: + TracingEnabled: true +Resources: + RiskFunction: + Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction + Properties: + CodeUri: ../risk-lambda + Handler: net.mjduffin.risk.lambda.App::handleRequest + Runtime: java21 + Architectures: + - x86_64 + MemorySize: 512 + Environment: # More info about Env Vars: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#environment-object + Variables: + PARAM1: VALUE + Events: + Risk: + Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api + Properties: + Path: /hello + Method: get + + ApplicationResourceGroup: + Type: AWS::ResourceGroups::Group + Properties: + Name: + Fn::Sub: ApplicationInsights-SAM-${AWS::StackName} + ResourceQuery: + Type: CLOUDFORMATION_STACK_1_0 + ApplicationInsightsMonitoring: + Type: AWS::ApplicationInsights::Application + Properties: + ResourceGroupName: + Ref: ApplicationResourceGroup + AutoConfigurationEnabled: 'true' +Outputs: + # ServerlessRestApi is an implicit API created out of Events key under Serverless::Function + # Find out more about other implicit resources you can reference within SAM + # https://github.com/awslabs/serverless-application-model/blob/master/docs/internals/generated_resources.rst#api + RiskApi: + Description: API Gateway endpoint URL for Prod stage for Risk function + Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/risk/" + RiskFunction: + Description: Risk Lambda Function ARN + Value: !GetAtt RiskFunction.Arn + RiskLambdaFunctionIamRole: + Description: Implicit IAM Role created for Risk function + Value: !GetAtt RiskFunctionRole.Arn diff --git a/risk-lambda/pom.xml b/risk-lambda/pom.xml new file mode 100644 index 0000000..dc50bb2 --- /dev/null +++ b/risk-lambda/pom.xml @@ -0,0 +1,122 @@ + + + 4.0.0 + + net.mjduffin + risk + 0.0.1-SNAPSHOT + + + risk-lambda + + + UTF-8 + official + 1.8 + + + + + mavenCentral + https://repo1.maven.org/maven2/ + + + + + src/main/kotlin + src/test/kotlin + + + org.jetbrains.kotlin + kotlin-maven-plugin + 1.9.22 + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + maven-surefire-plugin + 2.22.2 + + + maven-failsafe-plugin + 2.22.2 + + + + + + + + + + + org.apache.maven.plugins + maven-shade-plugin + 3.2.4 + + + + + package + + shade + + + + + + + + + + com.amazonaws + aws-lambda-java-core + 1.2.2 + + + com.amazonaws + aws-lambda-java-events + 3.11.0 + + + + org.jetbrains.kotlin + kotlin-test-junit5 + 1.9.22 + test + + + org.junit.jupiter + junit-jupiter-engine + 5.10.0 + test + + + org.jetbrains.kotlin + kotlin-stdlib + 1.9.22 + + + net.mjduffin + risk-web + 0.0.1-SNAPSHOT + compile + + + \ No newline at end of file diff --git a/risk-lambda/src/main/kotlin/net/mjduffin/risk/lambda/App.kt b/risk-lambda/src/main/kotlin/net/mjduffin/risk/lambda/App.kt new file mode 100644 index 0000000..e531bcf --- /dev/null +++ b/risk-lambda/src/main/kotlin/net/mjduffin/risk/lambda/App.kt @@ -0,0 +1,57 @@ +package net.mjduffin.risk.lambda + +import com.amazonaws.services.lambda.runtime.Context +import com.amazonaws.services.lambda.runtime.RequestHandler +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent +import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyResponseEvent +import net.mjduffin.risk.lib.usecase.GameFactory +import net.mjduffin.risk.web.controller.RestController +import net.mjduffin.risk.web.service.TerritoryService +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStreamReader +import java.net.URL +import java.util.stream.Collectors + +/** + * Handler for requests to Lambda function. + */ +class App : RequestHandler { + + // map of game ID to game container + + private val restController: RestController = RestController(TerritoryService(), GameFactory()); + + override fun handleRequest(input: APIGatewayProxyRequestEvent, context: Context?): APIGatewayProxyResponseEvent { + val headers: MutableMap = HashMap() + headers["Content-Type"] = "application/json" + headers["X-Custom-Header"] = "application/json" + + val response: APIGatewayProxyResponseEvent = APIGatewayProxyResponseEvent() + .withHeaders(headers) + try { + val pageContents = this.getPageContents("https://checkip.amazonaws.com") + val output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents) + + return response + .withStatusCode(200) + .withBody(output) + } catch (e: IOException) { + return response + .withBody("{}") + .withStatusCode(500) + } + } + + @Throws(IOException::class) + private fun getPageContents(address: String): String { + val url = URL(address) + BufferedReader(InputStreamReader(url.openStream())).use { br -> + return br.lines().collect( + Collectors.joining( + System.lineSeparator() + ) + ) + } + } +} diff --git a/risk-lib/src/main/kotlin/net/mjduffin/risk/lib/GameContainer.kt b/risk-lib/src/main/kotlin/net/mjduffin/risk/lib/GameContainer.kt new file mode 100644 index 0000000..c8ccac4 --- /dev/null +++ b/risk-lib/src/main/kotlin/net/mjduffin/risk/lib/GameContainer.kt @@ -0,0 +1,14 @@ +package net.mjduffin.risk.lib + +import net.mjduffin.risk.lib.usecase.GameManager + +interface GameContainer { + fun getGameManager() : GameManager + + fun waitThreeSeconds() + + fun increment() + fun addPlayer(name: String): Player + fun startGame() + fun toViewModel(): ViewModel +} \ No newline at end of file diff --git a/risk-web/src/main/kotlin/net/mjduffin/risk/web/service/ViewModel.kt b/risk-lib/src/main/kotlin/net/mjduffin/risk/lib/ViewModel.kt similarity index 96% rename from risk-web/src/main/kotlin/net/mjduffin/risk/web/service/ViewModel.kt rename to risk-lib/src/main/kotlin/net/mjduffin/risk/lib/ViewModel.kt index c9752a3..f14c9e0 100644 --- a/risk-web/src/main/kotlin/net/mjduffin/risk/web/service/ViewModel.kt +++ b/risk-lib/src/main/kotlin/net/mjduffin/risk/lib/ViewModel.kt @@ -1,4 +1,4 @@ -package net.mjduffin.risk.web.service +package net.mjduffin.risk.lib enum class Screen { diff --git a/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/LocalGameContainer.kt b/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/LocalGameContainer.kt new file mode 100644 index 0000000..9fb58eb --- /dev/null +++ b/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/LocalGameContainer.kt @@ -0,0 +1,121 @@ +package net.mjduffin.risk.web.controller + +import net.mjduffin.risk.lib.* +import net.mjduffin.risk.lib.usecase.GameFactory +import net.mjduffin.risk.lib.usecase.GameManager +import net.mjduffin.risk.web.service.TerritoryService +import java.util.concurrent.TimeUnit +import java.util.concurrent.locks.ReentrantLock +import kotlin.concurrent.withLock + +/** + * Holds all information relevant to a single game. + */ +class LocalGameContainer( + private val gameFactory: GameFactory, + private val territoryService: TerritoryService +) : GameContainer { + + private var manager: GameManager? = null + private val players: MutableList = mutableListOf() + + private val lock = ReentrantLock() + private val condition = lock.newCondition() + + // used by clients to determine if they have an up-to-date version of the game state + private var actionCount = 0 + private var playerCount = 0 + + override fun getGameManager(): GameManager { + if (!hasStarted()) { + throw IllegalArgumentException("Game not started") + } else { + return manager!! + } + } + + override fun waitThreeSeconds() { + lock.withLock { condition.await(3, TimeUnit.SECONDS) } + } + + /** + * Increments the counter that tracks actions taken in the game. + */ + override fun increment() { + actionCount++ + lock.withLock { condition.signalAll() } + } + + override fun addPlayer(name: String): Player { + val existing = findPlayer(name) + if (existing != null) { + return existing + } + val newPlayer = Player(name, colors[playerCount++]); + players.add(newPlayer) + increment() + return newPlayer + } + + override fun startGame() { + manager = gameFactory.mainGame(players.map { it.name }.toList()) + increment() + } + + /** + * Get the view-model for the game. + */ + override fun toViewModel(): ViewModel { + return if (hasStarted()) { + ViewModel(Screen.GAME, actionCount, getGameViewModel()) + } else { + val lobby = LobbyVM(players) + ViewModel(Screen.LOBBY, actionCount, lobby) + } + } + + private fun hasStarted(): Boolean = manager != null + + /** + * Get the view-model for the game screen. + */ + private fun getGameViewModel(): GameVM { + if (!hasStarted()) { + return error("Game not started") + } + + val gameState = manager?.getGameState()!! + + val territories = gameState.territories.indices.map { + toTerritoryVM( + gameState.territories[it], + gameState.occupyingPlayers[it], + gameState.units[it], + ) + } + var modal: ModalVM? = null + if (gameState.phase.equals("MOVE")) { + modal = ModalVM("Move from ${gameState.lastAttackingTerritory} to ${gameState.lastDefendingTerritory}", gameState.lastAttackingUnitCount, gameState.maxToMove!!) + } + + return GameVM(gameState.currentPlayer, gameState.phase, gameState.unitsToPlace, territories, modal) + } + + private fun error(errorMessage: String): GameVM { + return GameVM("", "", 0, listOf(), null, errorMessage) + } + + private fun findPlayer(playerName: String): Player? { + return players.find { it.name == playerName } + } + + private fun getPlayer(playerName: String): Player { + return findPlayer(playerName) ?: throw IllegalArgumentException("Missing color for $playerName") + } + + private fun toTerritoryVM(territory: String, playerName: String, units: Int): TerritoryVM { + val point = territoryService.getPosition(territory) + val player = getPlayer(playerName) + return TerritoryVM(territory, point.first, point.second, player, units) + } +} \ No newline at end of file diff --git a/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/RestController.kt b/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/RestController.kt index 6b84585..ec363f7 100644 --- a/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/RestController.kt +++ b/risk-web/src/main/kotlin/net/mjduffin/risk/web/controller/RestController.kt @@ -1,16 +1,14 @@ package net.mjduffin.risk.web.controller +import net.mjduffin.risk.lib.* import net.mjduffin.risk.lib.usecase.GameFactory import net.mjduffin.risk.lib.usecase.GameManager -import net.mjduffin.risk.web.service.* +import net.mjduffin.risk.web.service.TerritoryService import org.apache.commons.lang3.RandomStringUtils import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.web.bind.annotation.* import org.springframework.web.bind.annotation.RestController -import java.util.concurrent.TimeUnit -import java.util.concurrent.locks.ReentrantLock -import kotlin.concurrent.withLock val colors = listOf("red", "blue", "green", "violet", "orange", "magenta", "yellow") @@ -111,7 +109,7 @@ class RestController(private val territoryService: TerritoryService, private val log.info("Start new game") val id = RandomStringUtils.random(6, true, false)!!.uppercase() - containers[id] = GameContainer(gameFactory, territoryService) + containers[id] = LocalGameContainer(gameFactory, territoryService) return id } @@ -150,113 +148,3 @@ class RestController(private val territoryService: TerritoryService, private val fun getViewModel(id: String): ViewModel = containers[id]?.toViewModel() ?: ViewModel(Screen.ERROR, 0, "Container not found: $id") } - - -/** - * Holds all information relevant to a single game. - */ -class GameContainer(private val gameFactory: GameFactory, private val territoryService: TerritoryService) { - - private var manager: GameManager? = null - private val players: MutableList = mutableListOf() - - private val lock = ReentrantLock() - private val condition = lock.newCondition() - - // used by clients to determine if they have an up-to-date version of the game state - private var actionCount = 0 - private var playerCount = 0 - - fun getGameManager(): GameManager { - if (!hasStarted()) { - throw IllegalArgumentException("Game not started") - } else { - return manager!! - } - } - - fun waitThreeSeconds() { - lock.withLock { condition.await(3, TimeUnit.SECONDS) } - } - - /** - * Increments the counter that tracks actions taken in the game. - */ - fun increment() { - actionCount++ - lock.withLock { condition.signalAll() } - } - - fun addPlayer(name: String): Player { - val existing = findPlayer(name) - if (existing != null) { - return existing - } - val newPlayer = Player(name, colors[playerCount++]); - players.add(newPlayer) - increment() - return newPlayer - } - - fun startGame() { - manager = gameFactory.mainGame(players.map { it.name }.toList()) - increment() - } - - /** - * Get the view-model for the game. - */ - fun toViewModel(): ViewModel { - return if (hasStarted()) { - ViewModel(Screen.GAME, actionCount, getGameViewModel()) - } else { - val lobby = LobbyVM(players) - ViewModel(Screen.LOBBY, actionCount, lobby) - } - } - - private fun hasStarted(): Boolean = manager != null - - /** - * Get the view-model for the game screen. - */ - private fun getGameViewModel(): GameVM { - if (!hasStarted()) { - return error("Game not started") - } - - val gameState = manager?.getGameState()!! - - val territories = gameState.territories.indices.map { - toTerritoryVM( - gameState.territories[it], - gameState.occupyingPlayers[it], - gameState.units[it], - ) - } - var modal: ModalVM? = null - if (gameState.phase.equals("MOVE")) { - modal = ModalVM("Move from ${gameState.lastAttackingTerritory} to ${gameState.lastDefendingTerritory}", gameState.lastAttackingUnitCount, gameState.maxToMove!!) - } - - return GameVM(gameState.currentPlayer, gameState.phase, gameState.unitsToPlace, territories, modal) - } - - private fun error(errorMessage: String): GameVM { - return GameVM("", "", 0, listOf(), null, errorMessage) - } - - private fun findPlayer(playerName: String): Player? { - return players.find { it.name == playerName } - } - - private fun getPlayer(playerName: String): Player { - return findPlayer(playerName) ?: throw IllegalArgumentException("Missing color for $playerName") - } - - private fun toTerritoryVM(territory: String, playerName: String, units: Int): TerritoryVM { - val point = territoryService.getPosition(territory) - val player = getPlayer(playerName) - return TerritoryVM(territory, point.first, point.second, player, units) - } -} diff --git a/risk-web/src/main/kotlin/net/mjduffin/risk/web/service/TerritoryService.kt b/risk-web/src/main/kotlin/net/mjduffin/risk/web/service/TerritoryService.kt index 5dfc667..3d74e07 100644 --- a/risk-web/src/main/kotlin/net/mjduffin/risk/web/service/TerritoryService.kt +++ b/risk-web/src/main/kotlin/net/mjduffin/risk/web/service/TerritoryService.kt @@ -1,5 +1,6 @@ package net.mjduffin.risk.web.service +import net.mjduffin.risk.lib.GameVM import org.springframework.stereotype.Service @Service