namespace spark_api_server { using BCG; using Bts.PubSub; using Bts.Websocket; using bts; using bts.api.core; using CommandLine; using Spark.Api.Server; using System; using System.Reactive.Linq; using System.Threading.Tasks; using System.Threading; class Program { [Flags] enum Errors { None = 0, Listen = 1, // Add errors as needed } static async Task Main(string[] args) { var res = Parser.Default.ParseArguments(args); return await res.MapResult>( _run, SecurityDumper.run, BookDumper.run, errs => Task.FromResult(1)); } static async Task _run(RunOptions opts) { Console.WriteLine("Starting spark_api_server... "); opts.MergeWithConfigFile(); opts.MergeWith(RunOptions.Default()); Log.notnull(opts.user); Log.notnull(opts.password); PubSubConfig.SetGlobalConfig(Log.notnull(opts.PubSub)); var service_ctx = ServiceContext.create(opts.sparkd); await service_ctx.login(opts.user, opts.password); var sync = new bts.websocket_core.WebsocketDataSync(service_ctx); var gwy = new bts.websocket_core.WebsocketConnectionGateway(); var prms = new WebsocketServerConfig { DefaultEndPoint = "/", Host = "titan", Scheme = "http", Port = "8080", KeepAliveIntervalSecs = 0.1, }; gwy.init(sync); 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 vsdTask = Task.Run(() => { Log.Gen.info("Starting ViewStreamDatabase work loop"); var cancellationToken = cancellationTokenSource.Token; while (!cancellationToken.IsCancellationRequested) { ViewStreamDatabase.instance.doWork(); Thread.Sleep(100); } }, cancellationTokenSource.Token); // 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, vsdTask); //UPTILL HERE // These tasks aren't designed to finish naturally. If the code reaches here, it means one // of them threw an exception. Cancel the other task to exit (somewhat) gracefully. cancellationTokenSource.Cancel(); return (int)errors; } } }