using Bts.DataStreamCore; using BCG; using System; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; const int Port = 5079; var prefix = $"http://localhost:{Port}/"; var listener = new HttpListener(); listener.Prefixes.Add(prefix); var config = ConfigLoader.load(); var persistenceHelper = new PeristenceHelper(); var pub_sub_sync = new PubSubSync(persistenceHelper.database_path, config.pub_sub); var callHandler = new PersistenceCallHandler(persistenceHelper, pub_sub_sync); Console.WriteLine("PersistenceServer starting."); Console.WriteLine($"Listening on {prefix}"); Console.WriteLine($"DataStreamCore loaded from: {typeof(IDataPacket).Assembly.FullName}"); Console.WriteLine("Press Ctrl+C to stop."); var shutdown = new CancellationTokenSource(); Console.CancelKeyPress += (_, eventArgs) => { eventArgs.Cancel = true; Console.WriteLine("Shutdown requested."); shutdown.Cancel(); if (listener.IsListening) { listener.Stop(); } }; try { pub_sub_sync.publish_all_tables(); listener.Start(); await RunAsync(listener, callHandler, shutdown.Token); return 0; } catch (HttpListenerException ex) when (shutdown.IsCancellationRequested) { Console.WriteLine($"Listener stopped: {ex.Message}"); return 0; } catch (Exception ex) { Console.Error.WriteLine($"PersistenceServer crashed: {ex}"); return 1; } finally { listener.Close(); } static async Task RunAsync( HttpListener listener, PersistenceCallHandler callHandler, CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { HttpListenerContext context; try { context = await listener.GetContextAsync(); } catch (HttpListenerException) when (cancellationToken.IsCancellationRequested) { break; } catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested) { break; } _ = Task.Run(() => HandleRequestAsync(context, callHandler, cancellationToken), cancellationToken); } } static async Task HandleRequestAsync( HttpListenerContext context, PersistenceCallHandler callHandler, CancellationToken cancellationToken) { var request = context.Request; var response = context.Response; try { var body = await ReadBodyAsync(request, cancellationToken); callHandler.Handle(request, body); var responseText = $$""" {"status":"ok","method":"{{request.HttpMethod}}","path":"{{request.RawUrl ?? "/"}}"} """; var bytes = Encoding.UTF8.GetBytes(responseText); response.StatusCode = (int)HttpStatusCode.OK; response.ContentType = "application/json"; response.ContentEncoding = Encoding.UTF8; response.ContentLength64 = bytes.LongLength; await response.OutputStream.WriteAsync(bytes, cancellationToken); } catch (Exception ex) { Console.Error.WriteLine($"Request handling failed: {ex}"); response.StatusCode = (int)HttpStatusCode.InternalServerError; } finally { response.OutputStream.Close(); response.Close(); } } static async Task ReadBodyAsync(HttpListenerRequest request, CancellationToken cancellationToken) { if (!request.HasEntityBody) { return string.Empty; } using var reader = new StreamReader( request.InputStream, request.ContentEncoding ?? Encoding.UTF8, detectEncodingFromByteOrderMarks: true, leaveOpen: true); return await reader.ReadToEndAsync(cancellationToken); }