feat(server): API v1 with auth, uploads, sync, jobs, render nodes and events
- Security: PBKDF2-SHA512 (210,000 iterations) hashes, opaque bearer tokens stored as SHA-256 with sliding expiry and revocation, HttpOnly/Secure/ SameSite=Strict admin cookie with a session-bound CSRF token, sign-in rate limit and lockout, role/permission metadata on every endpoint, audit log, first-run administrator bootstrap. - Sequences with keyset paging, ETags and settings_version conflicts; sync manifest; frames, proxies, thumbnails and exports streamed with Range. - Chunked resumable uploads with hash short-circuit, quota and disk checks, staging on the archive volume, SHA-256 verification and IArchiveIngest. - Job engine host, jobs API, render nodes with heartbeat timeout and reassignment, WebSocket events, LAN discovery beacon, upload cleanup. - Windows service host over advapi32 (--service, --install-service, --uninstall-service); fails fast without the archive module services. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
56 files changed
+4726
-108
No files matched your search
@@ -0,0 +1,48 @@
|
||||
using System.Net;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// Serves the embedded admin panel at <c>/admin</c>. Requests over plain HTTP from another machine are redirected to
|
||||
/// the HTTPS listener, because the session cookie is <c>Secure</c> (BRIEF §14.2) and would not survive plain HTTP.
|
||||
/// </summary>
|
||||
public static class AdminPanel
|
||||
{
|
||||
public static void Map(WebApplication app, ServerOptions options)
|
||||
{
|
||||
var files = new EmbeddedStaticFiles(typeof(AdminPanel).Assembly, "admin/");
|
||||
var server = app.Services.GetRequiredService<IServer>();
|
||||
app.MapGet("/", () => Results.Redirect("/admin/"));
|
||||
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
|
||||
{
|
||||
if (HttpsLocation(context, options, server) is { } secure)
|
||||
{
|
||||
context.Response.Redirect(secure);
|
||||
return;
|
||||
}
|
||||
// Relative asset URLs need the trailing slash.
|
||||
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
|
||||
{
|
||||
context.Response.Redirect("/admin/");
|
||||
return;
|
||||
}
|
||||
if (!await files.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
});
|
||||
}
|
||||
|
||||
private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
|
||||
{
|
||||
if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null;
|
||||
if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null;
|
||||
foreach (var address in server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [])
|
||||
{
|
||||
if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
|
||||
var port = address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
|
||||
return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
using System.Net;
|
||||
using System.Net.NetworkInformation;
|
||||
using System.Net.Sockets;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.Hosting.Server.Features;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// LAN discovery (BRIEF §14.9, <c>TITANO_DISCOVERY</c>): every few seconds a <see cref="DiscoveryBeacon"/> is broadcast on
|
||||
/// UDP port <see cref="DiscoveryBeacon.Port"/> of every IPv4 network, so clients can offer this server on first run.
|
||||
/// Switching discovery off in the settings stops it without a restart.
|
||||
/// </summary>
|
||||
public sealed class DiscoveryBeaconService(ServerOptions options, ServerState state, IServer server, ILogger<DiscoveryBeaconService> logger) : BackgroundService
|
||||
{
|
||||
private static readonly TimeSpan Interval = TimeSpan.FromSeconds(5);
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
using var udp = new UdpClient(AddressFamily.InterNetwork) { EnableBroadcast = true };
|
||||
var warned = false;
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
if (options.Discovery)
|
||||
{
|
||||
try
|
||||
{
|
||||
await SendOnceAsync(udp, BroadcastTargets(), stoppingToken);
|
||||
}
|
||||
catch (SocketException ex) when (!warned)
|
||||
{
|
||||
warned = true;
|
||||
logger.LogInformation("LAN discovery beacon cannot be sent: {Reason}", ex.Message);
|
||||
}
|
||||
catch (SocketException)
|
||||
{
|
||||
// Already reported once; networks may come and go.
|
||||
}
|
||||
}
|
||||
try
|
||||
{
|
||||
await Task.Delay(Interval, stoppingToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The beacon for the ports Kestrel actually listens on (HTTPS 0 when TLS is terminated elsewhere).</summary>
|
||||
public DiscoveryBeacon CreateBeacon() => new(
|
||||
options.ServerName,
|
||||
SystemEndpoints.Version,
|
||||
BoundPort(Uri.UriSchemeHttp) ?? options.HttpPort,
|
||||
state.TlsFingerprint is null ? 0 : BoundPort(Uri.UriSchemeHttps) ?? options.HttpsPort,
|
||||
state.TlsFingerprint);
|
||||
|
||||
public async Task SendOnceAsync(UdpClient udp, IEnumerable<IPEndPoint> targets, CancellationToken cancellationToken)
|
||||
{
|
||||
var datagram = CreateBeacon().ToBytes();
|
||||
foreach (var target in targets) await udp.SendAsync(datagram, target, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>The limited broadcast address plus the directed broadcast of each IPv4 interface that is up.</summary>
|
||||
private static List<IPEndPoint> BroadcastTargets()
|
||||
{
|
||||
var targets = new List<IPEndPoint> { new(IPAddress.Broadcast, DiscoveryBeacon.Port) };
|
||||
foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
|
||||
{
|
||||
if (nic.OperationalStatus != OperationalStatus.Up || nic.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
|
||||
foreach (var unicast in nic.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (unicast.Address.AddressFamily != AddressFamily.InterNetwork || unicast.IPv4Mask is not { } mask) continue;
|
||||
var address = unicast.Address.GetAddressBytes();
|
||||
var bits = mask.GetAddressBytes();
|
||||
for (var i = 0; i < 4; i++) address[i] = (byte)(address[i] | ~bits[i]);
|
||||
var broadcast = new IPEndPoint(new IPAddress(address), DiscoveryBeacon.Port);
|
||||
if (!targets.Contains(broadcast)) targets.Add(broadcast);
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
private int? BoundPort(string scheme)
|
||||
{
|
||||
var addresses = server.Features.Get<IServerAddressesFeature>()?.Addresses ?? [];
|
||||
foreach (var address in addresses)
|
||||
{
|
||||
if (Uri.TryCreate(address.Replace("[::]", "localhost", StringComparison.Ordinal).Replace("0.0.0.0", "localhost", StringComparison.Ordinal),
|
||||
UriKind.Absolute, out var uri) && uri.Scheme == scheme)
|
||||
return uri.Port;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -38,7 +38,16 @@ public sealed class LoggerSink(ILoggerFactory factory) : ILogSink
|
||||
{
|
||||
public void Write(CoreLogLevel level, string category, string message, Exception? exception)
|
||||
{
|
||||
var logger = factory.CreateLogger("Titano." + category);
|
||||
ILogger logger;
|
||||
try
|
||||
{
|
||||
logger = factory.CreateLogger("Titano." + category);
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// The host that installed this sink has shut down (engine code may outlive it); the line is dropped.
|
||||
return;
|
||||
}
|
||||
var ms = level switch
|
||||
{
|
||||
CoreLogLevel.Trace => MsLogLevel.Trace,
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>
|
||||
/// First middleware of the pipeline: API version and security headers on every response, and the
|
||||
/// <c>{ code, message, details }</c> error body for failures that did not produce one (bad requests, unhandled
|
||||
/// exceptions, unknown methods).
|
||||
/// </summary>
|
||||
public sealed class ResponseMiddleware(RequestDelegate next, ILogger<ResponseMiddleware> logger)
|
||||
{
|
||||
/// <summary>The admin panel loads nothing from elsewhere and is never framed.</summary>
|
||||
private const string AdminPolicy =
|
||||
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'self'; connect-src 'self'; " +
|
||||
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'";
|
||||
|
||||
public async Task InvokeAsync(HttpContext context)
|
||||
{
|
||||
var headers = context.Response.Headers;
|
||||
headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
headers.XContentTypeOptions = "nosniff";
|
||||
headers["Referrer-Policy"] = "no-referrer";
|
||||
var api = context.Request.Path.StartsWithSegments("/api");
|
||||
if (api) headers.CacheControl = "no-store";
|
||||
if (context.Request.Path.StartsWithSegments("/admin"))
|
||||
{
|
||||
headers.ContentSecurityPolicy = AdminPolicy;
|
||||
headers.XFrameOptions = "DENY";
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (BadHttpRequestException ex) when (!context.Response.HasStarted)
|
||||
{
|
||||
await ApiErrors.WriteAsync(context, ex.StatusCode, CodeFor(ex.StatusCode));
|
||||
return;
|
||||
}
|
||||
catch (FormatException) when (!context.Response.HasStarted && context.Request.Query.ContainsKey("cursor"))
|
||||
{
|
||||
// Repositories reject cursors that do not belong to the listing.
|
||||
await ApiErrors.WriteAsync(context, StatusCodes.Status400BadRequest, "invalid_cursor");
|
||||
return;
|
||||
}
|
||||
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
}
|
||||
catch (Exception ex) when (!context.Response.HasStarted)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
|
||||
await ApiErrors.WriteAsync(context, StatusCodes.Status500InternalServerError, "internal");
|
||||
return;
|
||||
}
|
||||
|
||||
var response = context.Response;
|
||||
if (api && response.StatusCode >= 400 && !response.HasStarted && response.ContentType is null)
|
||||
await ApiErrors.WriteAsync(context, response.StatusCode, CodeFor(response.StatusCode));
|
||||
}
|
||||
|
||||
private static string CodeFor(int status) => status switch
|
||||
{
|
||||
StatusCodes.Status400BadRequest => "bad_request",
|
||||
StatusCodes.Status401Unauthorized => "unauthorized",
|
||||
StatusCodes.Status403Forbidden => "forbidden",
|
||||
StatusCodes.Status404NotFound => "not_found",
|
||||
StatusCodes.Status405MethodNotAllowed => "method_not_allowed",
|
||||
StatusCodes.Status413PayloadTooLarge => "too_large",
|
||||
StatusCodes.Status415UnsupportedMediaType => "unsupported_media_type",
|
||||
_ => "internal",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>What <c>Titano.Server</c> was asked to do.</summary>
|
||||
public enum ServerCommand
|
||||
{
|
||||
/// <summary>Run in the console (Docker, Linux, development).</summary>
|
||||
Run,
|
||||
|
||||
/// <summary>Run under the Windows Service Control Manager (the command line the installed service uses).</summary>
|
||||
Service,
|
||||
|
||||
InstallService,
|
||||
UninstallService,
|
||||
|
||||
/// <summary>Probe <c>/health</c> of the local server and exit 0/1 (container health check).</summary>
|
||||
HealthCheck,
|
||||
|
||||
Help,
|
||||
}
|
||||
|
||||
/// <summary>Command-line switches of the server; anything else is passed on to the web host.</summary>
|
||||
public sealed record ServerCommandLine(ServerCommand Command, IReadOnlyList<string> HostArguments, string? Error)
|
||||
{
|
||||
public const string Usage = """
|
||||
Titano Server — time-lapse archive, uploads, jobs and rendering.
|
||||
|
||||
Usage: Titano.Server [--service | --install-service | --uninstall-service | --healthcheck | --help]
|
||||
|
||||
(no switch) run in the console until Ctrl+C
|
||||
--service run under the Windows Service Control Manager
|
||||
--install-service register the "TitanoServer" Windows service (automatic start, LocalSystem)
|
||||
--uninstall-service stop and remove the Windows service
|
||||
--healthcheck exit 0 when the local server answers /health, 1 otherwise
|
||||
|
||||
Configuration: /data/server.json (TITANO_DATA_PATH) overridden by environment variables:
|
||||
TITANO_ARCHIVE_PATH TITANO_DATA_PATH TITANO_SERVER_NAME TITANO_ADMIN_USER TITANO_ADMIN_PASSWORD
|
||||
TITANO_DB (postgres | sqlite | connection string) TITANO_DB_HOST TITANO_DB_PORT TITANO_DB_NAME TITANO_DB_USER
|
||||
TITANO_DB_PASSWORD TITANO_DB_SSLMODE TITANO_HTTP_PORT TITANO_HTTPS_PORT TITANO_TLS_MODE (auto | pem | proxy)
|
||||
TITANO_TLS_CERT TITANO_TLS_KEY TITANO_LANG TITANO_WORKERS TITANO_DISCOVERY
|
||||
""";
|
||||
|
||||
public static ServerCommandLine Parse(IReadOnlyList<string> args)
|
||||
{
|
||||
var command = ServerCommand.Run;
|
||||
var rest = new List<string>();
|
||||
string? error = null;
|
||||
foreach (var arg in args)
|
||||
{
|
||||
ServerCommand? parsed = arg switch
|
||||
{
|
||||
"--service" => ServerCommand.Service,
|
||||
"--install-service" => ServerCommand.InstallService,
|
||||
"--uninstall-service" => ServerCommand.UninstallService,
|
||||
"--healthcheck" => ServerCommand.HealthCheck,
|
||||
"--help" or "-h" or "-?" or "/?" => ServerCommand.Help,
|
||||
_ => null,
|
||||
};
|
||||
if (parsed is not { } switchCommand)
|
||||
{
|
||||
rest.Add(arg);
|
||||
continue;
|
||||
}
|
||||
if (command != ServerCommand.Run && command != switchCommand) error = $"{arg} cannot be combined with another command switch.";
|
||||
command = switchCommand;
|
||||
}
|
||||
return new ServerCommandLine(command, rest, error);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Titano.Data;
|
||||
using Titano.Server.Configuration;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>Opens and migrates the server database at startup (BRIEF §6.1), waiting for a PostgreSQL container that is still starting.</summary>
|
||||
public static class ServerDatabase
|
||||
{
|
||||
private const int Attempts = 10;
|
||||
private static readonly TimeSpan RetryDelay = TimeSpan.FromSeconds(3);
|
||||
|
||||
public static async Task<TitanoDatabase> OpenAsync(ServerOptions options, ILogger logger, CancellationToken cancellationToken)
|
||||
{
|
||||
var settings = options.ToDatabaseOptions();
|
||||
for (var attempt = 1; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
var db = await TitanoDatabase.OpenAsync(settings, cancellationToken).ConfigureAwait(false);
|
||||
logger.LogInformation("Database {Dialect} ready, schema version {Version}", db.Dialect, db.SchemaVersion);
|
||||
return db;
|
||||
}
|
||||
catch (DatabaseConnectionException ex) when (attempt < Attempts)
|
||||
{
|
||||
logger.LogWarning("Database not reachable yet ({Reason}); retry {Attempt} of {Attempts} in {Delay} s",
|
||||
ex.Message, attempt, Attempts - 1, RetryDelay.TotalSeconds);
|
||||
await Task.Delay(RetryDelay, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Engine and version, e.g. "PostgreSQL 17.2" or "SQLite 3.45.1".</summary>
|
||||
public static async Task<string> DescribeAsync(TitanoDatabase db, CancellationToken cancellationToken)
|
||||
{
|
||||
await using var session = await db.Database.OpenAsync(cancellationToken).ConfigureAwait(false);
|
||||
var postgres = db.Dialect == Dialect.Postgres;
|
||||
var version = await session.ScalarAsync<string>(postgres ? "SHOW server_version" : "SELECT sqlite_version()", [], cancellationToken).ConfigureAwait(false);
|
||||
var number = version?.Split(' ', 2)[0] ?? string.Empty;
|
||||
return (postgres ? "PostgreSQL " : "SQLite ") + number;
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,37 @@
|
||||
using Microsoft.AspNetCore.HttpOverrides;
|
||||
using Microsoft.AspNetCore.Server.Kestrel.Core;
|
||||
using Titano.Core.Diagnostics;
|
||||
using Titano.Data;
|
||||
using Titano.Data.Archiving;
|
||||
using Titano.Protocol;
|
||||
using Titano.Server.Api;
|
||||
using Titano.Server.Configuration;
|
||||
using Titano.Server.Events;
|
||||
using Titano.Server.Jobs;
|
||||
using Titano.Server.Security;
|
||||
using Titano.Server.Storage;
|
||||
|
||||
namespace Titano.Server.Hosting;
|
||||
|
||||
/// <summary>Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program and tests).</summary>
|
||||
/// <summary>
|
||||
/// Builds the Titano Server web application from <see cref="ServerOptions"/> (used by Program, the Windows service
|
||||
/// host and tests). The archive module plugs in through <paramref name="configureServices"/> of <see cref="Build"/>:
|
||||
/// it must register <see cref="IArchiveIngest"/> and <see cref="IFrameAssetLocator"/>, and may add
|
||||
/// <see cref="Titano.Data.Jobs.IJobHandler"/>s; the server refuses to start without the first two.
|
||||
/// </summary>
|
||||
public static class ServerHost
|
||||
{
|
||||
public static WebApplication Build(ServerOptions options, string[] args)
|
||||
/// <summary>Request bodies other than upload chunks stay small (BRIEF §14.2 limits).</summary>
|
||||
public const long JsonBodyLimit = 1024 * 1024;
|
||||
|
||||
public static WebApplication Build(ServerOptions options, string[] args, Action<IServiceCollection>? configureServices = null)
|
||||
{
|
||||
Directory.CreateDirectory(options.DataPath);
|
||||
Directory.CreateDirectory(options.LogPath);
|
||||
Directory.CreateDirectory(options.UploadsPath);
|
||||
Directory.CreateDirectory(options.ArchivePath);
|
||||
|
||||
var builder = WebApplication.CreateSlimBuilder(args);
|
||||
var builder = WebApplication.CreateSlimBuilder(new WebApplicationOptions { Args = args, ContentRootPath = AppContext.BaseDirectory });
|
||||
builder.Logging.ClearProviders();
|
||||
builder.Logging.AddSimpleConsole(c => c.SingleLine = true);
|
||||
builder.Logging.AddProvider(new FileLoggerProvider(new FileLogSink(options.LogPath, "server")));
|
||||
@@ -23,26 +39,67 @@ public static class ServerHost
|
||||
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", Microsoft.Extensions.Logging.LogLevel.Information);
|
||||
|
||||
using var bootLoggerFactory = LoggerFactory.Create(l => l.AddSimpleConsole(c => c.SingleLine = true));
|
||||
var certificate = CertificateStore.Load(options, bootLoggerFactory.CreateLogger("Titano.Server"));
|
||||
var state = new ServerState { TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate) };
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
var bootLogger = bootLoggerFactory.CreateLogger("Titano.Server");
|
||||
var certificate = CertificateStore.Load(options, bootLogger);
|
||||
var database = ServerDatabase.OpenAsync(options, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
||||
try
|
||||
{
|
||||
k.AddServerHeader = false;
|
||||
k.Limits.MaxRequestBodySize = options.ChunkSizeBytes + 64 * 1024;
|
||||
k.ListenAnyIP(options.HttpPort);
|
||||
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
|
||||
var archive = ServerArchive.OpenAsync(database, options, TimeProvider.System, CancellationToken.None).GetAwaiter().GetResult();
|
||||
AdminBootstrap.RunAsync(database, options, TimeProvider.System, bootLogger, CancellationToken.None).GetAwaiter().GetResult();
|
||||
var state = new ServerState
|
||||
{
|
||||
l.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
l.UseHttps(certificate);
|
||||
TlsFingerprint = certificate is null ? null : CertificateStore.Fingerprint(certificate),
|
||||
Database = ServerDatabase.DescribeAsync(database, CancellationToken.None).GetAwaiter().GetResult(),
|
||||
};
|
||||
|
||||
builder.WebHost.ConfigureKestrel(k =>
|
||||
{
|
||||
k.AddServerHeader = false;
|
||||
k.Limits.MaxRequestBodySize = JsonBodyLimit;
|
||||
k.Limits.RequestHeadersTimeout = TimeSpan.FromSeconds(30);
|
||||
k.Limits.KeepAliveTimeout = TimeSpan.FromMinutes(2);
|
||||
k.ListenAnyIP(options.HttpPort);
|
||||
if (certificate is not null) k.ListenAnyIP(options.HttpsPort, l =>
|
||||
{
|
||||
l.Protocols = HttpProtocols.Http1AndHttp2;
|
||||
l.UseHttps(certificate);
|
||||
});
|
||||
});
|
||||
});
|
||||
builder.Services.AddSingleton(options);
|
||||
builder.Services.AddSingleton(state);
|
||||
builder.Services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
||||
ConfigureServices(builder.Services, options, state, database, archive);
|
||||
configureServices?.Invoke(builder.Services);
|
||||
|
||||
var app = builder.Build();
|
||||
RequireArchiveModule(app.Services);
|
||||
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
|
||||
ConfigurePipeline(app, options);
|
||||
app.Logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · {Database} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, state.Database, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
app.Lifetime.ApplicationStopping.Register(() => app.Logger.LogInformation("Titano Server stopping"));
|
||||
app.Lifetime.ApplicationStopped.Register(() => database.DisposeAsync().AsTask().GetAwaiter().GetResult());
|
||||
return app;
|
||||
}
|
||||
catch
|
||||
{
|
||||
database.DisposeAsync().AsTask().GetAwaiter().GetResult();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The single composition root of the server's services.</summary>
|
||||
public static void ConfigureServices(IServiceCollection services, ServerOptions options, ServerState state, TitanoDatabase database, ServerArchive archive)
|
||||
{
|
||||
services.AddSingleton(options);
|
||||
services.AddSingleton(state);
|
||||
services.AddSingleton(database);
|
||||
services.AddSingleton(archive);
|
||||
services.AddSingleton(TimeProvider.System);
|
||||
services.ConfigureHttpJsonOptions(j => j.SerializerOptions.TypeInfoResolverChain.Insert(0, ProtocolJson.Default));
|
||||
services.Configure<RouteHandlerOptions>(o => o.ThrowOnBadRequest = true);
|
||||
services.Configure<HostOptions>(o => o.ShutdownTimeout = TimeSpan.FromSeconds(30));
|
||||
if (options.TlsMode == TlsMode.Proxy)
|
||||
{
|
||||
builder.Services.Configure<ForwardedHeadersOptions>(f =>
|
||||
services.Configure<ForwardedHeadersOptions>(f =>
|
||||
{
|
||||
f.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedHost;
|
||||
f.KnownIPNetworks.Clear();
|
||||
@@ -50,49 +107,62 @@ public static class ServerHost
|
||||
});
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
Log.SetSink(new LoggerSink(app.Services.GetRequiredService<ILoggerFactory>()));
|
||||
var logger = app.Logger;
|
||||
logger.LogInformation("Titano Server {Version} · archive {Archive} · data {Data} · TLS {Tls}{Fingerprint}",
|
||||
SystemEndpoints.Version, options.ArchivePath, options.DataPath, options.TlsMode,
|
||||
state.TlsFingerprint is null ? string.Empty : " · SHA-256 " + state.TlsFingerprint);
|
||||
services.AddSingleton<EventHub>();
|
||||
services.AddSingleton<TokenService>();
|
||||
services.AddSingleton<LoginGuard>();
|
||||
services.AddSingleton<AuditLog>();
|
||||
services.AddSingleton<ServerSettingsStore>();
|
||||
services.AddSingleton<UploadStore>();
|
||||
services.AddSingleton<UploadService>();
|
||||
services.AddSingleton<RenderStore>();
|
||||
services.AddSingleton<SequenceJobs>();
|
||||
services.AddSingleton<RenderNodeService>();
|
||||
services.AddSingleton<JobEngineHost>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<JobEngineHost>());
|
||||
services.AddSingleton<RenderNodeMonitor>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<RenderNodeMonitor>());
|
||||
services.AddSingleton<UploadMaintenance>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<UploadMaintenance>());
|
||||
services.AddSingleton<DiscoveryBeaconService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<DiscoveryBeaconService>());
|
||||
}
|
||||
|
||||
private static void ConfigurePipeline(WebApplication app, ServerOptions options)
|
||||
{
|
||||
if (options.TlsMode == TlsMode.Proxy) app.UseForwardedHeaders();
|
||||
app.UseMiddleware<ResponseMiddleware>();
|
||||
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(30) });
|
||||
app.UseRouting();
|
||||
app.UseMiddleware<AuthenticationMiddleware>();
|
||||
|
||||
app.Use(async (context, next) =>
|
||||
AdminPanel.Map(app, options);
|
||||
var api = app.MapGroup("/api/v1");
|
||||
SystemEndpoints.Map(app, api);
|
||||
AuthEndpoints.Map(api);
|
||||
UserEndpoints.Map(api);
|
||||
SequenceEndpoints.Map(api);
|
||||
FileEndpoints.Map(api);
|
||||
UploadEndpoints.Map(api);
|
||||
JobEndpoints.Map(api);
|
||||
NodeEndpoints.Map(api);
|
||||
ArchiveEndpoints.Map(api);
|
||||
AdminEndpoints.Map(api);
|
||||
EventEndpoints.Map(api);
|
||||
app.MapFallback("/api/{**path}", (HttpContext context) => ApiErrors.NotFound(context)).AllowAnonymousCaller();
|
||||
}
|
||||
|
||||
/// <summary>Fails fast when the archive module's services are missing (the server would accept uploads it cannot commit).</summary>
|
||||
private static void RequireArchiveModule(IServiceProvider services)
|
||||
{
|
||||
var registry = services.GetRequiredService<IServiceProviderIsService>();
|
||||
var missing = new List<string>();
|
||||
if (!registry.IsService(typeof(IArchiveIngest))) missing.Add($"{typeof(IArchiveIngest).FullName} (commits verified uploads into the archive layout)");
|
||||
if (!registry.IsService(typeof(IFrameAssetLocator))) missing.Add($"{typeof(IFrameAssetLocator).FullName} (finds proxies and thumbnails)");
|
||||
if (missing.Count > 0)
|
||||
{
|
||||
context.Response.Headers[ApiVersion.Header] = ApiVersion.Current.ToString(System.Globalization.CultureInfo.InvariantCulture);
|
||||
context.Response.Headers.XContentTypeOptions = "nosniff";
|
||||
context.Response.Headers["Referrer-Policy"] = "no-referrer";
|
||||
try
|
||||
{
|
||||
await next(context);
|
||||
}
|
||||
catch (Exception ex) when (!context.Response.HasStarted && ex is not OperationCanceledException)
|
||||
{
|
||||
logger.LogError(ex, "Unhandled error on {Method} {Path}", context.Request.Method, context.Request.Path);
|
||||
context.Response.StatusCode = StatusCodes.Status500InternalServerError;
|
||||
await context.Response.WriteAsJsonAsync(new ApiError("internal", "Unexpected server error."), ProtocolJson.Default.ApiError);
|
||||
}
|
||||
});
|
||||
|
||||
var admin = new EmbeddedStaticFiles(typeof(ServerHost).Assembly, "admin/");
|
||||
app.MapGet("/", () => Results.Redirect("/admin/"));
|
||||
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
|
||||
{
|
||||
// Relative asset URLs need the trailing slash.
|
||||
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
|
||||
{
|
||||
context.Response.Redirect("/admin/");
|
||||
return;
|
||||
}
|
||||
if (!await admin.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
|
||||
});
|
||||
|
||||
SystemEndpoints.Map(app, options, state);
|
||||
|
||||
app.MapFallback("/api/{**path}", () => Results.Json(new ApiError("not_found", "No such endpoint."), ProtocolJson.Default.ApiError, statusCode: 404));
|
||||
app.Lifetime.ApplicationStopping.Register(() => logger.LogInformation("Titano Server stopping"));
|
||||
return app;
|
||||
throw new InvalidOperationException(
|
||||
"Titano Server cannot start: no implementation is registered for " + string.Join(" and ", missing) +
|
||||
". Register them in the services callback of ServerHost.Build.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using Titano.Core.Localization;
|
||||
using static Titano.Server.Hosting.Windows.ServiceNative;
|
||||
|
||||
namespace Titano.Server.Hosting.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// <c>--install-service</c> / <c>--uninstall-service</c>: registers the server with the Service Control Manager
|
||||
/// (automatic start, LocalSystem, command line <c>"…\Titano.Server.exe" --service</c>) or stops and removes it.
|
||||
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static unsafe class ServiceInstaller
|
||||
{
|
||||
private const string DisplayName = "Titano Server";
|
||||
|
||||
public static void Install()
|
||||
{
|
||||
var manager = OpenSCManagerW(null, null, ScManagerConnect | ScManagerCreateService);
|
||||
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
try
|
||||
{
|
||||
var service = CreateServiceW(manager, WindowsServiceHost.ServiceName, DisplayName, ServiceAllAccess, ServiceWin32OwnProcess, ServiceAutoStart,
|
||||
ServiceErrorNormal, CommandLine(), null, 0, null, null, null);
|
||||
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
try
|
||||
{
|
||||
fixed (char* text = Loc.L("Server.Service.Description"))
|
||||
{
|
||||
var description = new ServiceDescription { Description = text };
|
||||
ChangeServiceConfig2W(service, ServiceConfigDescription, &description);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(service);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(manager);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Uninstall()
|
||||
{
|
||||
var manager = OpenSCManagerW(null, null, ScManagerConnect);
|
||||
if (manager == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
try
|
||||
{
|
||||
var service = OpenServiceW(manager, WindowsServiceHost.ServiceName, Delete | ServiceStop | ServiceQueryStatus);
|
||||
if (service == 0) throw new Win32Exception(Marshal.GetLastPInvokeError());
|
||||
try
|
||||
{
|
||||
ServiceStatus status;
|
||||
if (!ControlService(service, ControlStop, &status) && Marshal.GetLastPInvokeError() is var stopError && stopError != ErrorServiceNotActive)
|
||||
throw new Win32Exception(stopError);
|
||||
if (!DeleteService(service) && Marshal.GetLastPInvokeError() is var deleteError && deleteError != ErrorServiceMarkedForDelete)
|
||||
throw new Win32Exception(deleteError);
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(service);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
CloseServiceHandle(manager);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The service's command line: this executable (or <c>dotnet</c> plus this assembly) with <c>--service</c>.</summary>
|
||||
private static string CommandLine()
|
||||
{
|
||||
var process = Environment.ProcessPath ?? throw new InvalidOperationException("The executable path is unknown.");
|
||||
var assembly = typeof(ServiceInstaller).Assembly.Location;
|
||||
return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase)
|
||||
? $"\"{process}\" \"{assembly}\" --service"
|
||||
: $"\"{process}\" --service";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
|
||||
namespace Titano.Server.Hosting.Windows;
|
||||
|
||||
/// <summary>Service Control Manager functions of advapi32 (no Windows-only package needed).</summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
internal static unsafe partial class ServiceNative
|
||||
{
|
||||
public const uint ServiceWin32OwnProcess = 0x10;
|
||||
public const uint ServiceAutoStart = 2;
|
||||
public const uint ServiceErrorNormal = 1;
|
||||
public const uint ScManagerConnect = 0x1;
|
||||
public const uint ScManagerCreateService = 0x2;
|
||||
public const uint ServiceAllAccess = 0xF01FF;
|
||||
public const uint ServiceQueryStatus = 0x4;
|
||||
public const uint ServiceStop = 0x20;
|
||||
public const uint Delete = 0x10000;
|
||||
public const uint ServiceConfigDescription = 1;
|
||||
|
||||
public const uint ControlStop = 1;
|
||||
public const uint ControlInterrogate = 4;
|
||||
public const uint ControlShutdown = 5;
|
||||
|
||||
public const int ErrorFailedServiceControllerConnect = 1063;
|
||||
public const int ErrorServiceNotActive = 1062;
|
||||
public const int ErrorServiceMarkedForDelete = 1072;
|
||||
public const uint NoError = 0;
|
||||
public const uint ErrorCallNotImplemented = 120;
|
||||
public const uint ErrorExceptionInService = 1064;
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct ServiceStatus
|
||||
{
|
||||
public uint ServiceType;
|
||||
public uint CurrentState;
|
||||
public uint ControlsAccepted;
|
||||
public uint Win32ExitCode;
|
||||
public uint ServiceSpecificExitCode;
|
||||
public uint CheckPoint;
|
||||
public uint WaitHint;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct ServiceTableEntry
|
||||
{
|
||||
public char* ServiceName;
|
||||
public delegate* unmanaged[Stdcall]<uint, char**, void> ServiceProc;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct ServiceDescription
|
||||
{
|
||||
public char* Description;
|
||||
}
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool StartServiceCtrlDispatcherW(ServiceTableEntry* table);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
public static partial nint RegisterServiceCtrlHandlerExW(string serviceName, delegate* unmanaged[Stdcall]<uint, uint, nint, nint, uint> handler, nint context);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool SetServiceStatus(nint statusHandle, ServiceStatus* status);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
public static partial nint OpenSCManagerW(string? machineName, string? databaseName, uint desiredAccess);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
public static partial nint CreateServiceW(nint manager, string serviceName, string displayName, uint desiredAccess, uint serviceType, uint startType,
|
||||
uint errorControl, string binaryPathName, string? loadOrderGroup, nint tagId, string? dependencies, string? serviceStartName, string? password);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
|
||||
public static partial nint OpenServiceW(nint manager, string serviceName, uint desiredAccess);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool ChangeServiceConfig2W(nint service, uint infoLevel, void* info);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool ControlService(nint service, uint control, ServiceStatus* status);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool DeleteService(nint service);
|
||||
|
||||
[LibraryImport("advapi32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static partial bool CloseServiceHandle(nint handle);
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
namespace Titano.Server.Hosting.Windows;
|
||||
|
||||
/// <summary>SERVICE_STATUS.dwCurrentState values the server reports.</summary>
|
||||
public enum ServiceState : uint
|
||||
{
|
||||
Stopped = 1,
|
||||
StartPending = 2,
|
||||
StopPending = 3,
|
||||
Running = 4,
|
||||
}
|
||||
|
||||
/// <summary>One status report for <c>SetServiceStatus</c>.</summary>
|
||||
public readonly record struct ServiceStatusReport(ServiceState State, uint ControlsAccepted, uint CheckPoint, uint WaitHintMilliseconds, uint ExitCode);
|
||||
|
||||
/// <summary>
|
||||
/// The service's state machine and the rules of SERVICE_STATUS: no controls are accepted while pending, the check point
|
||||
/// grows with every pending report and is zero otherwise, a stopped service carries its exit code.
|
||||
/// </summary>
|
||||
public sealed class ServiceStatusTracker
|
||||
{
|
||||
public const uint AcceptStop = 0x1;
|
||||
public const uint AcceptShutdown = 0x4;
|
||||
|
||||
private readonly Lock _gate = new();
|
||||
private uint _checkPoint;
|
||||
|
||||
public ServiceStatusReport Current { get; private set; } = new(ServiceState.Stopped, 0, 0, 0, 0);
|
||||
|
||||
public ServiceStatusReport StartPending(uint waitHintMilliseconds) => Pending(ServiceState.StartPending, waitHintMilliseconds, ServiceState.Stopped, ServiceState.StartPending);
|
||||
|
||||
public ServiceStatusReport Running()
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Require(ServiceState.StartPending);
|
||||
_checkPoint = 0;
|
||||
return Current = new ServiceStatusReport(ServiceState.Running, AcceptStop | AcceptShutdown, 0, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Stopping from start-up or from running; repeating it reports progress (a higher check point).</summary>
|
||||
public ServiceStatusReport StopPending(uint waitHintMilliseconds) =>
|
||||
Pending(ServiceState.StopPending, waitHintMilliseconds, ServiceState.StartPending, ServiceState.Running, ServiceState.StopPending);
|
||||
|
||||
public ServiceStatusReport Stopped(uint exitCode)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
_checkPoint = 0;
|
||||
return Current = new ServiceStatusReport(ServiceState.Stopped, 0, 0, 0, exitCode);
|
||||
}
|
||||
}
|
||||
|
||||
private ServiceStatusReport Pending(ServiceState state, uint waitHintMilliseconds, params ServiceState[] from)
|
||||
{
|
||||
lock (_gate)
|
||||
{
|
||||
Require(from);
|
||||
_checkPoint = Current.State == state ? _checkPoint + 1 : 1;
|
||||
return Current = new ServiceStatusReport(state, 0, _checkPoint, waitHintMilliseconds, 0);
|
||||
}
|
||||
}
|
||||
|
||||
private void Require(params ServiceState[] allowed)
|
||||
{
|
||||
if (!allowed.Contains(Current.State)) throw new InvalidOperationException($"A service cannot go from {Current.State} to that state.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Runtime.Versioning;
|
||||
using static Titano.Server.Hosting.Windows.ServiceNative;
|
||||
|
||||
namespace Titano.Server.Hosting.Windows;
|
||||
|
||||
/// <summary>
|
||||
/// Runs the server as a Windows service with the SCM API directly (StartServiceCtrlDispatcherW,
|
||||
/// RegisterServiceCtrlHandlerExW, SetServiceStatus). Stop and shutdown requests stop the web host gracefully: running
|
||||
/// jobs keep their checkpoints and resume at the next start.
|
||||
/// </summary>
|
||||
[SupportedOSPlatform("windows")]
|
||||
public static class WindowsServiceHost
|
||||
{
|
||||
public const string ServiceName = "TitanoServer";
|
||||
private const uint StartWaitHint = 60_000;
|
||||
private const uint StopWaitHint = 35_000;
|
||||
|
||||
private static readonly ServiceStatusTracker Status = new();
|
||||
private static Func<WebApplication>? _build;
|
||||
private static WebApplication? _app;
|
||||
private static nint _statusHandle;
|
||||
|
||||
/// <summary>
|
||||
/// Hands the process to the Service Control Manager and returns when the service has stopped. False when the
|
||||
/// process was not started by the SCM (for example from a console).
|
||||
/// </summary>
|
||||
public static unsafe bool Run(Func<WebApplication> build)
|
||||
{
|
||||
_build = build;
|
||||
fixed (char* name = ServiceName)
|
||||
{
|
||||
var table = stackalloc ServiceTableEntry[2];
|
||||
table[0] = new ServiceTableEntry { ServiceName = name, ServiceProc = &ServiceMain };
|
||||
table[1] = default;
|
||||
if (StartServiceCtrlDispatcherW(table)) return true;
|
||||
}
|
||||
var error = Marshal.GetLastPInvokeError();
|
||||
if (error == ErrorFailedServiceControllerConnect) return false;
|
||||
throw new Win32Exception(error);
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
|
||||
private static unsafe void ServiceMain(uint argc, char** argv)
|
||||
{
|
||||
_statusHandle = RegisterServiceCtrlHandlerExW(ServiceName, &Handler, 0);
|
||||
if (_statusHandle == 0) return;
|
||||
Report(Status.StartPending(StartWaitHint));
|
||||
try
|
||||
{
|
||||
_app = _build!();
|
||||
_app.StartAsync().GetAwaiter().GetResult();
|
||||
Report(Status.Running());
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine(ex);
|
||||
Report(Status.Stopped(ErrorExceptionInService));
|
||||
}
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])]
|
||||
private static unsafe uint Handler(uint control, uint eventType, nint eventData, nint context)
|
||||
{
|
||||
switch (control)
|
||||
{
|
||||
case ControlStop or ControlShutdown:
|
||||
if (Status.Current.State is ServiceState.Running or ServiceState.StartPending)
|
||||
{
|
||||
Report(Status.StopPending(StopWaitHint));
|
||||
// The handler must return at once; the host stops on the thread pool.
|
||||
_ = Task.Run(StopAsync);
|
||||
}
|
||||
return NoError;
|
||||
case ControlInterrogate:
|
||||
Report(Status.Current);
|
||||
return NoError;
|
||||
default:
|
||||
return ErrorCallNotImplemented;
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task StopAsync()
|
||||
{
|
||||
uint exitCode = 0;
|
||||
try
|
||||
{
|
||||
if (_app is { } app)
|
||||
{
|
||||
await app.StopAsync();
|
||||
await app.DisposeAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine(ex);
|
||||
exitCode = ErrorExceptionInService;
|
||||
}
|
||||
Report(Status.Stopped(exitCode));
|
||||
}
|
||||
|
||||
private static unsafe void Report(ServiceStatusReport report)
|
||||
{
|
||||
var status = new ServiceStatus
|
||||
{
|
||||
ServiceType = ServiceWin32OwnProcess,
|
||||
CurrentState = (uint)report.State,
|
||||
ControlsAccepted = report.ControlsAccepted,
|
||||
Win32ExitCode = report.ExitCode,
|
||||
CheckPoint = report.CheckPoint,
|
||||
WaitHint = report.WaitHintMilliseconds,
|
||||
};
|
||||
SetServiceStatus(_statusHandle, &status);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user