hermes-server/Store/PolicyStore.cs

106 lines
3.7 KiB
C#
Raw Normal View History

using HermesSocketLibrary.db;
using HermesSocketServer.Models;
namespace HermesSocketServer.Store
{
public class PolicyStore : GroupSaveStore<string, PolicyMessage>
{
private readonly string _userId;
private readonly Database _database;
private readonly Serilog.ILogger _logger;
private readonly GroupSaveSqlGenerator<PolicyMessage> _generator;
public PolicyStore(string userId, Database database, Serilog.ILogger logger) : base(logger)
{
_userId = userId;
_database = database;
_logger = logger;
var ctp = new Dictionary<string, string>
{
{ "id", "Id" },
{ "userId", "UserId" },
{ "groupId", "GroupId" },
{ "path", "Path" },
{ "count", "Usage" },
{ "timespan", "Span" },
};
_generator = new GroupSaveSqlGenerator<PolicyMessage>(ctp);
}
public override async Task Load()
{
var data = new Dictionary<string, object>() { { "user", _userId } };
string sql = $"SELECT id, \"groupId\", path, count, timespan FROM \"GroupPermissionPolicy\" WHERE \"userId\" = @user";
await _database.Execute(sql, data, (reader) =>
{
var id = reader.GetGuid(0);
_store.Add(id.ToString(), new PolicyMessage()
{
Id = id,
UserId = _userId,
GroupId = reader.GetGuid(1),
Path = reader.GetString(2),
Usage = reader.GetInt32(3),
Span = reader.GetInt32(4),
});
});
_logger.Information($"Loaded {_store.Count} policies from database.");
}
protected override void OnInitialAdd(string key, PolicyMessage value)
{
}
protected override void OnInitialModify(string key, PolicyMessage value)
{
}
protected override void OnInitialRemove(string key)
{
}
public override async Task<bool> Save()
{
int count = 0;
string sql = string.Empty;
if (_added.Any())
{
lock (_lock)
{
count = _added.Count;
sql = _generator.GenerateInsertSql("GroupPermissionPolicy", _added.Select(a => _store[a]), ["id", "userId", "groupId", "path", "count", "timespan"]);
_added.Clear();
}
_logger.Debug($"GroupPermissionPolicy - Adding {count} rows to database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
if (_modified.Any())
{
lock (_lock)
{
count = _modified.Count;
sql = _generator.GenerateUpdateSql("GroupPermissionPolicy", _modified.Select(m => _store[m]), ["id"], ["userId", "groupId", "path", "count", "timespan"]);
_modified.Clear();
}
_logger.Debug($"GroupPermissionPolicy - Modifying {count} rows in database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
if (_deleted.Any())
{
lock (_lock)
{
count = _deleted.Count;
sql = _generator.GenerateDeleteSql("GroupPermissionPolicy", _deleted, ["id"]);
_deleted.Clear();
}
_logger.Debug($"GroupPermissionPolicy - Deleting {count} rows from database: {sql}");
await _database.ExecuteScalarTransaction(sql);
}
return true;
}
}
}