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;
///
/// 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 .chronos 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.
///
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> _waiting = new();
private Action>? _received;
private Task? _listening;
private bool _disposed;
private SingleInstance(Mutex mutex, string pipeName)
{
_mutex = mutex;
_pipeName = pipeName;
}
///
/// The instance guard for , 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).
///
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;
}
///
/// Waits up to for the Chronos running on 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.
///
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;
}
///
/// Sends (absolute paths; empty = just show the window) to the Chronos running on
/// ; false when it could not be reached.
///
public static bool HandOver(string dataDirectory, IReadOnlyList 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;
}
}
/// Starts receiving messages from later launches; they wait until names who takes them.
public void Listen()
{
lock (_gate)
{
if (_listening is not null || _disposed) return;
_listening = ListenAsync(_pipeName, OnMessage, _stop.Token);
}
}
///
/// Hands the messages received so far, then each later one, to , in order; it runs on a
/// pool thread.
///
public void Receive(Action> received)
{
lock (_gate)
{
_received = received;
while (_waiting.TryDequeue(out var args)) received(args);
}
}
///
/// 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.
///
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();
}
/// UTF-8: a header line, then one argument per line (paths cannot contain line breaks).
public static byte[] Encode(IReadOnlyList args) =>
Encoding.UTF8.GetBytes(Header + "\n" + string.Join("\n", args.Where(a => !a.Contains('\n', StringComparison.Ordinal))));
/// Arguments of a message, or null when it is not one of ours.
public static IReadOnlyList? Decode(ReadOnlySpan 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 args)
{
lock (_gate)
{
if (_received is null) _waiting.Enqueue(args);
else _received(args);
}
}
/// The data folder's identity (case-insensitive, as Windows paths are): a portable copy has its own instance.
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> 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);
}