refactor(sf,site): both stores take ILocalDb instead of a connection string
Tasks 5 and 6 of the Phase 2 plan, committed together because their test
fallout is entangled — several fixtures construct both stores.
StoreAndForwardStorage and SiteStorageService now take ILocalDb. Connections
come from ILocalDb.CreateConnection(), which hands out an already-open,
pragma-configured connection carrying the zb_hlc_next() UDF the capture triggers
call; a raw connection would lack the UDF and every write to a replicated table
would fail closed. Deleted with the connection strings: S&F's
EnsureDatabaseDirectoryExists and its per-open busy_timeout pragma, and the site
service's BusyTimeoutFloorSeconds normalization — LocalDb owns all of it now.
DI: AddSiteRuntime's string overload is gone (nothing left to supply), so the
Host calls the no-arg form. ScadaBridge:Database:SiteDbPath and
StoreAndForwardOptions.SqliteDbPath survive only as the migrator's source
locations in Tasks 8/9.
Two things the plan did not anticipate, both worth reading:
1. FOUND A REAL LATENT DEFECT, from Phase 1, now fixed. The plan assumed
directory creation simply moved to LocalDb along with file ownership. It did
not: the LocalDb library never creates the parent directory, and
SqliteLocalDb opens the file eagerly in its constructor — so a missing
directory is a hard boot failure ("SQLite Error 14: unable to open database
file"), not a degraded start. The default site config points at the RELATIVE
path ./data/site-localdb.db, so any site node without a pre-existing data/
directory fails to boot. The docker rig escapes only because its volume mount
happens to create /app/data — a coincidence that would have hidden this until
a bare-metal or fresh deployment. This has been latent since Phase 1 made
LocalDb:Path required; deleting S&F's EnsureDatabaseDirectoryExists here
would have widened it. Re-established the guarantee at the layer that now
owns the path (SiteLocalDbDirectory.Ensure, called before AddZbLocalDb) and
pinned it with SiteLocalDbDirectoryTests. Non-vacuity is not assumed: two
tests written against the wrong assumption failed with exactly this
SQLite Error 14 before the fix existed.
2. Test fallout was ~7x the plan's estimate. The plan named "fixtures" in one
project; the constructor change actually reaches 40 files across 7 test
projects, and most used Mode=Memory;Cache=Shared — which LocalDb has no
equivalent for, so every one had to move to a real temp file. Rather than
copy the Phase 1 TestLocalDb fixture into 7 projects, added a shared
tests/ZB.MOM.WW.ScadaBridge.TestSupport library (not a test project) so the
WAL-sidecar cleanup and the "real, not stubbed" rationale live in one place.
Retargeted rather than deleted, in both directions: the S&F WAL test now asserts
against the LocalDb-backed store (WAL genuinely is LocalDb's job), while the
directory-creation test moved to Host.Tests (that guarantee is NOT LocalDb's).
SiteStorageServiceTests.Initialize_EnablesWalJournalMode got the same treatment.
DeploymentManagerMediumFindingsTests induced a persistence failure via an
unopenable path, which no longer reaches the assertion since the fixture now
throws first; it induces the same failure shape via an uninitialized store.
Verified: full solution build 0 warnings; SiteRuntime 532, Host 318,
AuditLog 355, ExternalSystemGateway 142, HealthMonitoring 97,
StoreAndForward 153 — 1597 passed, 0 failed.
Claude-Session: https://claude.ai/code/session_01BL2Vu1ESDQ9SCN4gVKkdts
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.LocalDb;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Services;
|
||||
using ZB.MOM.WW.ScadaBridge.SiteEventLogging;
|
||||
|
||||
@@ -15,14 +16,12 @@ public static class ServiceCollectionExtensions
|
||||
/// <returns>The same <paramref name="services"/> collection, for chaining.</returns>
|
||||
public static IServiceCollection AddStoreAndForward(this IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<StoreAndForwardStorage>(sp =>
|
||||
{
|
||||
var options = sp.GetRequiredService<IOptions<StoreAndForwardOptions>>().Value;
|
||||
var logger = sp.GetRequiredService<ILogger<StoreAndForwardStorage>>();
|
||||
return new StoreAndForwardStorage(
|
||||
$"Data Source={options.SqliteDbPath}",
|
||||
logger);
|
||||
});
|
||||
// The buffer now lives in the consolidated LocalDb database at LocalDb:Path, not
|
||||
// at StoreAndForwardOptions.SqliteDbPath — that option survives only as the
|
||||
// migrator's source location (Task 8).
|
||||
services.AddSingleton<StoreAndForwardStorage>(sp => new StoreAndForwardStorage(
|
||||
sp.GetRequiredService<ILocalDb>(),
|
||||
sp.GetRequiredService<ILogger<StoreAndForwardStorage>>()));
|
||||
|
||||
services.AddSingleton<StoreAndForwardService>(sp =>
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using Microsoft.Data.Sqlite;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ZB.MOM.WW.LocalDb;
|
||||
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.StoreAndForward;
|
||||
@@ -11,17 +12,25 @@ namespace ZB.MOM.WW.ScadaBridge.StoreAndForward;
|
||||
/// </summary>
|
||||
public class StoreAndForwardStorage
|
||||
{
|
||||
private readonly string _connectionString;
|
||||
private readonly ILocalDb _localDb;
|
||||
private readonly ILogger<StoreAndForwardStorage> _logger;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of <see cref="StoreAndForwardStorage"/> with the given SQLite connection string.
|
||||
/// Initializes the store over the consolidated site database and applies the schema.
|
||||
/// </summary>
|
||||
/// <param name="connectionString">SQLite connection string for the store-and-forward database.</param>
|
||||
/// <param name="localDb">
|
||||
/// The consolidated site database. Every connection it hands out is already open and carries
|
||||
/// the per-connection pragmas (including <c>busy_timeout</c>) plus the <c>zb_hlc_next()</c>
|
||||
/// UDF that <c>sf_messages</c>' capture triggers call — which is exactly why the store no
|
||||
/// longer opens its own <see cref="SqliteConnection"/> from a connection string. A raw
|
||||
/// connection would lack the UDF and every write to the replicated table would fail closed.
|
||||
/// </param>
|
||||
/// <param name="logger">Logger for diagnostics.</param>
|
||||
public StoreAndForwardStorage(string connectionString, ILogger<StoreAndForwardStorage> logger)
|
||||
public StoreAndForwardStorage(ILocalDb localDb, ILogger<StoreAndForwardStorage> logger)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
ArgumentNullException.ThrowIfNull(localDb);
|
||||
ArgumentNullException.ThrowIfNull(logger);
|
||||
_localDb = localDb;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -29,22 +38,12 @@ public class StoreAndForwardStorage
|
||||
/// Creates the sf_messages table if it does not exist.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task InitializeAsync()
|
||||
public Task InitializeAsync()
|
||||
{
|
||||
EnsureDatabaseDirectoryExists();
|
||||
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
|
||||
// Enable WAL so the concurrent writers this store has by design (script
|
||||
// enqueues, the retry sweep's per-target lanes, standby replication applies,
|
||||
// central pull queries) read/write without "database is locked". WAL is
|
||||
// persistent + file-scoped; in-memory DBs report "memory" instead — harmless,
|
||||
// so it is not asserted here.
|
||||
await using (var walCmd = connection.CreateCommand())
|
||||
{
|
||||
walCmd.CommandText = "PRAGMA journal_mode=WAL";
|
||||
await walCmd.ExecuteNonQueryAsync();
|
||||
}
|
||||
// No directory creation and no journal-mode pragma here any more: LocalDb owns
|
||||
// the file (it creates the directory) and sets WAL plus the per-connection
|
||||
// pragmas on every connection it hands out.
|
||||
using var connection = OpenConnection();
|
||||
|
||||
// The DDL itself lives in StoreAndForwardSchema so the Host can apply it to a
|
||||
// LocalDb-managed connection before RegisterReplicated installs the capture
|
||||
@@ -53,50 +52,16 @@ public class StoreAndForwardStorage
|
||||
StoreAndForwardSchema.Apply(connection);
|
||||
|
||||
_logger.LogInformation("Store-and-forward SQLite storage initialized");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ensures the directory for a file-backed SQLite database exists. SQLite creates
|
||||
/// the database file on demand but not its parent directory, so a configured path
|
||||
/// such as "./data/store-and-forward.db" fails to open ("unable to open database
|
||||
/// file") when the "data" directory does not yet exist. In-memory databases and
|
||||
/// bare filenames in the working directory have no directory to create and are
|
||||
/// skipped.
|
||||
/// CreateConnection returns an ALREADY-OPEN, pragma-configured connection with the
|
||||
/// <c>zb_hlc_next()</c> UDF registered. Calling <c>OpenAsync</c> on it throws, and a raw
|
||||
/// <see cref="SqliteConnection"/> would lack the UDF, making every capture trigger fail
|
||||
/// closed.
|
||||
/// </summary>
|
||||
private void EnsureDatabaseDirectoryExists()
|
||||
{
|
||||
var builder = new SqliteConnectionStringBuilder(_connectionString);
|
||||
if (builder.Mode == SqliteOpenMode.Memory)
|
||||
return;
|
||||
|
||||
var dataSource = builder.DataSource;
|
||||
if (string.IsNullOrEmpty(dataSource) || dataSource == ":memory:")
|
||||
return;
|
||||
|
||||
var directory = System.IO.Path.GetDirectoryName(System.IO.Path.GetFullPath(dataSource));
|
||||
if (!string.IsNullOrEmpty(directory) && !System.IO.Directory.Exists(directory))
|
||||
{
|
||||
System.IO.Directory.CreateDirectory(directory);
|
||||
_logger.LogInformation("Created store-and-forward database directory: {Directory}", directory);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens a connection with a 5s busy_timeout. Concurrent writers exist by
|
||||
/// design (script enqueues, the sweep's lanes, standby replication applies,
|
||||
/// central pull queries); with connection-per-operation the pragma must be
|
||||
/// set per open (it is per-connection, and Microsoft.Data.Sqlite pooling
|
||||
/// makes the extra statement cheap on a pooled physical connection).
|
||||
/// </summary>
|
||||
private async Task<SqliteConnection> OpenConnectionAsync()
|
||||
{
|
||||
var connection = new SqliteConnection(_connectionString);
|
||||
await connection.OpenAsync();
|
||||
await using var pragma = connection.CreateCommand();
|
||||
pragma.CommandText = "PRAGMA busy_timeout = 5000";
|
||||
await pragma.ExecuteNonQueryAsync();
|
||||
return connection;
|
||||
}
|
||||
private SqliteConnection OpenConnection() => _localDb.CreateConnection();
|
||||
|
||||
/// <summary>
|
||||
/// INSERT statement for a full message row. Shared by <see cref="EnqueueAsync"/>
|
||||
@@ -149,7 +114,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task EnqueueAsync(StoreAndForwardMessage message)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = InsertMessageSql;
|
||||
@@ -169,7 +134,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>The oldest-first page (at most <paramref name="limit"/> rows) and whether more rows exist beyond it.</returns>
|
||||
public async Task<(List<StoreAndForwardMessage> Messages, bool Truncated)> GetAllMessagesAsync(int limit)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -197,7 +162,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task ReplaceAllAsync(IReadOnlyList<StoreAndForwardMessage> messages)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync();
|
||||
|
||||
await using (var deleteCmd = connection.CreateCommand())
|
||||
@@ -232,7 +197,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task UpsertMessageAsync(StoreAndForwardMessage message)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -289,7 +254,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to the list of messages due for retry, ordered by creation time ascending.</returns>
|
||||
public async Task<List<StoreAndForwardMessage>> GetMessagesForRetryAsync(int limit = 0)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -323,7 +288,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task UpdateMessageAsync(StoreAndForwardMessage message)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -360,7 +325,7 @@ public class StoreAndForwardStorage
|
||||
StoreAndForwardMessage message,
|
||||
StoreAndForwardMessageStatus expectedStatus)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -393,7 +358,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
public async Task RemoveMessageAsync(string messageId)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "DELETE FROM sf_messages WHERE id = @id";
|
||||
@@ -414,7 +379,7 @@ public class StoreAndForwardStorage
|
||||
int pageNumber = 1,
|
||||
int pageSize = 50)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var transaction = (SqliteTransaction)await connection.BeginTransactionAsync();
|
||||
|
||||
@@ -459,7 +424,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to <c>true</c> if the message was found and reset to Pending; <c>false</c> if not found or not in Parked status.</returns>
|
||||
public async Task<bool> RetryParkedMessageAsync(string messageId)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -483,7 +448,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to <c>true</c> if the message was found and deleted; <c>false</c> if not found or not in Parked status.</returns>
|
||||
public async Task<bool> DiscardParkedMessageAsync(string messageId)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "DELETE FROM sf_messages WHERE id = @id AND status = @parked";
|
||||
@@ -500,7 +465,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to a dictionary mapping each category to its pending message count.</returns>
|
||||
public async Task<Dictionary<StoreAndForwardCategory, int>> GetBufferDepthByCategoryAsync()
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -530,7 +495,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to the number of messages whose origin instance matches <paramref name="instanceName"/>.</returns>
|
||||
public async Task<int> GetMessageCountByOriginInstanceAsync(string instanceName)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -549,7 +514,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to the matching message, or <c>null</c> if not found.</returns>
|
||||
public async Task<StoreAndForwardMessage?> GetMessageByIdAsync(string messageId)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = @"
|
||||
@@ -570,7 +535,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to the number of messages currently in Parked status.</returns>
|
||||
public async Task<int> GetParkedMessageCountAsync()
|
||||
{
|
||||
await using var conn = await OpenConnectionAsync();
|
||||
await using var conn = OpenConnection();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM sf_messages WHERE status = @parked";
|
||||
cmd.Parameters.AddWithValue("@parked", (int)StoreAndForwardMessageStatus.Parked);
|
||||
@@ -588,7 +553,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to the oldest parked row's creation time, or <c>null</c> if none are parked.</returns>
|
||||
public async Task<DateTimeOffset?> GetOldestParkedCreatedAtAsync()
|
||||
{
|
||||
await using var conn = await OpenConnectionAsync();
|
||||
await using var conn = OpenConnection();
|
||||
await using var cmd = conn.CreateCommand();
|
||||
cmd.CommandText = "SELECT MIN(created_at) FROM sf_messages WHERE status = @parked";
|
||||
cmd.Parameters.AddWithValue("@parked", (int)StoreAndForwardMessageStatus.Parked);
|
||||
@@ -605,7 +570,7 @@ public class StoreAndForwardStorage
|
||||
/// <returns>A task that resolves to the count of messages with the specified status.</returns>
|
||||
public async Task<int> GetMessageCountByStatusAsync(StoreAndForwardMessageStatus status)
|
||||
{
|
||||
await using var connection = await OpenConnectionAsync();
|
||||
await using var connection = OpenConnection();
|
||||
|
||||
await using var cmd = connection.CreateCommand();
|
||||
cmd.CommandText = "SELECT COUNT(*) FROM sf_messages WHERE status = @status";
|
||||
|
||||
Reference in New Issue
Block a user