fix: Ensure spark config init and login are only performed once

As a static function that could be called from anywhere in the code
(directly or indirectly), 'Configuration.Initialize' was vulnerable to
race bugs. The "Configuration.get<T>()" method, whose calls are
ubiquitous in our code, would initialize config if it hadn't been done
so already. Without a reference to the configServer param, this param
would effectively be ignored/overridden with null.

It's important that login only be performed once, for obvious reasons
(our exes that connect to sparkd are generally designed to process data
for a single user). Furthermore, not every routine that requires a
successful login has a reference to the credentials needed to do it. To
address this, we now pass the ISparkdLoginService singleton to these
routines so they can wait until the singular login task has completed
before they begin.
This commit is contained in:
John Colvin committed 2025-12-05 15:53:31 +00:00
1 parent f3f2e5834c
commit 69b1ac243e
3 files changed
+85 -16

No files matched your search

@@ -7,6 +7,8 @@ using bts.api.core;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Spark.Core.Services;
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -18,44 +20,53 @@ using System.Threading.Tasks;
public class SparkdLoginService : IHostedService, ISparkdLoginService {
readonly ServiceContext serviceContext;
readonly SparkApiCredentials config;
readonly ISparkConfigLoader sparkConfigLoader;
readonly object lockObj = new();
LoginResult? loginResult;
Task<LoginResult>? loginTask;
public SparkdLoginService(ServiceContext serviceContext, IOptions<SparkApiCredentials> config)
: this(serviceContext, config.Value) { }
public SparkdLoginService(ServiceContext serviceContext, IOptions<SparkApiCredentials> config, ISparkConfigLoader sparkConfigLoader)
: this(serviceContext, config.Value, sparkConfigLoader) { }
public SparkdLoginService(ServiceContext serviceContext, SparkApiCredentials config) {
public SparkdLoginService(ServiceContext serviceContext, SparkApiCredentials config, ISparkConfigLoader sparkConfigLoader) {
this.serviceContext = serviceContext;
this.config = config;
this.sparkConfigLoader = sparkConfigLoader;
}
public ValueTask<LoginResult> LoginAsync() {
public async ValueTask<LoginResult> LoginAsync() {
Log.Gen.info("SparkdLoginService.LoginAsync");
await sparkConfigLoader.InitializeAsync(CancellationToken.None);
if (loginResult is not null) {
return ValueTask.FromResult(loginResult);
return loginResult;
}
if (string.IsNullOrEmpty(config.User)) {
return ValueTask.FromException<LoginResult>(new InvalidOperationException("User is null/empty"));
Log.Gen.warn("SparkdLoginService.LoginAsync skipping because config.User is null");
throw new InvalidOperationException("User is null/empty");
}
lock (lockObj) {
if (loginResult is not null) {
return ValueTask.FromResult(loginResult);
return loginResult;
}
loginTask ??= LoginImplAsync();
return new(loginTask);
}
return await loginTask;
async Task<LoginResult> LoginImplAsync() {
Log.Gen.warn($"SparkdLoginService.LoginAsync logging in now. user: {config.User}");
loginResult = await serviceContext.login(config.User ?? string.Empty, config.Password ?? string.Empty);
if (!loginResult.success) {
Log.Gen.error($"Failed to login to sparkd. reason: {loginResult.reason}");
}
Log.Gen.info($"SparkdLoginService.LoginAsync successfully logged. user: {config.User}");
return loginResult;
}
}
public Task StartAsync(CancellationToken cancellationToken) =>
LoginAsync().AsTask();
public Task StartAsync(CancellationToken cancellationToken) {
Log.Gen.info("SparkdLoginService.StartAsync");
return LoginAsync().AsTask();
}
public Task StopAsync(CancellationToken cancellationToken) =>
Task.CompletedTask;
@@ -5,8 +5,10 @@ using bts;
using mbts.config;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Threading;
using System.Threading.Tasks;
@@ -15,13 +17,30 @@ using System.Threading.Tasks;
/// </summary>
public class SparkConfigLoader : ISparkConfigLoader {
readonly SparkConfigLoaderOpts config;
readonly ILogger? logger;
public SparkConfigLoader(IOptions<SparkConfigLoaderOpts> config)
: this(config.Value) { }
public SparkConfigLoader(IOptions<SparkConfigLoaderOpts> config, ILogger<SparkConfigLoader>? logger = null)
: this(config.Value, logger) { }
public SparkConfigLoader(SparkConfigLoaderOpts config) =>
public SparkConfigLoader(SparkConfigLoaderOpts config, ILogger<SparkConfigLoader>? logger = null) {
this.config = config;
this.logger = logger;
}
public async Task InitializeAsync(CancellationToken cancellationToken) =>
Log.assert(await Configuration.InitializeAsync(config.ConfigServer, cancellationToken));
public async Task InitializeAsync(CancellationToken cancellationToken) {
bool success = false;
logger?.LogInformation("Initializing Spark config. ConfigServer: {ConfigServer}", config.ConfigServer);
var task = Configuration.InitializeAsync(config.ConfigServer, cancellationToken);
if (task.IsCompleted) {
// logger?.LogWarning("Spark config already initialized.");
success = task.IsCompletedSuccessfully && task.Result;
} else {
try {
success = await task;
} catch (Exception ex) {
logger?.LogError("Failed to load Spark config. ConfigServer: {ConfigServer}; Exception:\n{Exception}", config.ConfigServer, ex);
}
}
Log.assert(success, $"Failed to load Spark config. ConfigServer: {config.ConfigServer}");
}
}
+40 -1
View File
@@ -53,6 +53,45 @@ namespace mbts.config {
}
}
public static ValueTask<bool> UntilInitializedAsync() {
var cts = new CancellationTokenSource();
var task = UntilInitializedAsync(cts.Token);
cts.CancelAfter(TimeSpan.FromSeconds(5));
return task;
}
public static ValueTask<bool> UntilInitializedAsync(CancellationToken cancellationToken) {
switch (_state) {
case State.OK:
return ValueTask.FromResult(true);
case State.Error:
return ValueTask.FromResult(false);
default:
break;
}
return new(Task.Run(Impl));
bool Impl() {
const int MAX_ATTEMPTS = 100;
const int SLEEP_MS = 100;
for (int i = 0; i < MAX_ATTEMPTS; i++) {
switch (_state) {
case State.OK:
return true;
case State.Error:
return false;
default:
if (cancellationToken.IsCancellationRequested) {
return false;
}
break;
}
Thread.Sleep(SLEEP_MS);
}
return false;
}
}
public static ValueTask<bool> InitializeAsync(string? configSource = null) =>
InitializeAsync(configSource, CancellationToken.None);
@@ -179,7 +218,7 @@ namespace mbts.config {
static byte[]? _get_buffer(string key_name) {
switch (_state) {
case State.Uninitialized:
if (!InitializeAsync().GetAwaiter().GetResult()) {
if (!UntilInitializedAsync().AsTask().GetAwaiter().GetResult()) {
return null;
}
break;