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

Букирев Воинов Ермаков Ховрычев #45

Open
wants to merge 5 commits 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
19 changes: 19 additions & 0 deletions ConsoleApp/MongoDbExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
using Game.Domain;
using MongoDB.Driver;

namespace ConsoleApp;

public static class MongoDbExtensions
{
public static IGameRepository GetGameRepository(this IMongoDatabase mongoDatabase)
{
mongoDatabase.DropCollection(MongoGameRepository.CollectionName);
return new MongoGameRepository(mongoDatabase);
}

public static IUserRepository GetUserRepository(this IMongoDatabase mongoDatabase)
{
mongoDatabase.DropCollection(MongoUserRepository.CollectionName);
return new MongoUserRepository(mongoDatabase);
}
}
15 changes: 13 additions & 2 deletions ConsoleApp/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
using System;
using System.Linq;
using Game.Domain;
using MongoDB.Driver;

namespace ConsoleApp
{
Expand All @@ -12,8 +13,17 @@ class Program

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
gameRepo = new InMemoryGameRepository();
var db = CreateMongoDb();
userRepo = db.GetUserRepository();
gameRepo = db.GetGameRepository();
}

private static IMongoDatabase CreateMongoDb()
{
var mongoConnectionString = Environment.GetEnvironmentVariable("PROJECT5100_MONGO_CONNECTION_STRING")
?? "mongodb://localhost:27017?maxConnecting=100";
var mongoClient = new MongoClient(mongoConnectionString);
return mongoClient.GetDatabase("game");
}

public static void Main(string[] args)
Expand Down Expand Up @@ -76,6 +86,7 @@ private bool TryJoinToGame(GameEntity game, UserEntity user)

user.CurrentGameId = game.Id;
userRepo.Update(user);
gameRepo.Update(game);

return true;
}
Expand Down
9 changes: 9 additions & 0 deletions Game/Domain/GameEntity.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,22 @@
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;

[BsonConstructor]
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 @@ -22,19 +26,24 @@ public GameEntity(Guid id, GameStatus status, int turnsCount, int currentTurnInd
this.players = players;
}

[BsonElement]
public Guid Id
{
get;
// ReSharper disable once AutoPropertyCanBeMadeGetOnly.Local For MongoDB
private set;
}

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

[BsonElement]
public int TurnsCount { get; }

[BsonElement]
public int CurrentTurnIndex { get; private set; }

[BsonElement]
public GameStatus Status { get; private set; }

public void AddPlayer(UserEntity user)
Expand Down
25 changes: 19 additions & 6 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,52 @@ namespace Game.Domain
// TODO Сделать по аналогии с MongoUserRepository
public class MongoGameRepository : IGameRepository
{
private readonly IMongoCollection<GameEntity> gameCollection;
public const string CollectionName = "games";

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

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

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

public void Update(GameEntity game)
{
throw new NotImplementedException();
var result = gameCollection.ReplaceOne(g => g.Id == game.Id, game);
if (!result.IsAcknowledged)
{
throw new Exception("Update operation was not acknowledged.");
}
}

// Возвращает не более чем 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 result = gameCollection.UpdateOne(
g => g.Id == game.Id && g.Status == GameStatus.WaitingToStart,
Builders<GameEntity>.Update.Set(g => g.Status, game.Status)
);

return result.IsAcknowledged && result.ModifiedCount > 0;
}
}
}
49 changes: 41 additions & 8 deletions Game/Domain/MongoUserRepositoty.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,43 +11,76 @@ public class MongoUserRepository : IUserRepository
public MongoUserRepository(IMongoDatabase database)
{
userCollection = database.GetCollection<UserEntity>(CollectionName);
var indexKeysDefinition = Builders<UserEntity>.IndexKeys.Ascending(user => user.Login);
var options = new CreateIndexOptions
{
Unique = true,
Name = "login_index"
};
userCollection.Indexes.CreateOne(new CreateIndexModel<UserEntity>(indexKeysDefinition, options));
}

public UserEntity Insert(UserEntity user)
{
//TODO: Ищи в документации InsertXXX.
throw new NotImplementedException();
/* var foundUser = userCollection.Find(u => u.Login == user.Login).FirstOrDefault();
if (foundUser != null)
throw new MongoWriteException();*/
userCollection.InsertOne(user);
/* try
{

}
catch (Exception ex)
{
throw;
}*/
return user;
}

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

public UserEntity GetOrCreateByLogin(string login)
{
//TODO: Это Find или Insert
throw new NotImplementedException();
}
lock (userCollection)
{
var user = userCollection.Find(u => u.Login == login, new FindOptions
{
Hint = "login_index"
}).FirstOrDefault();

if (user != null) return user;
user = new UserEntity(Guid.NewGuid()) { Login = login };
userCollection.InsertOne(user);

return user;
}
}

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

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

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

}

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

namespace Game.Domain
{
Expand All @@ -7,27 +8,32 @@ namespace Game.Domain
/// </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>
/// Ход, который выбрал игрок
/// </summary>
[BsonElement]
public PlayerDecision? Decision { get; set; }

/// <summary>
/// Текущие очки в игре. Сколько туров выиграл этот игрок.
/// </summary>
[BsonElement]
public int Score { get; set; }
}
}
12 changes: 11 additions & 1 deletion Game/Domain/UserEntity.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
using System;
using MongoDB.Bson.Serialization.Attributes;

namespace Game.Domain
{
public class UserEntity
{
[BsonConstructor]
public UserEntity()
{
Id = Guid.Empty;
}

[BsonConstructor]
public UserEntity(Guid id)
{
Id = id;
}


[BsonConstructor]
public UserEntity(Guid id, string login, string lastName, string firstName, int gamesPlayed, Guid? currentGameId)
{
Id = id;
Expand All @@ -24,6 +28,7 @@ public UserEntity(Guid id, string login, string lastName, string firstName, int
CurrentGameId = currentGameId;
}

[BsonElement]
public Guid Id
{
get;
Expand All @@ -34,19 +39,24 @@ public Guid Id
/// <summary>
/// Логин должен быть уникальным в системе. Логин решено не делать идентификатором, чтобы у пользователей была возможность в будущем поменять логин.
/// </summary>
[BsonElement]
public string Login { get; set; }
[BsonElement]
public string LastName { get; set; }
[BsonElement]
public string FirstName { get; set; }

/// <summary>
/// Количество сыгранных игр
/// </summary>
[BsonElement]
public int GamesPlayed { get; set; }

/// <summary>
/// Идентификатор игры, в которой этот пользователь участвует.
/// Нужен, чтобы искать игру по первичному индексу, а не по полю Games.Players.UserId. В частности, чтобы не создавать дополнительный индекс на Games.Players.UserId
/// </summary>
[BsonElement]
public Guid? CurrentGameId { get; set; } // Для того, чтобы использовать индекс по Game.Id, а не искать игру по индексу на Game.Players.UserId

public override string ToString()
Expand Down
2 changes: 1 addition & 1 deletion Tests/MongoUserRepositoryShould.cs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ public void Delete()

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