junction/src/Junction.Persistence/SqliteMachineRepository.cs
dtrentin 507753f82e init: scaffold Junction multi-protocol machine monitor (M1 walking skeleton)
Greenfield C# app reading industrial machine data over pluggable protocols.
M1 walking skeleton: MTConnect plugin polls a machine, Avalonia dashboard
shows live last datum. Build 0 warn/0 err on net48 + net8.0 (Linux),
115 unit tests + 2 docker-gated integration tests.

Projects:
- Junction.Domain (netstandard2.0): Result<T>, models, IProtocolDriver,
  IMachineRepository, plugin manifest. Zero package deps.
- Junction.Core (netstandard2.0): PollingEngine, PluginLoader
  (Assembly.LoadFrom), MachineMonitor, DI extensions.
- Junction.Persistence (netstandard2.0): SqliteMachineRepository (Dapper),
  schema, connection factory. Provider-swap seam to SQL Server.
- Junction.Protocols.MTConnect (netstandard2.0): HTTP driver + namespace-
  version-agnostic parser (MTConnect 1.7 + 2.0). Runtime plugin.
- Junction.App (net48;net8.0): Avalonia MVVM, live dashboard, NLog, DI root.
- Junction.Tests (net8.0): xUnit + Moq, 117 tests.
- mock/: docker-compose MTConnect agent (ladder99/agent).

Target net48 for Windows 7/8 fleet compatibility. Avalonia pinned 11.3.x.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-21 23:32:56 +02:00

446 lines
18 KiB
C#

