diff --git a/compose.yaml b/compose.yaml index a2fc41955..47b4fe6c6 100644 --- a/compose.yaml +++ b/compose.yaml @@ -16,7 +16,7 @@ services: - "3306:3306" faf-db-migrations: - image: faforever/faf-db-migrations:v146 + image: faforever/faf-db-migrations:v148 command: migrate environment: FLYWAY_URL: jdbc:mysql://faf-db/faf?useSSL=false @@ -42,7 +42,7 @@ services: environment: MINIO_ROOT_USER: admin MINIO_ROOT_PASSWORD: banana123 - MINIO_DEFAULT_BUCKETS: user-uploads + MINIO_DEFAULT_BUCKETS: user-uploads,desync-reports MINIO_SCHEME: http healthcheck: test: [ "CMD", "curl", "-f", "http://localhost:9000/minio/health/ready" ] diff --git a/src/inttest/java/com/faforever/api/config/MainDbTestContainers.java b/src/inttest/java/com/faforever/api/config/MainDbTestContainers.java index 9188d15aa..23e18f0d9 100644 --- a/src/inttest/java/com/faforever/api/config/MainDbTestContainers.java +++ b/src/inttest/java/com/faforever/api/config/MainDbTestContainers.java @@ -23,7 +23,7 @@ @Configuration public class MainDbTestContainers { private static final MariaDBContainer fafDBContainer = new MariaDBContainer<>("mariadb:11.7"); - private static final GenericContainer flywayMigrationsContainer = new GenericContainer<>("faforever/faf-db-migrations:v144"); + private static final GenericContainer flywayMigrationsContainer = new GenericContainer<>("faforever/faf-db-migrations:v148"); private static final Network sharedNetwork = Network.newNetwork(); @Bean diff --git a/src/inttest/resources/config/application.yml b/src/inttest/resources/config/application.yml index 7645f3291..de98bc473 100644 --- a/src/inttest/resources/config/application.yml +++ b/src/inttest/resources/config/application.yml @@ -102,6 +102,12 @@ faf-api: endpoint: http://minio region: auto user-upload-bucket: user-uploads + desync-report: + access-key: admin + secret-key: banana123 + endpoint: http://minio + region: auto + bucket: desync-reports logging: level: diff --git a/src/main/java/com/faforever/api/config/FafApiProperties.java b/src/main/java/com/faforever/api/config/FafApiProperties.java index 22ad0ab44..e2713d4df 100644 --- a/src/main/java/com/faforever/api/config/FafApiProperties.java +++ b/src/main/java/com/faforever/api/config/FafApiProperties.java @@ -3,6 +3,7 @@ import lombok.Data; import org.checkerframework.checker.index.qual.Positive; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.util.unit.DataSize; import java.nio.file.Path; import java.nio.file.Paths; @@ -44,6 +45,7 @@ public class FafApiProperties { private Monitoring monitoring = new Monitoring(); private Coturn coturn = new Coturn(); private S3 s3 = new S3(); + private DesyncReport desyncReport = new DesyncReport(); @Data public static class OAuth2 { @@ -304,4 +306,21 @@ public static class S3 { private String accessKey; private String secretKey; } + + @Data + public static class DesyncReport { + private String endpoint; + private String region; + private String bucket; + private String accessKey; + private String secretKey; + /** + * Upper limit for the size of a single desync report. + */ + private DataSize maxUploadSize = DataSize.ofMegabytes(10); + /** + * Object key of a report in the bucket, with the game id and the player id as arguments. + */ + private String reportFileNameFormat = "desync/%d/%d.zip"; + } } diff --git a/src/main/java/com/faforever/api/config/S3Config.java b/src/main/java/com/faforever/api/config/S3Config.java index e562ebe81..d22591c04 100644 --- a/src/main/java/com/faforever/api/config/S3Config.java +++ b/src/main/java/com/faforever/api/config/S3Config.java @@ -3,6 +3,7 @@ import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; import software.amazon.awssdk.regions.Region; @@ -19,6 +20,7 @@ public class S3Config { private final FafApiProperties properties; @Bean + @Primary public S3Client s3Client() { return S3Client.builder() .endpointOverride(URI.create(properties.getS3().getEndpoint())) @@ -46,4 +48,23 @@ public S3Presigner s3Presigner() { .build()) .build(); } + + /** + * Client for the dedicated desync report bucket, which has its own endpoint and credentials. + */ + @Bean + public S3Client desyncReportS3Client() { + FafApiProperties.DesyncReport desyncReport = properties.getDesyncReport(); + return S3Client.builder() + .endpointOverride(URI.create(desyncReport.getEndpoint())) + .region(Region.of(desyncReport.getRegion())) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(desyncReport.getAccessKey(), desyncReport.getSecretKey()) + )) + .serviceConfiguration(S3Configuration.builder() + .pathStyleAccessEnabled(true) + .chunkedEncodingEnabled(false) // R2 rejects the chunked signature of putObject with 403 + .build()) + .build(); + } } diff --git a/src/main/java/com/faforever/api/data/domain/GameDesync.java b/src/main/java/com/faforever/api/data/domain/GameDesync.java new file mode 100644 index 000000000..c35278f9f --- /dev/null +++ b/src/main/java/com/faforever/api/data/domain/GameDesync.java @@ -0,0 +1,102 @@ +package com.faforever.api.data.domain; + +import com.faforever.api.data.checks.Prefab; +import com.faforever.api.data.listeners.GameDesyncEnricher; +import com.yahoo.elide.annotation.ComputedAttribute; +import com.yahoo.elide.annotation.CreatePermission; +import com.yahoo.elide.annotation.DeletePermission; +import com.yahoo.elide.annotation.Include; +import com.yahoo.elide.annotation.UpdatePermission; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EntityListeners; +import jakarta.persistence.FetchType; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.GenerationType; +import jakarta.persistence.Id; +import jakarta.persistence.JoinColumn; +import jakarta.persistence.ManyToOne; +import jakarta.persistence.Table; +import jakarta.persistence.Transient; +import lombok.Setter; +import org.hibernate.annotations.Immutable; + +import java.time.OffsetDateTime; + +/** + * A player whose client reported a desync in a game via GPGNet. Written by the lobby server only; one row per game and + * player, recording the first report. + */ +@Entity +@Table(name = "game_desync") +@Include(name = "gameDesync") +@Immutable +@Setter +@EntityListeners(GameDesyncEnricher.class) +@CreatePermission(expression = Prefab.NONE) +@UpdatePermission(expression = Prefab.NONE) +@DeletePermission(expression = Prefab.NONE) +public class GameDesync { + + private int id; + private Game game; + private Player player; + private OffsetDateTime reportedAt; + private Integer gameTime; + private OffsetDateTime reportUploadedAt; + private String reportFileName; + + @Id + @Column(name = "id") + @GeneratedValue(strategy = GenerationType.IDENTITY) + public int getId() { + return id; + } + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "game_id") + public Game getGame() { + return game; + } + + /** + * The player whose client reported the desync. Every client that detects the mismatch reports it, so this is not the + * culprit. + */ + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "player_id") + public Player getPlayer() { + return player; + } + + @Column(name = "reported_at") + public OffsetDateTime getReportedAt() { + return reportedAt; + } + + /** + * Seconds since the game was launched, derived by the lobby server. Not a simulation tick. + */ + @Column(name = "game_time") + public Integer getGameTime() { + return gameTime; + } + + /** + * Time the player uploaded the desync report file through the API, null if there is none. + */ + @Column(name = "report_uploaded_at") + public OffsetDateTime getReportUploadedAt() { + return reportUploadedAt; + } + + /** + * Object key under which the report of this player is stored in the object storage, filled by the + * {@link GameDesyncEnricher}. Only points to an existing file if {@link #getReportUploadedAt()} is set. + */ + @Transient + @ComputedAttribute + public String getReportFileName() { + return reportFileName; + } +} diff --git a/src/main/java/com/faforever/api/data/listeners/GameDesyncEnricher.java b/src/main/java/com/faforever/api/data/listeners/GameDesyncEnricher.java new file mode 100644 index 000000000..783a28d5d --- /dev/null +++ b/src/main/java/com/faforever/api/data/listeners/GameDesyncEnricher.java @@ -0,0 +1,23 @@ +package com.faforever.api.data.listeners; + +import com.faforever.api.data.domain.GameDesync; +import com.faforever.api.desync.DesyncReportService; +import jakarta.inject.Inject; +import jakarta.persistence.PostLoad; +import org.springframework.stereotype.Component; + +@Component +public class GameDesyncEnricher { + + private static DesyncReportService desyncReportService; + + @Inject + public void init(DesyncReportService desyncReportService) { + GameDesyncEnricher.desyncReportService = desyncReportService; + } + + @PostLoad + public void enrich(GameDesync gameDesync) { + gameDesync.setReportFileName(desyncReportService.getReportFileName(gameDesync.getGame().getId(), gameDesync.getPlayer().getId())); + } +} diff --git a/src/main/java/com/faforever/api/desync/DesyncReportController.java b/src/main/java/com/faforever/api/desync/DesyncReportController.java new file mode 100644 index 000000000..4568c66f6 --- /dev/null +++ b/src/main/java/com/faforever/api/desync/DesyncReportController.java @@ -0,0 +1,42 @@ +package com.faforever.api.desync; + +import com.faforever.api.player.PlayerService; +import com.faforever.api.security.OAuthScope; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import lombok.RequiredArgsConstructor; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseStatus; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.multipart.MultipartFile; + +import java.io.IOException; + +@RestController +@RequestMapping(path = "/game/{gameId}/desync") +@RequiredArgsConstructor +public class DesyncReportController { + + private final PlayerService playerService; + private final DesyncReportService desyncReportService; + + @Operation(summary = "Upload the desync report (a zip file) of the authenticated player for a game", + description = "A repeated upload for the same game replaces the previous report.") + @ApiResponse(responseCode = "204", description = "Report stored") + @ApiResponse(responseCode = "403", description = "The player did not participate in this game") + @ApiResponse(responseCode = "422", description = "The file is empty or larger than the allowed size") + @PostMapping(path = "/report", consumes = "multipart/form-data") + @ResponseStatus(HttpStatus.NO_CONTENT) + @PreAuthorize("hasScope('" + OAuthScope._UPLOAD_DESYNC_REPORT + "')") + public void uploadReport(Authentication authentication, + @PathVariable("gameId") int gameId, + @RequestParam("file") MultipartFile file) throws IOException { + desyncReportService.storeReport(playerService.getPlayer(authentication).getId(), gameId, file); + } +} diff --git a/src/main/java/com/faforever/api/desync/DesyncReportService.java b/src/main/java/com/faforever/api/desync/DesyncReportService.java new file mode 100644 index 000000000..8d4f2d4ef --- /dev/null +++ b/src/main/java/com/faforever/api/desync/DesyncReportService.java @@ -0,0 +1,84 @@ +package com.faforever.api.desync; + +import com.faforever.api.config.FafApiProperties; +import com.faforever.api.config.FafApiProperties.DesyncReport; +import com.faforever.api.error.ApiException; +import com.faforever.api.error.Error; +import com.faforever.api.error.ErrorCode; +import com.faforever.api.game.GameDesyncRepository; +import com.faforever.api.game.GamePlayerStatsRepository; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.http.ContentStreamProvider; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; + +import java.io.IOException; +import java.io.UncheckedIOException; + +@Slf4j +@Service +public class DesyncReportService { + static final String CONTENT_TYPE = "application/zip"; + + private final DesyncReport properties; + private final GamePlayerStatsRepository gamePlayerStatsRepository; + private final GameDesyncRepository gameDesyncRepository; + private final S3Client s3Client; + + public DesyncReportService(FafApiProperties properties, + GamePlayerStatsRepository gamePlayerStatsRepository, + GameDesyncRepository gameDesyncRepository, + @Qualifier("desyncReportS3Client") S3Client s3Client) { + this.properties = properties.getDesyncReport(); + this.gamePlayerStatsRepository = gamePlayerStatsRepository; + this.gameDesyncRepository = gameDesyncRepository; + this.s3Client = s3Client; + } + + public String getReportFileName(int gameId, int playerId) { + return properties.getReportFileNameFormat().formatted(gameId, playerId); + } + + /** + * Stores the desync report of a player and marks it as uploaded. A repeated upload for the same game replaces the + * previous report. + */ + public void storeReport(int playerId, int gameId, MultipartFile report) throws IOException { + long maxSize = properties.getMaxUploadSize().toBytes(); + long size = report.getSize(); + if (size < 1 || size > maxSize) { + throw new ApiException(new Error(ErrorCode.DESYNC_REPORT_INVALID_SIZE, maxSize)); + } + + if (!gamePlayerStatsRepository.existsByGameIdAndPlayerId(gameId, playerId)) { + throw new AccessDeniedException("Player %d did not participate in game %d".formatted(playerId, gameId)); + } + + String key = getReportFileName(gameId, playerId); + log.info("Player {} uploads a desync report for game {} ({} bytes)", playerId, gameId, size); + + // the SDK reads the body more than once (checksum, then upload), so every read needs a fresh stream + ContentStreamProvider streamProvider = () -> { + try { + return report.getInputStream(); + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }; + + s3Client.putObject(PutObjectRequest.builder() + .bucket(properties.getBucket()) + .key(key) + .contentType(CONTENT_TYPE) + .contentLength(size) + .build(), RequestBody.fromContentProvider(streamProvider, size, CONTENT_TYPE)); + + // only after the file is stored, so the column can be relied on to filter for existing reports + gameDesyncRepository.markReportUploaded(gameId, playerId); + } +} diff --git a/src/main/java/com/faforever/api/error/ErrorCode.java b/src/main/java/com/faforever/api/error/ErrorCode.java index 34e1c8c32..df2eeb422 100644 --- a/src/main/java/com/faforever/api/error/ErrorCode.java +++ b/src/main/java/com/faforever/api/error/ErrorCode.java @@ -121,6 +121,7 @@ public enum ErrorCode { MAP_VERSION_INVALID_RANGE(211, "Invalid map version", "The map version must be a whole number in range {0, number} to {1, number}."), MOD_VERSION_INVALID_RANGE(212, "Invalid mod version", "The mod version must be a whole number in range {0, number} to {1, number}."), AVATAR_NOT_ASSIGNED(213, "Avatar not assigned", "Avatar ''{0}'' is not assigned to player ''{1}''."), + DESYNC_REPORT_INVALID_SIZE(214, "Invalid desync report size", "The size of a desync report must be between 1 and {0, number} bytes."), ; diff --git a/src/main/java/com/faforever/api/game/GameDesyncRepository.java b/src/main/java/com/faforever/api/game/GameDesyncRepository.java new file mode 100644 index 000000000..bbc63df45 --- /dev/null +++ b/src/main/java/com/faforever/api/game/GameDesyncRepository.java @@ -0,0 +1,25 @@ +package com.faforever.api.game; + +import com.faforever.api.data.domain.GameDesync; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Modifying; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.query.Param; +import org.springframework.transaction.annotation.Transactional; + +public interface GameDesyncRepository extends JpaRepository { + + /** + * Marks the desync report of a player as uploaded. The lobby server records desyncs reported via GPGNet in the same + * table, so the row is created if it does not exist yet. This is a single atomic statement, so it is safe against the + * lobby server inserting the row at the same time. + */ + @Transactional + @Modifying + @Query(value = """ + INSERT INTO game_desync (game_id, player_id, reported_at, report_uploaded_at) + VALUES (:gameId, :playerId, NOW(3), NOW(3)) + ON DUPLICATE KEY UPDATE report_uploaded_at = NOW(3) + """, nativeQuery = true) + void markReportUploaded(@Param("gameId") int gameId, @Param("playerId") int playerId); +} diff --git a/src/main/java/com/faforever/api/game/GamePlayerStatsRepository.java b/src/main/java/com/faforever/api/game/GamePlayerStatsRepository.java index 1c139dcb3..b9ec9dbfc 100644 --- a/src/main/java/com/faforever/api/game/GamePlayerStatsRepository.java +++ b/src/main/java/com/faforever/api/game/GamePlayerStatsRepository.java @@ -7,4 +7,6 @@ public interface GamePlayerStatsRepository extends JpaRepository { int countByPlayerAndGameValidity(Player player, Validity validity); + + boolean existsByGameIdAndPlayerId(int gameId, int playerId); } diff --git a/src/main/java/com/faforever/api/security/OAuthScope.java b/src/main/java/com/faforever/api/security/OAuthScope.java index a1afbb032..a8b6fa09c 100644 --- a/src/main/java/com/faforever/api/security/OAuthScope.java +++ b/src/main/java/com/faforever/api/security/OAuthScope.java @@ -11,6 +11,7 @@ public enum OAuthScope { WRITE_EVENTS(OAuthScope._WRITE_EVENTS, "Write events"), UPLOAD_MAP(OAuthScope._UPLOAD_MAP, "Upload maps"), UPLOAD_MOD(OAuthScope._UPLOAD_MOD, "Upload mods"), + UPLOAD_DESYNC_REPORT(OAuthScope._UPLOAD_DESYNC_REPORT, "Upload desync reports"), WRITE_ACCOUNT_DATA(OAuthScope._WRITE_ACCOUNT_DATA, "Edit account data"), EDIT_CLAN_DATA(OAuthScope._EDIT_CLAN_DATA, "Edit clan data"), VOTE(OAuthScope._VOTE, "Vote"), @@ -24,6 +25,7 @@ public enum OAuthScope { public static final String _WRITE_EVENTS = "write_events"; public static final String _UPLOAD_MAP = "upload_map"; public static final String _UPLOAD_MOD = "upload_mod"; + public static final String _UPLOAD_DESYNC_REPORT = "upload_desync_report"; public static final String _WRITE_ACCOUNT_DATA = "write_account_data"; public static final String _EDIT_CLAN_DATA = "edit_clan_data"; public static final String _VOTE = "vote"; diff --git a/src/main/resources/config/application.yml b/src/main/resources/config/application.yml index 23f715ae6..bc16f22c0 100644 --- a/src/main/resources/config/application.yml +++ b/src/main/resources/config/application.yml @@ -16,7 +16,7 @@ faf-api: hmac-secret: ${CLOUDFLARE_HMAC_SECRET} hmac-param: ${CLOUDFLARE_HMAC_PARAM:verify} database: - schema-version: ${DATABASE_SCHEMA_VERSION:140} + schema-version: ${DATABASE_SCHEMA_VERSION:148} deployment: forged-alliance-exe-path: ${FORGED_ALLIANCE_EXE_PATH:/content/legacy-featured-mod-files/updates_faf_files/ForgedAlliance.exe} repositories-directory: ${REPOSITORIES_DIRECTORY:/repositories} @@ -94,6 +94,14 @@ faf-api: endpoint: ${S3_ENDPOINT:http://minio} region: ${S3_REGION:auto} # auto is a Cloudflare value user-upload-bucket: ${S3_USER_UPLOAD_BUCKET:user-uploads} + desync-report: + access-key: ${DESYNC_REPORT_S3_ACCESS_KEY:admin} + secret-key: ${DESYNC_REPORT_S3_SECRET_KEY:banana123} + endpoint: ${DESYNC_REPORT_S3_ENDPOINT:http://minio} + region: ${DESYNC_REPORT_S3_REGION:auto} + bucket: ${DESYNC_REPORT_S3_BUCKET:desync-reports} + max-upload-size: ${DESYNC_REPORT_MAX_UPLOAD_SIZE:10MB} + report-file-name-format: ${DESYNC_REPORT_FILE_NAME_FORMAT:desync/%d/%d.zip} spring: application: diff --git a/src/test/java/com/faforever/api/data/listeners/GameDesyncEnricherTest.java b/src/test/java/com/faforever/api/data/listeners/GameDesyncEnricherTest.java new file mode 100644 index 000000000..8b22e7c2f --- /dev/null +++ b/src/test/java/com/faforever/api/data/listeners/GameDesyncEnricherTest.java @@ -0,0 +1,40 @@ +package com.faforever.api.data.listeners; + +import com.faforever.api.data.domain.Game; +import com.faforever.api.data.domain.GameDesync; +import com.faforever.api.data.domain.Player; +import com.faforever.api.desync.DesyncReportService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class GameDesyncEnricherTest { + + @Mock + private DesyncReportService desyncReportService; + + @Test + void enrichSetsReportFileName() { + Game game = new Game(); + game.setId(1234); + Player player = new Player(); + player.setId(42); + GameDesync gameDesync = new GameDesync(); + gameDesync.setGame(game); + gameDesync.setPlayer(player); + + when(desyncReportService.getReportFileName(1234, 42)).thenReturn("desync/1234/42.zip"); + GameDesyncEnricher enricher = new GameDesyncEnricher(); + enricher.init(desyncReportService); + + enricher.enrich(gameDesync); + + assertThat(gameDesync.getReportFileName(), is("desync/1234/42.zip")); + } +} diff --git a/src/test/java/com/faforever/api/desync/DesyncReportServiceTest.java b/src/test/java/com/faforever/api/desync/DesyncReportServiceTest.java new file mode 100644 index 000000000..b699fb531 --- /dev/null +++ b/src/test/java/com/faforever/api/desync/DesyncReportServiceTest.java @@ -0,0 +1,132 @@ +package com.faforever.api.desync; + +import com.faforever.api.config.FafApiProperties; +import com.faforever.api.error.ApiException; +import com.faforever.api.error.ErrorCode; +import com.faforever.api.game.GameDesyncRepository; +import com.faforever.api.game.GamePlayerStatsRepository; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockMultipartFile; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.util.unit.DataSize; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; + +import java.io.IOException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class DesyncReportServiceTest { + private static final int GAME_ID = 1234; + private static final int PLAYER_ID = 42; + + @Mock + private GamePlayerStatsRepository gamePlayerStatsRepository; + @Mock + private GameDesyncRepository gameDesyncRepository; + @Mock + private S3Client s3Client; + + private DesyncReportService instance; + + @BeforeEach + void setUp() { + FafApiProperties properties = new FafApiProperties(); + properties.getDesyncReport().setBucket("desync-reports"); + properties.getDesyncReport().setMaxUploadSize(DataSize.ofBytes(1000)); + + instance = new DesyncReportService(properties, gamePlayerStatsRepository, gameDesyncRepository, s3Client); + } + + private static MockMultipartFile report(int size) { + return new MockMultipartFile("file", "dump.zip", "application/zip", new byte[size]); + } + + @Test + void storeReportStoresFileThenMarksUploaded() throws IOException { + when(gamePlayerStatsRepository.existsByGameIdAndPlayerId(GAME_ID, PLAYER_ID)).thenReturn(true); + + instance.storeReport(PLAYER_ID, GAME_ID, report(500)); + + ArgumentCaptor request = ArgumentCaptor.forClass(PutObjectRequest.class); + InOrder inOrder = inOrder(s3Client, gameDesyncRepository); + inOrder.verify(s3Client).putObject(request.capture(), any(RequestBody.class)); + inOrder.verify(gameDesyncRepository).markReportUploaded(GAME_ID, PLAYER_ID); + + assertThat(request.getValue().bucket(), is("desync-reports")); + assertThat(request.getValue().key(), is("desync/1234/42.zip")); + assertThat(request.getValue().contentLength(), is(500L)); + assertThat(request.getValue().contentType(), is("application/zip")); + } + + @Test + void reportFileNameUsesConfiguredFormat() { + FafApiProperties properties = new FafApiProperties(); + properties.getDesyncReport().setReportFileNameFormat("dumps/%d-%d.zip"); + DesyncReportService custom = new DesyncReportService(properties, gamePlayerStatsRepository, gameDesyncRepository, s3Client); + + assertThat(custom.getReportFileName(1234, 42), is("dumps/1234-42.zip")); + assertThat(instance.getReportFileName(1234, 42), is("desync/1234/42.zip")); + } + + @Test + void storeReportAtMaxSize() throws IOException { + when(gamePlayerStatsRepository.existsByGameIdAndPlayerId(GAME_ID, PLAYER_ID)).thenReturn(true); + + instance.storeReport(PLAYER_ID, GAME_ID, report(1000)); + + verify(s3Client).putObject(any(PutObjectRequest.class), any(RequestBody.class)); + verify(gameDesyncRepository).markReportUploaded(GAME_ID, PLAYER_ID); + } + + @Test + void storeReportTooLarge() { + ApiException exception = assertThrows(ApiException.class, () -> instance.storeReport(PLAYER_ID, GAME_ID, report(1001))); + + assertThat(exception.getErrors()[0].getErrorCode(), is(ErrorCode.DESYNC_REPORT_INVALID_SIZE)); + verifyNoInteractions(gamePlayerStatsRepository, s3Client, gameDesyncRepository); + } + + @Test + void storeReportEmpty() { + ApiException exception = assertThrows(ApiException.class, () -> instance.storeReport(PLAYER_ID, GAME_ID, report(0))); + + assertThat(exception.getErrors()[0].getErrorCode(), is(ErrorCode.DESYNC_REPORT_INVALID_SIZE)); + verifyNoInteractions(gamePlayerStatsRepository, s3Client, gameDesyncRepository); + } + + @Test + void storeReportPlayerNotInGame() { + when(gamePlayerStatsRepository.existsByGameIdAndPlayerId(GAME_ID, PLAYER_ID)).thenReturn(false); + + assertThrows(AccessDeniedException.class, () -> instance.storeReport(PLAYER_ID, GAME_ID, report(500))); + + verifyNoInteractions(s3Client, gameDesyncRepository); + } + + @Test + void storeReportNotMarkedWhenStorageFails() { + when(gamePlayerStatsRepository.existsByGameIdAndPlayerId(GAME_ID, PLAYER_ID)).thenReturn(true); + when(s3Client.putObject(any(PutObjectRequest.class), any(RequestBody.class))).thenThrow(S3Exception.builder().build()); + + assertThrows(S3Exception.class, () -> instance.storeReport(PLAYER_ID, GAME_ID, report(500))); + + verifyNoInteractions(gameDesyncRepository); + } +}