Add spark service modules designed for Dependency Injection

This commit is contained in:
John Colvin committed 2025-07-23 15:14:34 -04:00
1 parent b214198dd6
commit ddf9bc7c0b
13 files changed
+175 -5

No files matched your search

@@ -0,0 +1,11 @@
#nullable enable
namespace Spark.Api.Services;
public class SparkApiConfig {
public string? ConfigServer { get; set; }
public string? User { get; set; }
public string? Password { get; set; }
public bool EnableAdmin { get; set; }
public bool EnableOrders { get; set; }
public bool EnablePosition { get; set; }
}
@@ -0,0 +1,54 @@
#nullable enable
namespace Spark.Api.Services;
using bts.api.admin;
using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Spark.Api.Admin;
using Spark.Api.Orders;
using Spark.Api.Reactive;
using Spark.Core.Services;
using System;
using System.Linq;
public static class SparkApiServices {
/// <summary>
/// Connects to Sparkd. To configure, define 'SparkdCredentials.User' and
/// 'SparkdCredentials.Password' in the input --config json file.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection"/> to add the service to.</param>
/// <returns>A reference to this instance after the operation has completed.</returns>
public static IServiceCollection AddSparkApi(this IServiceCollection services, IConfiguration configurationSection) {
if (!services.Any(s => s.ServiceType == typeof(SparkService))) {
/// <see cref="SparkService"/> initializes configuration and logging (this should be done
/// before any api-related services run).
throw new InvalidOperationException("Must add SparkService first");
}
services
.Configure<SparkApiCredentials>(configurationSection.GetSection("Credentials"))
.AddSingleton<ServiceContext>()
.AddHostedService<SparkdLoginService>()
.AddSparkdService<SecurityResolver>();
if (configurationSection.GetValue("EnableOrders", true)) {
services.AddSparkdService<OrderService>()
.AddSingleton<OrdersClient>();
}
if (configurationSection.GetValue("EnablePosition", true)) {
services.AddSparkdService<PositionService>();
}
if (configurationSection.GetValue("EnableAdmin", true)) {
services.AddSparkdService<AdminService>();
services.AddSparkdService<AdminClient>();
}
return services;
}
internal static IServiceCollection AddSparkdService<T>(this IServiceCollection services) where T : class =>
services.AddSingleton(sp => sp.GetRequiredService<ServiceContext>().GetRequiredService<T>());
}
@@ -0,0 +1,7 @@
#nullable enable
namespace Spark.Api.Services;
public class SparkApiCredentials {
public string? User { get; set; }
public string? Password { get; set; }
}
@@ -0,0 +1,37 @@
#nullable enable
namespace Spark.Api.Services;
using bts;
using bts.api.core;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
///
/// </summary>
public class SparkdLoginService : IHostedService {
readonly ServiceContext serviceContext;
readonly SparkApiCredentials config;
public SparkdLoginService(ServiceContext serviceContext, IOptions<SparkApiCredentials> config) {
this.serviceContext = serviceContext;
this.config = config.Value;
}
public Task StartAsync(CancellationToken cancellationToken) =>
string.IsNullOrEmpty(config.User)
? Task.CompletedTask
: Task.Run(() => {
var res = serviceContext.login(config.User, config.Password ?? string.Empty).GetAwaiter().GetResult();
if (!res.success) {
Log.Gen.error("Failed to login to sparkd.");
}
}, cancellationToken);
public Task StopAsync(CancellationToken cancellationToken) =>
Task.CompletedTask;
}
+3 -2
View File
@@ -2,6 +2,8 @@
namespace bts.api.core {
using bts.api.user;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -12,8 +14,7 @@ namespace bts.api.core {
IntPtr _qbus;
AuthToken? _token;
public ServiceContext(string? config_source = null) {
BTS.init(config_source);
public ServiceContext() {
_qbus = ApiNativeMethods.api_create_quickbus(null, 0);
}
+1
View File
@@ -20,6 +20,7 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Google.Protobuf" Version="3.24.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="System.Collections.Immutable" Version="7.0.0" />
<PackageReference Include="System.Reactive" Version="6.0.0" />
</ItemGroup>
+1 -1
View File
@@ -4,7 +4,7 @@ namespace Spark.Core.Protobuf {
using System;
public interface IProtobuf<T> : ICloneable<T>, IEquatable<T> {
public interface IProtobuf<T> : ICloneable<T>, IEquatable<T> where T : notnull {
object ICloneable.Clone() =>
Clone() ?? throw new InvalidOperationException();
}
@@ -0,0 +1,6 @@
#nullable enable
namespace Spark.Core.Services;
public class SparkConfig {
public string? ConfigServer { get; set; }
}
@@ -0,0 +1,18 @@
namespace Spark.Core.Services;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Linq;
public static class SparkCoreServices {
public static IServiceCollection AddSpark(this IServiceCollection services, IConfiguration configurationSection) {
if (services.Any(s => s.ServiceType == typeof(SparkService))) {
throw new InvalidOperationException("SparkService has already been added");
}
return services.Configure<SparkConfig>(configurationSection)
.AddSingleton<SparkService>()
.AddHostedService(sp => sp.GetRequiredService<SparkService>());
}
}
@@ -0,0 +1,32 @@
#nullable enable
namespace Spark.Core.Services;
using mbts.config;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// An <see cref="IHostedService"/> facade that initializes Spark protobuf config, logging, and
/// quickbus for both c# and cpp.
/// </summary>
public class SparkService : IHostedService {
readonly SparkConfig config;
public SparkService(IOptions<SparkConfig> config)
: this(config.Value) { }
public SparkService(SparkConfig config) =>
this.config = config;
public Task StartAsync(CancellationToken cancellationToken) {
Configuration.initialize(config.ConfigServer);
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken) =>
Task.CompletedTask;
}
+1
View File
@@ -15,6 +15,7 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Google.Protobuf" Version="3.24.3" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="protobuf-net" Version="3.2.26" />
<PackageReference Include="System.Reactive" Version="6.0.0" />
</ItemGroup>
+2 -1
View File
@@ -9,7 +9,7 @@ namespace bts
{
static int _needs_init_spark_lib = 0;
public static void init(string config_source = null) {
public static bool init(string config_source = null) {
var version = Assembly.GetExecutingAssembly().GetName().Version;
Console.WriteLine(
$"Configuring Spark {version} with {(config_source is null ? "defaults" : $"'{config_source}'")}");
@@ -26,6 +26,7 @@ namespace bts
if (Interlocked.CompareExchange(ref _needs_init_spark_lib,1,0) == 0) {
utils.BTSNativeMethods.init_spark_lib();
}
return true;
// This seems like a good idea but it crashes due to thread shutdown order
// AppDomain.CurrentDomain.ProcessExit += (o, e) => {
@@ -2,7 +2,8 @@
namespace bts {
using System;
public interface ICloneable<T> : ICloneable {
public interface ICloneable<T> : ICloneable where T : notnull {
new T Clone();
object ICloneable.Clone() => Clone();
}
}