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

Куршев Алексей, Хрусталев Дмитрий, Володько Екатерина. ФТ-302 #41

Open
wants to merge 3 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
7 changes: 6 additions & 1 deletion 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,7 +13,11 @@ class Program

private Program(string[] args)
{
userRepo = new InMemoryUserRepository();
// Настройка подключения к MongoDB
var mongoClient = new MongoClient("mongodb://localhost:27017");
var database = mongoClient.GetDatabase("GameDatabase");

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

Expand Down
5 changes: 5 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;


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 @@ -31,6 +35,7 @@ public Guid Id

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

[BsonElement]
public int TurnsCount { get; }

public int CurrentTurnIndex { get; private set; }
Expand Down
32 changes: 21 additions & 11 deletions Game/Domain/MongoGameRepository.cs
Original file line number Diff line number Diff line change
@@ -1,45 +1,55 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using MongoDB.Driver;

namespace Game.Domain
{
// TODO Сделать по аналогии с MongoUserRepository
public class MongoGameRepository : IGameRepository
{
public const string CollectionName = "games";
private readonly IMongoCollection<GameEntity> _gamesCollection;

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

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

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

public void Update(GameEntity game)
{
throw new NotImplementedException();
var result = _gamesCollection.ReplaceOne(g => g.Id == game.Id, game);
if (!result.IsAcknowledged)
{
throw new Exception("Update failed.");
}
}

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

// Обновляет игру, если она находится в статусе GameStatus.WaitingToStart
public bool TryUpdateWaitingToStart(GameEntity game)
{
//TODO: Для проверки успешности используй IsAcknowledged и ModifiedCount из результата
throw new NotImplementedException();
var result = _gamesCollection.ReplaceOne(
g => g.Id == game.Id && g.Status == GameStatus.WaitingToStart,
game);

return result.IsAcknowledged && result.ModifiedCount > 0;
}
}
}
}
61 changes: 45 additions & 16 deletions Game/Domain/MongoUserRepositoty.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using MongoDB.Driver;

namespace Game.Domain
Expand All @@ -8,52 +11,78 @@ public class MongoUserRepository : IUserRepository
private readonly IMongoCollection<UserEntity> userCollection;
public const string CollectionName = "users";

public static readonly Object Lock = new();

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

// Создание уникального индекса для логинов
userCollection.Indexes.CreateOne(new CreateIndexModel<UserEntity>(
Builders<UserEntity>.IndexKeys.Ascending(u => u.Login),
new CreateIndexOptions { Unique = true }
));
}

public UserEntity Insert(UserEntity user)
{
//TODO: Ищи в документации InsertXXX.
throw new NotImplementedException();
// Используем метод InsertOne, чтобы избежать необходимости вызывать Find
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();
lock(Lock)
{
return userCollection.Find(user => user.Login == login).FirstOrDefault()
?? Insert(new UserEntity(Guid.NewGuid()) { Login = login });
}

}

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 users = userCollection
.Find(u => true)
.SortBy(u => u.Login)
.Skip((pageNumber - 1) * pageSize)
.Limit(pageSize)
.ToList();

var totalUsers = userCollection.CountDocuments(u => true);

return new PageList<UserEntity>(users, totalUsers, pageNumber, pageSize);
}

// Не нужно реализовывать этот метод
public void UpdateOrInsert(UserEntity user, out bool isInserted)
{
throw new NotImplementedException();
var existingUser = FindById(user.Id);
if (existingUser == null)
{
Insert(user);
isInserted = true;
}
else
{
Update(user);
isInserted = false;
}
}
}
}
}
8 changes: 6 additions & 2 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,24 +8,27 @@ 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>
public PlayerDecision? Decision { get; set; }

/// <summary>
/// Текущие очки в игре. Сколько туров выиграл этот игрок.
/// </summary>
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(20000)]
public void SearchByLoginFast()
{
for (int i = 0; i < 10000; i++)
Expand Down
22 changes: 22 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from pymongo import MongoClient

client = MongoClient('mongodb://localhost:27017/')

db = client['game-tests']

collection1 = db['users']

documents = collection1.find()

for doc in documents:
print(doc)

collection2 = db['games']

documents = collection2.find()

for doc in documents:
print(doc)

client.close()