Use dependency injection in spark api server

This commit is contained in:
John Colvin committed 2024-07-31 00:02:11 -04:00
1 parent a89c4a5e1e
commit e775bc19b8
9 files changed
+205 -235

No files matched your search

+96 -77
View File
@@ -1,86 +1,105 @@
namespace spark_api_server {
using bts;
using bts.api.core;
using bts.websocket_core;
using bts;
using bts.websocket_core;
using CommandLine;
using CommandLine;
using Spark.Api.Server;
using Spark.Api.Services;
using Spark.Core.Services;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Threading;
using Spark.Api.Server;
using Spark.Api.Services;
using Spark.Core;
using Spark.Core.Services;
using Spark.WebSocket.Services;
class Program {
[Flags]
enum Errors {
None = 0,
Listen = 1,
// Add errors as needed
using spark_api_server;
using System;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
var res = Parser.Default.ParseArguments<RunOptions, DumpSecuritiesOptions, DumpBooksOptions>(args);
await res.MapResult<RunOptions, DumpSecuritiesOptions, DumpBooksOptions, Task<int>>(
Run, SecurityDumper.run, BookDumper.run, errs => Task.FromResult(1));
static Task<int> Run(RunOptions opts) {
var builder = WebApplication.CreateBuilder(new WebApplicationOptions {
Args = Environment.GetCommandLineArgs(),
ApplicationName = "spark_api_server",
});
ConfigureApp(builder.Configuration, builder.Environment.EnvironmentName);
ConfigureServices(builder.Services, builder.Configuration);
var app = builder.Build();
app.UseWebSockets(app.Configuration.GetValue<WebSocketOptions>("WebSocketOptions") ?? new() { KeepAliveInterval = TimeSpan.FromMinutes(2) });
var gateway = new Lazy<IWebsocketConnectionGateway>(app.Services.GetRequiredService<IWebsocketConnectionGateway>);
app.Map("/", HandleRequest);
var errors = Errors.None;
Log.Api.info("Starting websocket server...");
try {
app.Run();
Log.Api.info("Websocket server stopped without error");
} catch (Exception ex) {
Log.Api.error($"Websocket server threw ex: {ex}");
errors |= Errors.Listen;
}
return Task.FromResult((int)errors);
Task HandleRequest(HttpContext context) =>
gateway.Value.HandleRequest(context);
}
static void ConfigureApp(ConfigurationManager configBuilder, string environment) {
// We prefix appsettings with the exe name because multiple exes will usually be in the build dir
// (this way, each exe can still load its own appsettings files from the current directory).
var exeName = Assembly.GetCallingAssembly().GetName().Name;
AddJsonFile($"{exeName}.appsettings.json");
AddJsonFile($"{exeName}.appsettings.{environment}.json");
var cfg = configBuilder.GetSection("config")?.Value;
if (!SetBasePath(cfg)) {
AddJsonFile(cfg);
}
bool SetBasePath(string? path) {
if (!Directory.Exists(path)) {
return false;
}
configBuilder.SetBasePath(path);
return true;
}
static async Task<int> Main(string[] args) {
var res = Parser.Default.ParseArguments<RunOptions, DumpSecuritiesOptions, DumpBooksOptions>(args);
return await res.MapResult<RunOptions, DumpSecuritiesOptions, DumpBooksOptions, Task<int>>(
_run, SecurityDumper.run, BookDumper.run, errs => Task.FromResult(1));
}
static async Task<int> _run(RunOptions opts) {
Console.WriteLine("Starting spark_api_server... ");
Log.notnull(opts.user);
Log.notnull(opts.password);
var service_ctx = new ServiceContext(new SparkConfigLoader(new SparkConfigLoaderOpts() { ConfigServer = opts.sparkd } ));
var loginService = new SparkdLoginService(service_ctx, new SparkApiCredentials() { User = opts.user, Password = opts.password });
await loginService.LoginAsync();
var userDataPermissions = new UserDataPermissions(loginService);
var sync = new bts.websocket_core.WebsocketDataSync(service_ctx, userDataPermissions);
var gwy = new bts.websocket_core.WebsocketConnectionGateway();
var prms = new WebsocketServerConfig {
DefaultEndPoint = "/",
Host = "titan",
Scheme = "http",
Port = 8080,
KeepAliveIntervalSecs = 0.1,
};
await sync.initAsync(gwy);
var errors = Errors.None;
Log.Api.info("Starting websocket server...");
// try {
// await gwy.start_listening(prms);
// Log.Api.info("Websocket server stopped without error");
// } catch (Exception ex) {
// Log.Api.error($"Websocket server threw ex: {ex}");
// errors |= Errors.Listen;
// }
//REMOVE IN PRODUCTION AND UNCOMMENT ABOVE CODE
var cancellationTokenSource = new CancellationTokenSource();
var listen = Task.Run(async () => {
Log.Api.info("Starting websocket server...");
try {
await gwy.start_listening(prms);
Log.Api.info("Websocket server stopped without error");
} catch (Exception ex) {
Log.Api.error($"Websocket server threw ex: {ex}");
errors |= Errors.Listen;
}
});
// var task = Task.Run(() => {
// while (!cancellationTokenSource.IsCancellationRequested) {
// // Do something that can be interrupted
// }
// }, cancellationTokenSource.Token);
// Console.WriteLine("Press any key to stop the server...");
// Console.ReadKey();
// cancellationTokenSource.Cancel();
await Task.WhenAny(listen);
//UPTILL HERE
return (int)errors;
bool AddJsonFile(string? path) {
if (!File.Exists(path)) {
return false;
}
configBuilder.AddJsonFile(path);
return true;
}
}
static void ConfigureServices(IServiceCollection services, IConfiguration config) {
services.Configure<WebSocketOptions>(config.GetSection("WebSocket"))
.AddLogging(ConfigureLogging)
.AddSpark(config.GetSection("Spark"))
.AddSparkApi(config.GetSection("SparkApi"))
.AddWebSocketServer();
static void ConfigureLogging(ILoggingBuilder loggingBuilder) =>
loggingBuilder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("NToastNotify", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddProvider(new SparkLoggerProvider())
.AddConsole()
.AddDebug();
}
[Flags]
enum Errors {
None = 0,
Listen = 1,
// Add errors as needed
}
@@ -0,0 +1,12 @@
{
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://localhost:8080"
},
"Https": {
"Url": "https://localhost:8443"
}
}
}
}
@@ -0,0 +1,29 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Kestrel": {
"Endpoints": {
"Http": {
"Url": "http://0.0.0.0:8080"
},
"Https": {
"Url": "https://0.0.0.0:8443"
}
}
},
"WebSocketOptions": {
"KeepAliveInterval": "00:02:00",
"ReceiveBufferSize": 4096
},
"SparkApi": {
"Credentials": {
"User": "bts",
"Password": ""
}
}
}
@@ -23,4 +23,9 @@
<ProjectReference Include="..\spark_websocket\spark_websocket.csproj" />
</ItemGroup>
<ItemGroup>
<ConfigurationProfile Include="appsettings.Development.json" />
<ConfigurationProfile Include="appsettings.json" />
</ItemGroup>
</Project>
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using Microsoft.AspNetCore.Http;
namespace bts.websocket_core {
// The implementation of this interface controls all low level
@@ -16,12 +14,10 @@ namespace bts.websocket_core {
event Action<WebsocketClientID>? Disconnected;
event Action<WebsocketIncomingMessage>? MessageReceived;
// This function tells the class to start listening to client connections.
// All the parameters (ports to open, security parameters etc) are
// passed through the WebsocketServerParams arguments
public Task start_listening(WebsocketServerConfig server_params);
// Messages are sent to the client through this
public void send_to_clients(
IEnumerable<WebsocketOutgoingMessage> messages);
Task HandleRequest(HttpContext context);
}
}
@@ -1,89 +0,0 @@
namespace bts.websocket_core;
using bts;
using mbts;
using System;
using System.Reactive.Disposables;
using System.Reactive.Subjects;
/// <summary>
/// Represents websocket client as an I/O model, via the <c>ISubject&lt;TIn, TOut&gt;</c> interface.
/// </summary>
public class WebsocketClient : ISubject<IEnumerable<WebsocketOutgoingMessage>, WebsocketConnectionUpdate>, IConnectableObservable<WebsocketConnectionUpdate>, IDisposable {
readonly WebsocketServerConfig config;
readonly object lockObj = new();
IWebsocketConnectionGateway? gatewayBacking;
public WebsocketClient(WebsocketServerConfig config, IWebsocketConnectionGateway? gateway = null) {
this.config = config;
gatewayBacking = gateway ?? new WebsocketConnectionGateway();
}
IWebsocketConnectionGateway gateway =>
/// The gateway is (only) set to null in <see cref="Dispose"/>
gatewayBacking ?? throw new ObjectDisposedException($"{GetType()}");
public async Task ConnectAsync() {
try {
await gateway.start_listening(config);
} catch (Exception ex) {
Log.Api.error($"Error running {typeof(IWebsocketConnectionGateway)}: {ex}");
throw;
}
}
IDisposable IConnectableObservable<WebsocketConnectionUpdate>.Connect() {
ConnectAsync().ignore();
return this;
}
public IDisposable Subscribe(IObserver<WebsocketConnectionUpdate> observer) {
lock (lockObj) {
gateway.Connected += OnConnected;
gateway.Disconnected += OnDisconnected;
gateway.MessageReceived += OnMessageReceived;
}
return Disposable.Create(Dispose);
void OnConnected(WebsocketClientID id, WebsocketIncomingMessage? message) =>
observer.OnNext(WebsocketConnectionUpdate.Create(
id, new WebsocketConnectNotification(id, message)));
void OnDisconnected(WebsocketClientID id) =>
observer.OnNext(WebsocketConnectionUpdate.Create(
id, new WebsocketDisconnectNotification(id)));
void OnMessageReceived(WebsocketIncomingMessage message) =>
observer.OnNext(WebsocketConnectionUpdate.Create(
message.sender_client_id, message));
void Dispose() {
lock (lockObj) {
gateway.Connected += OnConnected;
gateway.Disconnected += OnDisconnected;
gateway.MessageReceived += OnMessageReceived;
}
}
}
public void Dispose() {
GC.SuppressFinalize(this);
lock (lockObj) {
(gatewayBacking as IDisposable)?.Dispose();
gatewayBacking = null;
}
}
void IObserver<IEnumerable<WebsocketOutgoingMessage>>.OnCompleted() =>
Log.Api.warn($"{GetType()} outgoing message stream completed.");
void IObserver<IEnumerable<WebsocketOutgoingMessage>>.OnError(Exception error) =>
Log.Api.error($"{GetType()} detected error in outgoing message stream: {error}");
void IObserver<IEnumerable<WebsocketOutgoingMessage>>.OnNext(
IEnumerable<WebsocketOutgoingMessage> outMessages) =>
gateway.send_to_clients(outMessages);
}
@@ -1,10 +1,8 @@
using Microsoft.AspNetCore.Http;
using System.Net.WebSockets;
using System.Text;
using System.Collections.Concurrent;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace bts.websocket_core {
public enum MessageType {
@@ -329,8 +327,6 @@ namespace bts.websocket_core {
public event Action<WebsocketClientID>? Disconnected;
public event Action<WebsocketIncomingMessage>? MessageReceived;
private WebApplication? app = null;
private WebsocketServerConfig? _server_params = null;
private WebSocketConnectionStore Connections { get; } = new();
/// <summary>
/// creates a new connections dictionary and a new WebSocketHandler.
@@ -403,62 +399,6 @@ namespace bts.websocket_core {
if (_WebSocketHandler.AddToQueue(id, Tuple.Create(MessageType.Close, "")))
logger.info(" added to que");
}
/// <summary>
/// Starts listening for incoming websocket connections. need to call init before this
/// </summary>
/// <param name="server_params">The parameters for the websocket server includind the URL and endpoint,</param>
public Task start_listening(WebsocketServerConfig server_params) {
// start listening, assert that init has been called already
bts.Log.isnull(_server_params);
bts.Log.isnull(app);
_server_params = server_params;
var builder = WebApplication.CreateBuilder();
var localServerParams = _server_params.Clone();
localServerParams.Scheme = "http";
var localUri = localServerParams.Uri();
builder.WebHost.UseUrls(localUri);
var publicServerParams = _server_params.Clone();
publicServerParams.Scheme = "https";
publicServerParams.Host = "192.168.50.94";
var publicUri = publicServerParams.Uri();
builder.WebHost.UseUrls(publicUri);
// var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddLogging(builder => {
builder.AddFilter("Microsoft", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("System", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddFilter("NToastNotify", Microsoft.Extensions.Logging.LogLevel.Warning)
.AddConsole();
});
// builder.Services.AddCors(options => {
// options.AddPolicy(MyAllowSpecificOrigins,
// policy => policy
// .WithOrigins("http://localhost:3000")
// .AllowAnyHeader()
// .AllowAnyMethod());
// });
app = builder.Build();
app.UseWebSockets(_server_params.get_ws_options());
// app.Use(async (context, next) => {
// context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
// context.Response.Headers.Add("Access-Control-Allow-Headers", "*");
// await next();
// });
app.Map(_server_params.DefaultEndPoint, async context => {
if (context.WebSockets.IsWebSocketRequest) {
using (var ws = await context.WebSockets.AcceptWebSocketAsync()) {
await _WebSocketHandler.ProcessWebSocketConnectionAsync(ws);
}
} else {
context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
}
});
return app.RunAsync();
}
/// <summary>
/// Sends a message to a list of websocket clients.
@@ -472,5 +412,14 @@ namespace bts.websocket_core {
break;
}
}
public async Task HandleRequest(HttpContext context) {
if (!context.WebSockets.IsWebSocketRequest) {
context.Response.StatusCode = (int)System.Net.HttpStatusCode.BadRequest;
return;
}
using var ws = await context.WebSockets.AcceptWebSocketAsync();
await _WebSocketHandler.ProcessWebSocketConnectionAsync(ws);
}
}
}
@@ -0,0 +1,26 @@
namespace Spark.WebSocket.Services;
using bts.websocket_core;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
class SparkApiWebSocketServer : BackgroundService {
readonly WebsocketDataSync dataSync;
readonly WebsocketConnectionGateway gateway;
readonly ILogger<SparkApiWebSocketServer> logger;
public SparkApiWebSocketServer(WebsocketDataSync dataSync, WebsocketConnectionGateway gateway, ILogger<SparkApiWebSocketServer> logger) {
this.dataSync = dataSync;
this.gateway = gateway;
this.logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken) {
logger.LogInformation("Initializing DataSync...");
await dataSync.initAsync(gateway);
}
}
@@ -0,0 +1,23 @@
namespace Spark.WebSocket.Services;
using bts.websocket_core;
using Microsoft.Extensions.DependencyInjection;
using Spark.Api.Services;
public static class SparkWebSocketServices {
public static IServiceCollection AddWebSocketServer(this IServiceCollection services) =>
services.AddSingleton<IUserDataPermissions, UserDataPermissions>()
.AddSingleton<WebsocketConnectionGateway>()
.AddSingleton<IWebsocketConnectionGateway>(sp => sp.GetRequiredService<WebsocketConnectionGateway>())
.AddSingleton<WebsocketDataSync>()
.AddHostedService<SparkApiWebSocketServer>();
// .AddCors(
// options => options.AddPolicy(
// "_myAllowSpecificOrigins",
// policy => policy
// .WithOrigins("http://localhost:3000")
// .AllowAnyHeader()
// .AllowAnyMethod()));
}