Files
Chronos/src/Chronos.App/Infrastructure/SingleInstance.cs
T
Alby96andClaude Opus 5.5 f2b58522b9
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
refactor!: rename Titano to Chronos and move CI and releases to Gitea (#6)
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>
2026-10-23 12:45:18 +02:00

253 lines
9.6 KiB
C#

using System.Diagnostics;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using Chronos.Core.Diagnostics;
namespace Chronos.App.Infrastructure;
/// <summary>
/// One Chronos per data folder in a Windows session (two would share one index and job engine): a named mutex marks
/// the running instance, and a later launch (a double-clicked <c>.chronos</c> file, the Start menu) hands its file
/// arguments over a named pipe (current user only), lets the running window come to the front and exits. The running
/// instance listens from the moment it holds the mutex, keeping what arrives until its window can take it, and stops
/// listening as soon as it starts closing; a launch that gets no answer waits for it to exit and starts in its place.
/// Same protocol as the Uploader's, kept per program so neither depends on the other.
/// </summary>
public sealed partial class SingleInstance : IDisposable
{
private const string Header = "CHRONOS/1";
private const int MaxMessageBytes = 1 << 20;
private const int AnyProcess = -1;
private readonly Mutex _mutex;
private readonly string _pipeName;
private readonly CancellationTokenSource _stop = new();
private readonly Lock _gate = new();
private readonly Queue<IReadOnlyList<string>> _waiting = new();
private Action<IReadOnlyList<string>>? _received;
private Task? _listening;
private bool _disposed;
private SingleInstance(Mutex mutex, string pipeName)
{
_mutex = mutex;
_pipeName = pipeName;
}
/// <summary>
/// The instance guard for <paramref name="dataDirectory"/>, or null when another Chronos already uses it in this
/// session (also one running with administrator rights, whose mutex this launch may not even open).
/// </summary>
public static SingleInstance? TryAcquire(string dataDirectory)
{
Mutex mutex;
bool createdNew;
try
{
mutex = new Mutex(initiallyOwned: true, MutexName(dataDirectory), out createdNew);
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Chronos runs with administrator rights on this data folder: {ex.Message}");
return null;
}
if (createdNew) return new SingleInstance(mutex, PipeName(dataDirectory));
mutex.Dispose();
return null;
}
/// <summary>
/// Waits up to <paramref name="timeout"/> for the Chronos running on <paramref name="dataDirectory"/> to exit (while
/// it closes it no longer answers hand-overs), then becomes the running instance; null when it still runs, or runs
/// with administrator rights.
/// </summary>
public static SingleInstance? WaitForTurn(string dataDirectory, TimeSpan timeout)
{
Mutex mutex;
try
{
mutex = new Mutex(initiallyOwned: false, MutexName(dataDirectory));
}
catch (UnauthorizedAccessException ex)
{
Log.Info("instance", $"Chronos runs with administrator rights on this data folder: {ex.Message}");
return null;
}
try
{
if (mutex.WaitOne(timeout)) return new SingleInstance(mutex, PipeName(dataDirectory));
}
catch (AbandonedMutexException)
{
// The other Chronos ended without releasing it (it crashed): this thread owns it now.
Log.Warning("instance", "The previous Chronos ended without closing");
return new SingleInstance(mutex, PipeName(dataDirectory));
}
mutex.Dispose();
return null;
}
/// <summary>
/// Sends <paramref name="args"/> (absolute paths; empty = just show the window) to the Chronos running on
/// <paramref name="dataDirectory"/>; false when it could not be reached.
/// </summary>
public static bool HandOver(string dataDirectory, IReadOnlyList<string> args)
{
// This launch came from the user, so it may give the running window the right to come to the front.
AllowSetForegroundWindow(AnyProcess);
try
{
using var pipe = new NamedPipeClientStream(".", PipeName(dataDirectory), PipeDirection.Out, PipeOptions.CurrentUserOnly);
pipe.Connect(3000);
pipe.Write(Encode(args));
pipe.Flush();
return true;
}
catch (Exception ex) when (ex is IOException or TimeoutException or UnauthorizedAccessException)
{
Log.Warning("instance", "Could not reach the running Chronos", ex);
return false;
}
}
/// <summary>Starts receiving messages from later launches; they wait until <see cref="Receive"/> names who takes them.</summary>
public void Listen()
{
lock (_gate)
{
if (_listening is not null || _disposed) return;
_listening = ListenAsync(_pipeName, OnMessage, _stop.Token);
}
}
/// <summary>
/// Hands the messages received so far, then each later one, to <paramref name="received"/>, in order; it runs on a
/// pool thread.
/// </summary>
public void Receive(Action<IReadOnlyList<string>> received)
{
lock (_gate)
{
_received = received;
while (_waiting.TryDequeue(out var args)) received(args);
}
}
/// <summary>
/// Stops answering later launches while keeping the mutex: from now on they wait for this instance to exit instead
/// of handing over arguments it could no longer open.
/// </summary>
public void StopListening()
{
Task? listening;
lock (_gate)
{
if (_disposed) return;
_stop.Cancel();
listening = _listening;
}
// The pipe closes as the loop ends (cancellation ends it quietly).
try
{
listening?.Wait(TimeSpan.FromSeconds(2));
}
catch (AggregateException ex)
{
Log.Warning("instance", "Hand-over listener ended with an error", ex);
}
}
public void Dispose()
{
StopListening();
lock (_gate)
{
if (_disposed) return;
_disposed = true;
}
_mutex.ReleaseMutex();
_mutex.Dispose();
_stop.Dispose();
}
/// <summary>UTF-8: a header line, then one argument per line (paths cannot contain line breaks).</summary>
public static byte[] Encode(IReadOnlyList<string> args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// <summary>Arguments of a message, or null when it is not one of ours.</summary>
public static IReadOnlyList<string>? Decode(ReadOnlySpan<byte> message)
{
if (message.Length > MaxMessageBytes) return null;
var lines = Encoding.UTF8.GetString(message).Split('\n');
if (lines[0] != Header) return null;
return [.. lines.Skip(1).Where(l => l.Length > 0)];
}
private void OnMessage(IReadOnlyList<string> args)
{
lock (_gate)
{
if (_received is null) _waiting.Enqueue(args);
else _received(args);
}
}
/// <summary>The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.</summary>
private static string Key(string dataDirectory) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.GetFullPath(dataDirectory).TrimEnd('\\', '/').ToUpperInvariant())))[..16];
private static string MutexName(string dataDirectory) => @"Local\Chronos.App." + Key(dataDirectory);
private static string PipeName(string dataDirectory)
{
using var process = Process.GetCurrentProcess();
return $"Chronos.App.{process.SessionId}.{Environment.UserName}.{Key(dataDirectory)}";
}
private static async Task ListenAsync(string pipeName, Action<IReadOnlyList<string>> received, CancellationToken ct)
{
while (!ct.IsCancellationRequested)
{
try
{
await using var pipe = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte,
PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
await pipe.WaitForConnectionAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
await pipe.CopyToAsync(buffer, ct).ConfigureAwait(false);
if (Decode(buffer.GetBuffer().AsSpan(0, (int)buffer.Length)) is { } args) received(args);
}
catch (OperationCanceledException)
{
return;
}
catch (UnauthorizedAccessException ex)
{
// The pipe name belongs to a Chronos running with administrator rights: later launches wait instead.
Log.Warning("instance", "Hand-over pipe not available", ex);
return;
}
catch (IOException ex)
{
// A pipe of the same name still held by a Chronos that is exiting, or a broken connection: try again shortly.
Log.Warning("instance", "Hand-over pipe failed; listening again", ex);
try
{
await Task.Delay(TimeSpan.FromSeconds(1), ct).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
return;
}
}
}
}
[LibraryImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool AllowSetForegroundWindow(int processId);
}