Skip to content

Commit

Permalink
Fixed dkg-node binding (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
maxirmx authored Apr 15, 2024
1 parent 6b85628 commit 517aa2d
Show file tree
Hide file tree
Showing 18 changed files with 184 additions and 42 deletions.
40 changes: 40 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: Test

on:
push:
branches: [ main ]
pull_request:

concurrency:
group: '${{ github.workflow }}-${{ github.job }}-${{ github.head_ref || github.ref_name }}'
cancel-in-progress: true

jobs:
build:

name: Test on ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ ubuntu-latest, windows-latest, macos-latest ]

steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: true

- name: Setup .NET Core
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x

- name: Install dependencies
run: dotnet restore dkg-nodes.sln

- name: Build
run: dotnet build dkg-nodes.sln --configuration Release --no-restore

- name: Test
run: dotnet test dkg-nodes.sln --no-restore --verbosity normal /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura
6 changes: 6 additions & 0 deletions dkg-nodes.sln
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dkgCommon", "dkgCommon\dkgC
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "dkgLibrary", "dkg\dkgLibrary\dkgLibrary.csproj", "{8C58697D-1A09-40EB-B840-CDB9BBE49FA4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dkgNodesTests", "dkgNodesTests\dkgNodesTests.csproj", "{598AFFF1-61B6-43FD-B170-9E44CC6D7EC4}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -42,6 +44,10 @@ Global
{8C58697D-1A09-40EB-B840-CDB9BBE49FA4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{8C58697D-1A09-40EB-B840-CDB9BBE49FA4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{8C58697D-1A09-40EB-B840-CDB9BBE49FA4}.Release|Any CPU.Build.0 = Release|Any CPU
{598AFFF1-61B6-43FD-B170-9E44CC6D7EC4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{598AFFF1-61B6-43FD-B170-9E44CC6D7EC4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{598AFFF1-61B6-43FD-B170-9E44CC6D7EC4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{598AFFF1-61B6-43FD-B170-9E44CC6D7EC4}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
5 changes: 2 additions & 3 deletions dkgCommon/Models/Reference.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,8 @@

namespace dkgCommon.Models
{
public class Reference
public class Reference(int id)
{
public required int Id { get; set; }
public Reference(int id) { Id = id; }
public int Id { get; set; } = id;
}
}
21 changes: 17 additions & 4 deletions dkgNode/Services/DkgNodeServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -125,15 +125,28 @@ public string Name
}
else
{
roundId = reference.Id;
if (reference.Id == 0)
{
roundId = null;
Logger.LogInformation($"Node '{Config.Name}' not registered with {ServiceNodeUrl} - no rounds");
}
else
{
roundId = reference.Id;
Logger.LogInformation($"Node '{Config.Name}' succesfully registered with {ServiceNodeUrl}");
}
}
}
catch (JsonException ex)
{
Logger.LogError($"Node '{Config.Name}' failed to parse service node response '{responseContent}' from {ServiceNodeUrl}");
Logger.LogError(ex.Message);
}
Logger.LogInformation($"Node '{Config.Name}' succesfully registered with {ServiceNodeUrl}");
}
else
{
Logger.LogError($"Node '{Config.Name}' failed to register with {ServiceNodeUrl}: {response.StatusCode}");
Logger.LogError(responseContent);
}
}
return roundId;
Expand All @@ -160,7 +173,7 @@ internal async void Runner()
}
else
{
if (j++ % 10 == 0)
if (j++ % 30 == 0)
{
Logger.LogDebug($" '{Config.Name}': '{NodeStatusConstants.GetRoundStatusById(Status).Name}'");
}
Expand All @@ -184,7 +197,7 @@ public DkgNodeServer(DkgNodeConfig config, string serviceNodeUrl, ILogger logger
GRpcServer = new Server
{
Services = { BindService(DkgNodeSrv) },
Ports = { new ServerPort(Config.Host, Config.Port, ServerCredentials.Insecure) }
Ports = { new ServerPort("0.0.0.0", Config.Port, ServerCredentials.Insecure) }
};

RunnerThread = new Thread(Runner);
Expand Down
35 changes: 35 additions & 0 deletions dkgNodesTests/Reference.Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using dkgCommon.Models;

namespace dkgNodesTests
{
[TestFixture]
public class ReferenceTests
{
[Test]
public void Constructor_Sets_Id()
{
// Arrange
int expectedId = 5;

// Act
var reference = new Reference(expectedId);

// Assert
Assert.That(reference.Id, Is.EqualTo(expectedId));
}

[Test]
public void Id_Can_Be_Changed()
{
// Arrange
var reference = new Reference(1);
int newId = 2;

// Act
reference.Id = newId;

// Assert
Assert.That(reference.Id, Is.EqualTo(newId));
}
}
}
31 changes: 31 additions & 0 deletions dkgNodesTests/dkgNodesTests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.9.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\dkgCommon\dkgCommon.csproj" />
<ProjectReference Include="..\dkgNode\dkgNode.csproj" />
<ProjectReference Include="..\dkgServiceNode\dkgServiceNode.csproj" />
<ProjectReference Include="..\dkg\dkgLibrary\dkgLibrary.csproj" />
</ItemGroup>

<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>

</Project>
38 changes: 13 additions & 25 deletions dkgServiceNode/Controllers/NodesController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -77,50 +77,38 @@ public async Task<ActionResult<Node>> GetNode(int id)
[HttpPost("register")]
[AllowAnonymous]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Reference))]
[ProducesResponseType(StatusCodes.Status409Conflict, Type = typeof(ErrMessage))]
public async Task<ActionResult<Reference>> RegisterNode(Node node)
{

int? roundId = null;
List<Round> rounds = await roundContext.Rounds.Where(r => r.StatusValue == (short)RStatus.Started).ToListAsync();
if (rounds.Count == 0)
if (rounds.Count != 0)
{
return _409Round();
Round round = rounds[new Random().Next(rounds.Count)];
roundId = round.Id;
}
Round round = rounds[new Random().Next(rounds.Count)];
int id = round.Id;

var xNode = await nodeContext.FindByHostAndPortAsync(node.Host, node.Port);
if (xNode == null)
{
node.RoundId = id;
node.RoundId = roundId;
nodeContext.Nodes.Add(node);
await nodeContext.SaveChangesAsync();
}
else
{
xNode.Name = node.Name;
xNode.PublicKey = node.PublicKey;
xNode.RoundId = id;
xNode.RoundId = roundId;
nodeContext.Entry(xNode).State = EntityState.Modified;
try
{
await nodeContext.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!await nodeContext.ExistsAsync(id))
{
return _404Node(id);
}
else
{
throw;
}
}
await nodeContext.SaveChangesAsync();
}