using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Dapper;
using Junction.Domain;
using Junction.Domain.Models;
using Junction.Domain.Persistence;
namespace Junction.Persistence
{
/// <summary>
/// Dapper + SQLite adapter for <see cref="IMachineRepository"/>.
/// </summary>
/// <remarks>
/// Provider-swap seam: all SQLite/Dapper/ADO.NET types stay inside this class. Only
/// <see cref="Junction.Domain"/> types and BCL primitives cross the boundary.
///
/// Column mapping (see <see cref="SqliteSchema"/> DDL):
/// <list type="bullet">
/// <item><description><see cref="Guid"/> &lt;-&gt; TEXT via <c>ToString("D")</c> (canonical 8-4-4-4-12).</description></item>
/// <item><description><see cref="Machine.PollInterval"/> &lt;-&gt; INTEGER ticks (<see cref="TimeSpan.Ticks"/>).</description></item>
/// <item><description><see cref="Machine.ConnectionConfig"/> &lt;-&gt; TEXT JSON of a Dictionary&lt;string,string&gt; (System.Text.Json). Null/blank JSON rehydrates to an empty dictionary.</description></item>
/// <item><description><see cref="DateTimeOffset"/> &lt;-&gt; TEXT ISO 8601 round-trip ("O").</description></item>
/// <item><description><see cref="ConnectionState"/> &lt;-&gt; INTEGER (enum cast).</description></item>
/// </list>
///
/// Not-found policy: <see cref="GetByIdAsync"/> and <see cref="GetLatestSnapshotAsync"/> return
/// <c>Result.Fail</c> carrying an <see cref="OperationError"/> with code <c>"not_found"</c> — never throw,
/// never a success with a null value.
///
/// Errors: expected failures are reported via <see cref="Result"/>/<see cref="Result{T}"/>. Store
/// exceptions are caught and mapped to <c>Result.Fail</c>; cancellation is mapped to <c>Result.Cancelled</c>.
/// </remarks>
public sealed class SqliteMachineRepository : IMachineRepository
{
private const string Source = "SqliteMachineRepository";
private const string NotFoundCode = "not_found";
private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions();
private readonly IConnectionFactory _connectionFactory;
public SqliteMachineRepository(IConnectionFactory connectionFactory)
{
_connectionFactory = connectionFactory ?? throw new ArgumentNullException(nameof(connectionFactory));
}
public async Task<Result<IReadOnlyList<Machine>>> GetAllAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Result<IReadOnlyList<Machine>>.Cancelled();
}
try
{
using (var connection = OpenConnection())
{
var command = new CommandDefinition(
"SELECT Id, Name, ProtocolId, PollIntervalTicks, ConnectionConfigJson FROM machines;",
cancellationToken: cancellationToken);
var rows = await connection.QueryAsync<MachineRow>(command).ConfigureAwait(false);
var machines = new List<Machine>();
foreach (var row in rows)
{
machines.Add(MapMachine(row));
}
return Result<IReadOnlyList<Machine>>.Ok(machines);
}
}
catch (OperationCanceledException)
{
return Result<IReadOnlyList<Machine>>.Cancelled();
}
catch (Exception ex)
{
return Result<IReadOnlyList<Machine>>.Fail(
OperationError.Of(Source, "GetAll failed: " + ex.Message));
}
}
public async Task<Result<Machine>> GetByIdAsync(Guid id, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Result<Machine>.Cancelled();
}
try
{
using (var connection = OpenConnection())
{
var command = new CommandDefinition(
"SELECT Id, Name, ProtocolId, PollIntervalTicks, ConnectionConfigJson " +
"FROM machines WHERE Id = @Id;",
new { Id = GuidText(id) },
cancellationToken: cancellationToken);
var row = await connection.QuerySingleOrDefaultAsync<MachineRow>(command).ConfigureAwait(false);
if (row == null)
{
return Result<Machine>.Fail(new OperationError(
NotFoundCode, Source, "Machine not found: " + GuidText(id)));
}
return Result<Machine>.Ok(MapMachine(row));
}
}
catch (OperationCanceledException)
{
return Result<Machine>.Cancelled();
}
catch (Exception ex)
{
return Result<Machine>.Fail(
OperationError.Of(Source, "GetById failed: " + ex.Message));
}
}
public async Task<Result> UpsertAsync(Machine machine, CancellationToken cancellationToken)
{
if (machine == null)
{
return Result.Fail(OperationError.Of(Source, "Machine is null."));
}
if (cancellationToken.IsCancellationRequested)
{
return Result.Cancelled();
}
try
{
using (var connection = OpenConnection())
{
var command = new CommandDefinition(
"INSERT INTO machines (Id, Name, ProtocolId, PollIntervalTicks, ConnectionConfigJson) " +
"VALUES (@Id, @Name, @ProtocolId, @PollIntervalTicks, @ConnectionConfigJson) " +
"ON CONFLICT(Id) DO UPDATE SET " +
"Name = excluded.Name, " +
"ProtocolId = excluded.ProtocolId, " +
"PollIntervalTicks = excluded.PollIntervalTicks, " +
"ConnectionConfigJson = excluded.ConnectionConfigJson;",
new
{
Id = GuidText(machine.Id),
machine.Name,
machine.ProtocolId,
PollIntervalTicks = machine.PollInterval.Ticks,
ConnectionConfigJson = SerializeConfig(machine.ConnectionConfig)
},
cancellationToken: cancellationToken);
await connection.ExecuteAsync(command).ConfigureAwait(false);
return Result.Ok();
}
}
catch (OperationCanceledException)
{
return Result.Cancelled();
}
catch (Exception ex)
{
return Result.Fail(OperationError.Of(Source, "Upsert failed: " + ex.Message));
}
}
public async Task<Result> DeleteAsync(Guid id, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Result.Cancelled();
}
try
{
using (var connection = OpenConnection())
using (var transaction = connection.BeginTransaction())
{
var idParam = new { Id = GuidText(id) };
await connection.ExecuteAsync(new CommandDefinition(
"DELETE FROM snapshot_items WHERE MachineId = @Id;",
idParam, transaction, cancellationToken: cancellationToken)).ConfigureAwait(false);
await connection.ExecuteAsync(new CommandDefinition(
"DELETE FROM latest_snapshots WHERE MachineId = @Id;",
idParam, transaction, cancellationToken: cancellationToken)).ConfigureAwait(false);
await connection.ExecuteAsync(new CommandDefinition(
"DELETE FROM machines WHERE Id = @Id;",
idParam, transaction, cancellationToken: cancellationToken)).ConfigureAwait(false);
transaction.Commit();
return Result.Ok();
}
}
catch (OperationCanceledException)
{
return Result.Cancelled();
}
catch (Exception ex)
{
return Result.Fail(OperationError.Of(Source, "Delete failed: " + ex.Message));
}
}
public async Task<Result> SaveSnapshotAsync(MachineSnapshot snapshot, CancellationToken cancellationToken)
{
if (snapshot == null)
{
return Result.Fail(OperationError.Of(Source, "Snapshot is null."));
}
if (cancellationToken.IsCancellationRequested)
{
return Result.Cancelled();
}
try
{
using (var connection = OpenConnection())
using (var transaction = connection.BeginTransaction())
{
var machineIdText = GuidText(snapshot.MachineId);
// Upsert the single latest-snapshot header row.
await connection.ExecuteAsync(new CommandDefinition(
"INSERT INTO latest_snapshots (MachineId, CapturedAt, ConnectionState) " +
"VALUES (@MachineId, @CapturedAt, @ConnectionState) " +
"ON CONFLICT(MachineId) DO UPDATE SET " +
"CapturedAt = excluded.CapturedAt, " +
"ConnectionState = excluded.ConnectionState;",
new
{
MachineId = machineIdText,
CapturedAt = IsoText(snapshot.CapturedAt),
ConnectionState = (int)snapshot.ConnectionState
},
transaction, cancellationToken: cancellationToken)).ConfigureAwait(false);
// Only-latest policy: drop previous items, insert current set.
await connection.ExecuteAsync(new CommandDefinition(
"DELETE FROM snapshot_items WHERE MachineId = @MachineId;",
new { MachineId = machineIdText },
transaction, cancellationToken: cancellationToken)).ConfigureAwait(false);
if (snapshot.Items.Count > 0)
{
var itemParams = new List<object>(snapshot.Items.Count);
foreach (var item in snapshot.Items)
{
itemParams.Add(new
{
MachineId = machineIdText,
ItemId = item.Id,
item.Name,
item.Value,
item.Category,
Timestamp = IsoText(item.Timestamp)
});
}
await connection.ExecuteAsync(new CommandDefinition(
"INSERT INTO snapshot_items (MachineId, ItemId, Name, Value, Category, Timestamp) " +
"VALUES (@MachineId, @ItemId, @Name, @Value, @Category, @Timestamp);",
itemParams,
transaction, cancellationToken: cancellationToken)).ConfigureAwait(false);
}
transaction.Commit();
return Result.Ok();
}
}
catch (OperationCanceledException)
{
return Result.Cancelled();
}
catch (Exception ex)
{
return Result.Fail(OperationError.Of(Source, "SaveSnapshot failed: " + ex.Message));
}
}
public async Task<Result<MachineSnapshot>> GetLatestSnapshotAsync(Guid machineId, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Result<MachineSnapshot>.Cancelled();
}
try
{
using (var connection = OpenConnection())
{
var machineIdText = GuidText(machineId);
var header = await connection.QuerySingleOrDefaultAsync<SnapshotRow>(new CommandDefinition(
"SELECT MachineId, CapturedAt, ConnectionState FROM latest_snapshots WHERE MachineId = @MachineId;",
new { MachineId = machineIdText },
cancellationToken: cancellationToken)).ConfigureAwait(false);
if (header == null)
{
return Result<MachineSnapshot>.Fail(new OperationError(
NotFoundCode, Source, "Snapshot not found for machine: " + machineIdText));
}
var itemRows = await connection.QueryAsync<SnapshotItemRow>(new CommandDefinition(
"SELECT ItemId, Name, Value, Category, Timestamp FROM snapshot_items WHERE MachineId = @MachineId;",
new { MachineId = machineIdText },
cancellationToken: cancellationToken)).ConfigureAwait(false);
var items = new List<DataItem>();
foreach (var itemRow in itemRows)
{
items.Add(new DataItem(
itemRow.ItemId,
itemRow.Name,
itemRow.Value,
itemRow.Category,
ParseIso(itemRow.Timestamp)));
}
var snapshot = new MachineSnapshot(
machineId,
ParseIso(header.CapturedAt),
(ConnectionState)header.ConnectionState,
items);
return Result<MachineSnapshot>.Ok(snapshot);
}
}
catch (OperationCanceledException)
{
return Result<MachineSnapshot>.Cancelled();
}
catch (Exception ex)
{
return Result<MachineSnapshot>.Fail(
OperationError.Of(Source, "GetLatestSnapshot failed: " + ex.Message));
}
}
// -- helpers -------------------------------------------------------------------------
private DbConnection OpenConnection()
{
// SqliteConnectionFactory yields a SqliteConnection (a DbConnection); Dapper's *Async
// needs the DbConnection surface. The concrete Sqlite type never escapes this class.
var connection = _connectionFactory.CreateOpenConnection();
if (connection is DbConnection dbConnection)
{
return dbConnection;
}
connection?.Dispose();
throw new InvalidOperationException(
"IConnectionFactory must return a DbConnection for async Dapper operations.");
}
private static Machine MapMachine(MachineRow row)
{
return new Machine(
Guid.Parse(row.Id),
row.Name,
row.ProtocolId,
DeserializeConfig(row.ConnectionConfigJson),
TimeSpan.FromTicks(row.PollIntervalTicks));
}
private static string GuidText(Guid id) => id.ToString("D");
private static string IsoText(DateTimeOffset value) => value.ToString("O");
private static DateTimeOffset ParseIso(string value) =>
DateTimeOffset.Parse(value, null, System.Globalization.DateTimeStyles.RoundtripKind);
private static string SerializeConfig(IReadOnlyDictionary<string, string> config)
{
Dictionary<string, string> dict;
if (config is Dictionary<string, string> concrete)
{
dict = concrete;
}
else
{
dict = new Dictionary<string, string>(config.Count);
foreach (var pair in config)
{
dict[pair.Key] = pair.Value;
}
}
return JsonSerializer.Serialize(dict, JsonOptions);
}
private static IReadOnlyDictionary<string, string> DeserializeConfig(string? json)
{
if (string.IsNullOrWhiteSpace(json))
{
return new Dictionary<string, string>(0);
}
var dict = JsonSerializer.Deserialize<Dictionary<string, string>>(json!, JsonOptions);
return dict ?? new Dictionary<string, string>(0);
}
// -- row DTOs (private; never cross the boundary) -----------------------------------
private sealed class MachineRow
{
public string Id { get; set; } = "";
public string Name { get; set; } = "";
public string ProtocolId { get; set; } = "";
public long PollIntervalTicks { get; set; }
public string? ConnectionConfigJson { get; set; }
}
private sealed class SnapshotRow
{
public string MachineId { get; set; } = "";
public string CapturedAt { get; set; } = "";
public int ConnectionState { get; set; }
}
private sealed class SnapshotItemRow
{
public string ItemId { get; set; } = "";
public string Name { get; set; } = "";
public string Value { get; set; } = "";
public string Category { get; set; } = "";
public string Timestamp { get; set; } = "";
}
}
}