refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
CI / Build and test (push) Successful in 8m14s
CI / Windows tests and installer (push) Skipped
CI / YAML check (push) Successful in 7s
Release / Build, test and publish (push) Successful in 13m19s
CI / PostgreSQL 16 integration (push) Successful in 4m49s
CI / PostgreSQL 17 integration (push) Successful in 5m28s
CI / Docker image (push) Successful in 53s
Release / Server image (push) Failing after 10s

The owner renamed the product and moved the repository to the self-hosted
Gitea (https://gitea.encke-hake.ts.net/BalboSoft/Chronos) for more control,
and asked for Actions and a first automatic release with the server package
and the Windows exe (docs/requests/2026-10-23-chronos-gitea.md).

- Chronos everywhere: a byte-exact rename of contents and paths, then a
  per-language review of the forms the old name's ending had dictated.
- Gitea instead of GitHub: the update check, licence, issue and support
  links read ChronosReleasesUrl; the update check takes the highest stable
  version, offers a pre-release build its final release and reports a
  repository it cannot see as a failed check. EULA, security policy and
  Gitea issue forms live at the repository root.
- Gitea Actions for the Linux act_runner (.gitea/workflows): CI, release,
  nightly image and performance gates in the .NET SDK container with git
  checkout and the system SQLite. The release cross-compiles the Windows
  programs, checks their icon, version and DPI manifest, packs installers
  and zips, publishes the Gitea release and pushes the server image
  (REGISTRY_TOKEN). Windows-only tests run in an opt-in job on a Windows
  runner (WINDOWS_RUNNER).
- New Chronos.Tools commands: zip, gitea-release, postgres-ci (replaces the
  docker-exec script, which Gitea's service containers do not allow; the
  throw-away server runs without durability) and pe-check.
- Timed tests take their budget from TestTiming (CHRONOS_TEST_TIME_FACTOR,
  3 on the shared runner; the weekly performance gates keep theirs).

BREAKING CHANGE: programs, settings, data folders, file types, environment
variables and the Docker image use the new name; nothing is migrated from
Titano, which never had a release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Alberto Balbo <alberto.balbo.96@gmail.com>
This commit was merged in pull request #6.
This commit is contained in:
Alby96andClaude Opus 5.5 authored and Alby96 committed 2026-10-23 12:45:18 +02:00
1 parent c99842cc86
commit f2b58522b9
1801 files changed
+11804 -10676

No files matched your search

@@ -0,0 +1,58 @@
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.Server.Hosting.Windows;
/// <summary>
/// Errors of the Windows service in the Application event log (source <c>ChronosServer</c>). A service has no console,
/// and a start-up failure comes before the server's log file exists (the data folder that holds it may be the very
/// thing refused), so Event Viewer is where an operator finds why the service stopped. The source is not registered
/// with a message file: Event Viewer says it found no description for the event, then shows the text whole.
/// </summary>
internal static unsafe class ServiceEventLog
{
public const uint StartFailed = 1;
public const uint StopFailed = 2;
/// <summary>ReportEvent takes at most 31,839 characters per string.</summary>
public const int MaxLength = 31_839;
/// <summary>
/// The event text: <paramref name="what"/> and the reason the server gave (the entry to check, for a refused data
/// folder), then the exception for a bug report; cut to <see cref="MaxLength"/>.
/// </summary>
public static string Describe(string what, Exception exception)
{
var text = $"{what} {exception.Message}{Environment.NewLine}{Environment.NewLine}{exception}";
if (text.Length <= MaxLength) return text;
var cut = MaxLength - 1;
// Never half a surrogate pair.
if (char.IsHighSurrogate(text[cut - 1])) cut--;
return string.Concat(text.AsSpan(0, cut), "…");
}
/// <summary>Writes an error event; false when the event log could not be written (the console still gets it).</summary>
[SupportedOSPlatform("windows")]
public static bool Error(uint eventId, string text) => Error(WindowsServiceHost.ServiceName, eventId, text);
/// <summary><see cref="Error(uint, string)"/> as <paramref name="sourceName"/> (tests write as their own source).</summary>
[SupportedOSPlatform("windows")]
internal static bool Error(string sourceName, uint eventId, string text)
{
var source = RegisterEventSourceW(null, sourceName);
if (source == 0) return false;
try
{
fixed (char* chars = text.Length <= MaxLength ? text : text[..MaxLength])
{
var strings = stackalloc char*[1];
strings[0] = chars;
return ReportEventW(source, EventLogErrorType, 0, eventId, 0, 1, 0, strings, null);
}
}
finally
{
DeregisterEventSource(source);
}
}
}
@@ -0,0 +1,160 @@
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using Chronos.Core.Localization;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.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>"…\Chronos.Server.exe" --service</c>) or stops and removes it.
/// Both need an elevated prompt; failures surface as <see cref="Win32Exception"/>. A LocalSystem service runs whatever
/// sits at its image path, so it is registered only from a copy under Program Files that nobody but SYSTEM,
/// Administrators and TrustedInstaller can change: a per-user install or a zip unpacked elsewhere would hand SYSTEM to
/// any program of that user. Otherwise <see cref="Install"/> refuses with <see cref="InvalidOperationException"/>.
/// </summary>
[SupportedOSPlatform("windows")]
public static unsafe class ServiceInstaller
{
private const string DisplayName = "Chronos Server";
/// <summary>TrustedInstaller, the owner of Windows' own files under Program Files.</summary>
private static readonly SecurityIdentifier TrustedInstaller = new("S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464");
/// <exception cref="InvalidOperationException">This copy is not in a folder that only administrators can change.</exception>
public static void Install()
{
if (UnsafeLocation() is { } problem) throw new InvalidOperationException(problem);
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>
/// Why this copy may not be registered, as a localized sentence, or null when it may: the program folder (and, when
/// run by <c>dotnet</c>, the host's folder) must be inside Program Files and changeable only by administrators.
/// </summary>
internal static string? UnsafeLocation()
{
var program = Path.TrimEndingDirectorySeparator(AppContext.BaseDirectory);
if (!IsUnderProgramFiles(program)) return Loc.L("Server.Service.NotProgramFiles", program);
if (FindChangeable(new DirectoryInfo(program), recursive: true) is { } open) return Loc.L("Server.Service.Writable", open);
// Under dotnet the host runs as SYSTEM too; its folder is checked without the thousands of framework files below it.
if (Environment.ProcessPath is { } process && Path.GetDirectoryName(process) is { } host
&& !string.Equals(Path.TrimEndingDirectorySeparator(host), program, StringComparison.OrdinalIgnoreCase))
{
if (!IsUnderProgramFiles(host)) return Loc.L("Server.Service.NotProgramFiles", host);
if (FindChangeable(new DirectoryInfo(host), recursive: false) is { } hostOpen) return Loc.L("Server.Service.Writable", hostOpen);
}
return null;
}
/// <summary>True for a path inside <c>%ProgramFiles%</c> or <c>%ProgramFiles(x86)%</c> (not the folder itself).</summary>
internal static bool IsUnderProgramFiles(string path)
{
var full = Path.GetFullPath(path);
foreach (var folder in new[] { Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolder.ProgramFilesX86 })
{
var root = Environment.GetFolderPath(folder);
if (root.Length > 0 && full.StartsWith(Path.TrimEndingDirectorySeparator(root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
/// <summary>
/// The first of the folder, its files and (when recursive) its subfolders whose ACL lets an account other than
/// SYSTEM, Administrators, TrustedInstaller or the registering administrator change it; null when there is none.
/// </summary>
internal static string? FindChangeable(DirectoryInfo folder, bool recursive) => FindChangeable(folder, recursive, TrustedAccounts());
private static string? FindChangeable(DirectoryInfo folder, bool recursive, HashSet<SecurityIdentifier> trusted)
{
if (DataFolderAccess.IsChangeableByOthers(folder.GetAccessControl(), trusted, checkOwner: false)) return folder.FullName;
foreach (var file in folder.EnumerateFiles())
{
if (DataFolderAccess.IsChangeableByOthers(file.GetAccessControl(), trusted, checkOwner: false)) return file.FullName;
}
if (!recursive) return null;
foreach (var child in folder.EnumerateDirectories())
{
if (FindChangeable(child, recursive: true, trusted) is { } path) return path;
}
return null;
}
private static HashSet<SecurityIdentifier> TrustedAccounts()
{
var trusted = new HashSet<SecurityIdentifier>
{
new(WellKnownSidType.LocalSystemSid, null),
new(WellKnownSidType.BuiltinAdministratorsSid, null),
TrustedInstaller,
};
// Registering needs an elevated prompt, so the account doing it is an administrator; setups often name it.
using var identity = WindowsIdentity.GetCurrent();
if (identity.User is { } user && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)) trusted.Add(user);
return trusted;
}
/// <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.");
// Assembly.Location is empty in a single-file app; under dotnet the entry assembly sits in the base directory.
var assembly = Path.Combine(AppContext.BaseDirectory, typeof(ServiceInstaller).Assembly.GetName().Name + ".dll");
return Path.GetFileNameWithoutExtension(process).Equals("dotnet", StringComparison.OrdinalIgnoreCase)
? $"\"{process}\" \"{assembly}\" --service"
: $"\"{process}\" --service";
}
}
@@ -0,0 +1,107 @@
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace Chronos.Server.Hosting.Windows;
/// <summary>Service Control Manager and event log 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;
public const ushort EventLogErrorType = 0x1;
[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);
[LibraryImport("advapi32.dll", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)]
public static partial nint RegisterEventSourceW(string? uncServerName, string sourceName);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ReportEventW(nint eventLog, ushort type, ushort category, uint eventId, nint userSid, ushort stringCount, uint dataSize,
char** strings, void* rawData);
[LibraryImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool DeregisterEventSource(nint eventLog);
}
@@ -0,0 +1,68 @@
namespace Chronos.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,121 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using static Chronos.Server.Hosting.Windows.ServiceNative;
namespace Chronos.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. A failure to start or stop goes to the Application event
/// log (<see cref="ServiceEventLog"/>), since a service has no console.
/// </summary>
[SupportedOSPlatform("windows")]
public static class WindowsServiceHost
{
public const string ServiceName = "ChronosServer";
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)
{
// A refused data folder or server.json says which entry to check; the SCM itself records only error 1064.
Console.Error.WriteLine(ex);
ServiceEventLog.Error(ServiceEventLog.StartFailed, ServiceEventLog.Describe("Chronos Server did not start:", 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);
ServiceEventLog.Error(ServiceEventLog.StopFailed, ServiceEventLog.Describe("Chronos Server did not stop cleanly:", 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);
}
}