var reference = new Reference(round.Id) { Id = id };
return CreatedAtAction(nameof(RegisterNode), new { id = node.Id }, reference);
if (roundId == null)
{
roundId = 0;
}
var reference = new Reference((int)roundId);
return Ok(reference);
}

// DELETE: api/nodes/5
Expand Down
2 changes: 1 addition & 1 deletion dkgServiceNode/Controllers/RoundsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ public async Task<ActionResult<Reference>> AddRound()
roundContext.Rounds.Add(round);
await roundContext.SaveChangesAsync();

var reference = new Reference(round.Id) { Id = round.Id };
var reference = new Reference(round.Id);
return CreatedAtAction(nameof(AddRound), new { id = round.Id }, reference);
}

Expand Down
2 changes: 1 addition & 1 deletion dkgServiceNode/Controllers/UsersController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ public async Task<ActionResult<Reference>> PostUser(User user)
userContext.Users.Add(user);
await userContext.SaveChangesAsync();

var reference = new Reference(user.Id) { Id = user.Id };
var reference = new Reference(user.Id);
return CreatedAtAction(nameof(GetUser), new { id = user.Id }, reference);
}

Expand Down
38 changes: 33 additions & 5 deletions dkgServiceNode/Data/DbEnsure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,29 +89,57 @@ public static class DbEnsure
COMMIT;
";

readonly static string sqlScript_0_2_0 = @"
START TRANSACTION;
INSERT INTO ""versions"" (""version"", ""date"") VALUES
('0.2.0', '" + DateTime.Now.ToString("yyyy-MM-dd") + @"');
COMMIT;
";


public static void Ensure_0_1_0(NpgsqlConnection connection)
{
// Check if table 'versions' exists
var sql = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = 'versions';";
using var command = new NpgsqlCommand(sql, connection);
var command = new NpgsqlCommand(sql, connection);
var rows = command.ExecuteScalar();

if (rows != null && (long)rows != 0)
{
sql = "SELECT COUNT(*) FROM versions WHERE version = '0.1.0';";
command = new NpgsqlCommand(sql, connection);
rows = command.ExecuteScalar();
}

if (rows == null || (long)rows == 0)
{
using (var scriptCommand = new NpgsqlCommand(sqlScript_0_1_0, connection))
{
int r = scriptCommand.ExecuteNonQuery();
}
using var scriptCommand = new NpgsqlCommand(sqlScript_0_1_0, connection);
int r = scriptCommand.ExecuteNonQuery();
}
}

public static void Ensure_0_2_0(NpgsqlConnection connection)
{
// Check if table 'versions' exists
var sql = "SELECT COUNT(*) FROM versions WHERE version = '0.2.0';";
using var command = new NpgsqlCommand(sql, connection);
var rows = command.ExecuteScalar();

if (rows == null || (long)rows == 0)
{
using var scriptCommand = new NpgsqlCommand(sqlScript_0_2_0, connection);
int r = scriptCommand.ExecuteNonQuery();
}
}
public static void Ensure(string connectionString)
{

using (var connection = new NpgsqlConnection("Host=dkgservice_db;Port=5432;Database=dkgservice;Username=postgres;Password=postgres"))
{
connection.Open();
Ensure_0_1_0(connection);
Ensure_0_2_0(connection);
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion dkgServiceNode/appsettings.Development.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
"AllowedHosts": "*",
Expand Down
3 changes: 2 additions & 1 deletion dkgServiceNode/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
"Microsoft.AspNetCore": "Warning",
"Microsoft.EntityFrameworkCore": "Warning"
}
},
"AllowedHosts": "*",
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ services:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_HTTP_PORTS=8080
- ASPNETCORE_HTTPS_PORTS=8081
- ASPNETCORE_Kestrel__Certificates__Default__Path=/etc/dkg/s.pfx
# - ASPNETCORE_Kestrel__Certificates__Default__Path=/etc/dkg/s.pfx
# - ASPNETCORE_Kestrel__Certificates__Default__Password=
# - ASPNETCORE_Kestrel__Certificates__Default__Password_FILE=/etc/dkg/s.pwd
ports:
Expand Down
Binary file added readme/dkg-1.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added readme/dkg-2.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added readme/dkg-3.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added readme/dkg-4.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added readme/dkg-5.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 517aa2d

Please sign in to comment.