mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-11-26 13:36:46 +00:00
Fixed the .NET server shutting down while the runtime still runs (#1237)
This commit is contained in:
1 parent
9ebfce3855
commit
902e406e1d
22 files changed
+923
-115
No files matched your search
@@ -0,0 +1,7 @@
|
||||
namespace AIStudio.Tools.Rust;
|
||||
|
||||
/// <summary>
|
||||
/// A batch of log events which the Rust runtime writes to the log file.
|
||||
/// </summary>
|
||||
/// <param name="Events">The events, in the order they happened.</param>
|
||||
public readonly record struct LogEventsRequest(IReadOnlyList<LogEventRequest> Events);
|
||||
@@ -10,6 +10,12 @@ internal sealed partial class FileSourceIndexer
|
||||
{
|
||||
private const int WATCHER_DEBOUNCE_SECONDS = 2;
|
||||
|
||||
/// <summary>
|
||||
/// How long the changes of a data source are counted after the one which was logged, before their summary is logged.
|
||||
/// </summary>
|
||||
private const int WATCHER_SUMMARY_SECONDS = 30;
|
||||
|
||||
private readonly WatcherChangeTally watcherChangeTally = new();
|
||||
private readonly ConcurrentDictionary<string, DataSourceWatcherRegistration> watchers = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Dictionary<string, CancellationTokenSource> watcherDebounceTokens = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly Lock watcherDebounceLock = new();
|
||||
@@ -130,23 +136,52 @@ internal sealed partial class FileSourceIndexer
|
||||
|
||||
private void OnWatchedDataSourceChanged(string dataSourceId, DataSourceWatcherConfiguration configuration, FileSystemEventArgs args)
|
||||
{
|
||||
if (!IsRelevantWatcherEvent(configuration, args))
|
||||
var isRelevant = IsRelevantWatcherEvent(configuration, args);
|
||||
|
||||
//
|
||||
// Only the first change of a burst gets a line of its own, and the others are counted,
|
||||
// cf. WatcherChangeTally:
|
||||
//
|
||||
if (this.watcherChangeTally.Count(dataSourceId, args.FullPath, isRelevant))
|
||||
{
|
||||
logger.LogDebug(
|
||||
"Ignoring file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}) because the path is not part of the RAG index.",
|
||||
dataSourceId,
|
||||
args.FullPath,
|
||||
args.ChangeType);
|
||||
return;
|
||||
if (isRelevant)
|
||||
logger.LogDebug(
|
||||
"Detected relevant file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}). Scheduling a debounced embedding run. Further changes within {Seconds} s are summarized.",
|
||||
dataSourceId,
|
||||
args.FullPath,
|
||||
args.ChangeType,
|
||||
WATCHER_SUMMARY_SECONDS);
|
||||
else
|
||||
logger.LogDebug(
|
||||
"Ignoring file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}) because the path is not part of the RAG index. Further changes within {Seconds} s are summarized.",
|
||||
dataSourceId,
|
||||
args.FullPath,
|
||||
args.ChangeType,
|
||||
WATCHER_SUMMARY_SECONDS);
|
||||
|
||||
this.ScheduleWatcherSummary(dataSourceId);
|
||||
}
|
||||
|
||||
logger.LogDebug(
|
||||
"Detected relevant file system change for data source '{DataSourceId}' at '{Path}' (event={ChangeType}). Scheduling a debounced embedding run.",
|
||||
dataSourceId,
|
||||
args.FullPath,
|
||||
args.ChangeType);
|
||||
if (isRelevant)
|
||||
this.ScheduleWatchedDataSourceRefresh(dataSourceId);
|
||||
}
|
||||
|
||||
this.ScheduleWatchedDataSourceRefresh(dataSourceId);
|
||||
private void ScheduleWatcherSummary(string dataSourceId)
|
||||
{
|
||||
Task.Run(async () =>
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(WATCHER_SUMMARY_SECONDS));
|
||||
var counts = this.watcherChangeTally.Close(dataSourceId);
|
||||
if (counts.Total > 0)
|
||||
logger.LogDebug(
|
||||
"The watcher of data source '{DataSourceId}' reported {FurtherChanges} further file system change(s) within {Seconds} s: {Relevant} concern the RAG index, {Ignored} do not. The last one was at '{Path}'.",
|
||||
dataSourceId,
|
||||
counts.Total,
|
||||
WATCHER_SUMMARY_SECONDS,
|
||||
counts.Relevant,
|
||||
counts.Ignored,
|
||||
counts.LastPath);
|
||||
}).Observe($"{nameof(FileSourceIndexer)}: summarizing the file system changes of a data source");
|
||||
}
|
||||
|
||||
private void ScheduleWatchedDataSourceRefresh(string dataSourceId)
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
namespace AIStudio.Tools.Services.Indexing;
|
||||
|
||||
/// <summary>
|
||||
/// The file system changes of one data source which WatcherChangeTally counted instead of logging each.
|
||||
/// </summary>
|
||||
/// <param name="Ignored">How many changes concerned no file of the RAG index.</param>
|
||||
/// <param name="Relevant">How many changes concerned the RAG index.</param>
|
||||
/// <param name="LastPath">The path of the last change, or an empty string without any.</param>
|
||||
internal readonly record struct WatcherChangeCounts(int Ignored, int Relevant, string LastPath)
|
||||
{
|
||||
/// <summary>
|
||||
/// No change counted.
|
||||
/// </summary>
|
||||
public static readonly WatcherChangeCounts NONE = new(0, 0, string.Empty);
|
||||
|
||||
/// <summary>
|
||||
/// How many changes were counted.
|
||||
/// </summary>
|
||||
public int Total => this.Ignored + this.Relevant;
|
||||
|
||||
/// <summary>
|
||||
/// Counts one more change.
|
||||
/// </summary>
|
||||
/// <param name="path">The path of the change.</param>
|
||||
/// <param name="isRelevant">Whether the change concerns the RAG index.</param>
|
||||
/// <returns>The counts including this change.</returns>
|
||||
public WatcherChangeCounts Add(string path, bool isRelevant) => isRelevant
|
||||
? this with { Relevant = this.Relevant + 1, LastPath = path }
|
||||
: this with { Ignored = this.Ignored + 1, LastPath = path };
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
namespace AIStudio.Tools.Services.Indexing;
|
||||
|
||||
/// <summary>
|
||||
/// Counts the file system changes which the watchers report, so the log gets a summary instead of one line per change.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A build, a checkout, or a sync tool changes thousands of files within seconds. With one log line each, such a
|
||||
/// burst buried the log, and the log events piled up on their way to the runtime until it closed the connection
|
||||
/// of the .NET server. Therefore, the first change of a data source opens a window and is logged as it comes;
|
||||
/// every further change is only counted until the window closes, and its summary takes one line.
|
||||
/// </remarks>
|
||||
internal sealed class WatcherChangeTally
|
||||
{
|
||||
private readonly Lock tallyLock = new();
|
||||
private readonly Dictionary<string, WatcherChangeCounts> openWindows = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Counts a change of a data source.
|
||||
/// </summary>
|
||||
/// <param name="dataSourceId">The id of the data source.</param>
|
||||
/// <param name="path">The path of the change.</param>
|
||||
/// <param name="isRelevant">Whether the change concerns the RAG index.</param>
|
||||
/// <returns>True when the change opened a window: the caller logs it as it comes and closes the window later.</returns>
|
||||
public bool Count(string dataSourceId, string path, bool isRelevant)
|
||||
{
|
||||
lock (this.tallyLock)
|
||||
{
|
||||
if (this.openWindows.TryGetValue(dataSourceId, out var counts))
|
||||
{
|
||||
this.openWindows[dataSourceId] = counts.Add(path, isRelevant);
|
||||
return false;
|
||||
}
|
||||
|
||||
this.openWindows[dataSourceId] = WatcherChangeCounts.NONE;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Closes the window of a data source, so its next change opens a new one.
|
||||
/// </summary>
|
||||
/// <param name="dataSourceId">The id of the data source.</param>
|
||||
/// <returns>The changes counted after the one which opened the window.</returns>
|
||||
public WatcherChangeCounts Close(string dataSourceId)
|
||||
{
|
||||
lock (this.tallyLock)
|
||||
return this.openWindows.Remove(dataSourceId, out var counts) ? counts : WatcherChangeCounts.NONE;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Decides whether the runtime is gone after a call to it failed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A failed call alone proves little. All calls share one HTTP/2 connection, which a flood of requests can
|
||||
/// congest and which the runtime may close, while the runtime itself keeps running. Therefore, a report
|
||||
/// starts a round of probes, which ask the runtime over a connection of their own. The first answer ends the
|
||||
/// round, and the next report starts afresh: failed calls never add up over the lifetime of the server. Only
|
||||
/// when no probe of a round gets an answer does the runtime count as gone, and the server shuts down.
|
||||
/// </remarks>
|
||||
/// <param name="isRuntimeAlive">Asks the runtime whether it is alive; true when it answered.</param>
|
||||
/// <param name="shutDown">Shuts the server down once the runtime counts as gone.</param>
|
||||
/// <param name="schedule">How many probes a round makes and how long it waits between them.</param>
|
||||
/// <param name="stopToken">Ends a running round when the server stops.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public sealed class RuntimeOutageCheck(Func<CancellationToken, Task<bool>> isRuntimeAlive, Action shutDown, RuntimeProbeSchedule schedule, CancellationToken stopToken, ILogger logger)
|
||||
{
|
||||
private readonly Lock roundLock = new();
|
||||
|
||||
private Task runningRound = Task.CompletedTask;
|
||||
private int reportsInRound;
|
||||
private int shutDownStarted;
|
||||
|
||||
/// <summary>
|
||||
/// Reports that a call to the runtime failed, and starts a round of probes unless one is running.
|
||||
/// </summary>
|
||||
/// <param name="reason">Why the call failed, for the log.</param>
|
||||
/// <returns>The round this report joined. It ends once the runtime answered or counts as gone, and it never fails.</returns>
|
||||
public Task Report(string reason)
|
||||
{
|
||||
if (Volatile.Read(ref this.shutDownStarted) != 0)
|
||||
return Task.CompletedTask;
|
||||
|
||||
lock (this.roundLock)
|
||||
{
|
||||
if (!this.runningRound.IsCompleted)
|
||||
{
|
||||
this.reportsInRound++;
|
||||
logger.LogDebug("Another call to the runtime failed while a round of probes is running. Reason = '{Reason}'.", reason);
|
||||
return this.runningRound;
|
||||
}
|
||||
|
||||
this.reportsInRound = 1;
|
||||
this.runningRound = Task.Run(() => this.RunRoundAsync(reason));
|
||||
this.runningRound.Observe($"{nameof(RuntimeOutageCheck)}: checking whether the runtime is alive");
|
||||
return this.runningRound;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RunRoundAsync(string reason)
|
||||
{
|
||||
logger.LogWarning("A call to the runtime failed. Reason = '{Reason}'. Checking over a connection of its own whether the runtime is still alive.", reason);
|
||||
try
|
||||
{
|
||||
for (var probe = 1; probe <= schedule.Probes; probe++)
|
||||
{
|
||||
if (probe > 1)
|
||||
await Task.Delay(schedule.Interval, stopToken);
|
||||
|
||||
if (await this.ProbeAsync())
|
||||
{
|
||||
logger.LogInformation("The runtime answered probe {Probe} of {Probes} and is still alive. The {Reports} failed call(s) of this round were transient.", probe, schedule.Probes, this.ReportsInRound);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.LogWarning("The runtime did not answer probe {Probe} of {Probes}.", probe, schedule.Probes);
|
||||
}
|
||||
}
|
||||
catch (Exception) when (stopToken.IsCancellationRequested)
|
||||
{
|
||||
// The server stops anyway, so the outcome of this round no longer matters.
|
||||
return;
|
||||
}
|
||||
|
||||
if (Interlocked.Exchange(ref this.shutDownStarted, 1) != 0)
|
||||
return;
|
||||
|
||||
logger.LogError("The runtime did not answer any of {Probes} probes, {Interval} apart, and counts as gone. Failed calls in this round: {Reports}; the first one failed with reason '{Reason}'. Shutting down the server.", schedule.Probes, schedule.Interval, this.ReportsInRound, reason);
|
||||
shutDown();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks the runtime once whether it is alive. A probe which fails in any way counts as no answer.
|
||||
/// </summary>
|
||||
private async Task<bool> ProbeAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
return await isRuntimeAlive(stopToken);
|
||||
}
|
||||
catch (Exception e) when (!stopToken.IsCancellationRequested)
|
||||
{
|
||||
logger.LogWarning(e, "The probe whether the runtime is alive failed.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int ReportsInRound
|
||||
{
|
||||
get
|
||||
{
|
||||
lock (this.roundLock)
|
||||
return this.reportsInRound;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// How a round of RuntimeOutageCheck probes the runtime.
|
||||
/// </summary>
|
||||
/// <param name="Probes">How many probes a round makes at most, before the runtime counts as gone.</param>
|
||||
/// <param name="Interval">How long the round waits between two probes.</param>
|
||||
public readonly record struct RuntimeProbeSchedule(int Probes, TimeSpan Interval)
|
||||
{
|
||||
/// <summary>
|
||||
/// Seven probes, ten seconds apart: the runtime counts as gone once it did not answer for a minute.
|
||||
/// </summary>
|
||||
public static readonly RuntimeProbeSchedule DEFAULT = new(7, TimeSpan.FromSeconds(10));
|
||||
}
|
||||
@@ -2,31 +2,24 @@ using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Shuts the server down once the runtime is gone.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Services report a failed call to the runtime with the event RUST_SERVICE_UNAVAILABLE. Such a call can fail
|
||||
/// while the runtime keeps running, so RuntimeOutageCheck probes the runtime before the server shuts down.
|
||||
/// </remarks>
|
||||
public sealed class RustAvailabilityMonitorService : BackgroundService, IMessageBusReceiver
|
||||
{
|
||||
private const int UNAVAILABLE_EVENT_THRESHOLD = 2;
|
||||
|
||||
private readonly ILogger<RustAvailabilityMonitorService> logger;
|
||||
private readonly MessageBus messageBus;
|
||||
private readonly RustService rustService;
|
||||
private readonly IHostApplicationLifetime appLifetime;
|
||||
private readonly RuntimeOutageCheck outageCheck;
|
||||
|
||||
private int rustUnavailableCount;
|
||||
private int availabilityCheckTriggered;
|
||||
|
||||
// To prevent multiple shutdown triggers. We use int instead of bool for Interlocked operations.
|
||||
private int shutdownTriggered;
|
||||
|
||||
public RustAvailabilityMonitorService(
|
||||
ILogger<RustAvailabilityMonitorService> logger,
|
||||
MessageBus messageBus,
|
||||
RustService rustService,
|
||||
IHostApplicationLifetime appLifetime)
|
||||
public RustAvailabilityMonitorService(ILogger<RustAvailabilityMonitorService> logger, MessageBus messageBus, RustService rustService, IHostApplicationLifetime appLifetime)
|
||||
{
|
||||
this.logger = logger;
|
||||
this.messageBus = messageBus;
|
||||
this.rustService = rustService;
|
||||
this.appLifetime = appLifetime;
|
||||
this.outageCheck = new(rustService.IsRuntimeAliveAsync, appLifetime.StopApplication, RuntimeProbeSchedule.DEFAULT, appLifetime.ApplicationStopping, logger);
|
||||
|
||||
this.messageBus.RegisterComponent(this);
|
||||
this.ApplyFilters([], [Event.RUST_SERVICE_UNAVAILABLE]);
|
||||
@@ -54,40 +47,13 @@ public sealed class RustAvailabilityMonitorService : BackgroundService, IMessage
|
||||
string s when !string.IsNullOrWhiteSpace(s) => s,
|
||||
_ => "unknown reason",
|
||||
};
|
||||
|
||||
// Thread-safe incrementation of the unavailable count and check against the threshold:
|
||||
var numEvents = Interlocked.Increment(ref this.rustUnavailableCount);
|
||||
|
||||
// On the first event, trigger some Rust availability checks to confirm.
|
||||
// Just fire and forget - we don't need to await this here.
|
||||
if (numEvents == 1 && Interlocked.Exchange(ref this.availabilityCheckTriggered, 1) == 0)
|
||||
{
|
||||
//
|
||||
// This is also useful to speed up the detection of Rust availability issues,
|
||||
// as it triggers two immediate checks instead of waiting for the next scheduled check.
|
||||
// Scheduled checks are typically every few minutes, which might be too long to wait
|
||||
// in case of critical Rust service failures.
|
||||
//
|
||||
// On the other hand, we cannot kill the .NET server on the first failure, as it might
|
||||
// be a transient issue.
|
||||
//
|
||||
|
||||
this.VerifyRustAvailability().Observe($"{nameof(RustAvailabilityMonitorService)}: verifying the Rust availability");
|
||||
this.VerifyRustAvailability().Observe($"{nameof(RustAvailabilityMonitorService)}: verifying the Rust availability");
|
||||
}
|
||||
|
||||
if (numEvents <= UNAVAILABLE_EVENT_THRESHOLD)
|
||||
{
|
||||
this.logger.LogWarning("Rust service unavailable (num repeats={NumRepeats}, threshold={Threshold}). Reason = '{Reason}'. Waiting for more occurrences before shutting down the server.", numEvents, UNAVAILABLE_EVENT_THRESHOLD, reason);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
// Ensure shutdown is only triggered once:
|
||||
if (Interlocked.Exchange(ref this.shutdownTriggered, 1) != 0)
|
||||
return Task.CompletedTask;
|
||||
|
||||
this.logger.LogError("Rust service unavailable (num repeats={NumRepeats}, threshold={Threshold}). Reason = '{Reason}'. Shutting down the server.", numEvents, UNAVAILABLE_EVENT_THRESHOLD, reason);
|
||||
this.appLifetime.StopApplication();
|
||||
//
|
||||
// The round of probes runs on its own and takes up to a minute. The service which reported
|
||||
// the failed call goes on meanwhile, e.g., the event stream with its next attempt. The check
|
||||
// watches the outcome of the round itself.
|
||||
//
|
||||
_ = this.outageCheck.Report(reason);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -95,17 +61,4 @@ public sealed class RustAvailabilityMonitorService : BackgroundService, IMessage
|
||||
{
|
||||
return Task.FromResult(MessageBusAnswer<TResult>.NONE);
|
||||
}
|
||||
|
||||
private async Task VerifyRustAvailability()
|
||||
{
|
||||
try
|
||||
{
|
||||
await this.rustService.ReadUserLanguage(forceRequest: true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogWarning(e, "Rust availability check failed.");
|
||||
await this.messageBus.SendMessage(null, Event.RUST_SERVICE_UNAVAILABLE, "Rust availability check failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ namespace AIStudio.Tools.Services;
|
||||
[JsonSerializable(typeof(ValidateShortcutRequest))]
|
||||
[JsonSerializable(typeof(SetInterfaceSizeRequest))]
|
||||
[JsonSerializable(typeof(CreateMediaJobRequest))]
|
||||
[JsonSerializable(typeof(LogEventRequest))]
|
||||
[JsonSerializable(typeof(LogEventsRequest))]
|
||||
[JsonSerializable(typeof(ValidateTokenizerRequest))]
|
||||
[JsonSerializable(typeof(StoreTokenizerRequest))]
|
||||
[JsonSerializable(typeof(DeleteTokenizerRequest))]
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
using System.Threading.Channels;
|
||||
|
||||
using AIStudio.Tools.Rust;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Forwards the log events of the .NET server to the runtime, in batches and in the order they happened.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// With one request per event, a burst of events, such as the changes of a build in a watched folder, put
|
||||
/// thousands of requests on the HTTP/2 connection to the runtime at once. The runtime fell minutes behind,
|
||||
/// and once the server gave up on more than 20 of them, the runtime closed the connection which all calls
|
||||
/// of the server share. Therefore, a single sender takes the waiting events off a bounded queue and sends up
|
||||
/// to MAX_BATCH_SIZE of them per request, one request at a time, over a client of its own. When the runtime
|
||||
/// cannot keep up, the queue fills up, further events are dropped, and the next batch says how many.
|
||||
/// </remarks>
|
||||
public sealed class RustLogForwarder : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// How many events wait for the runtime at most.
|
||||
/// </summary>
|
||||
public const int CAPACITY = 10_000;
|
||||
|
||||
/// <summary>
|
||||
/// How many events one request carries at most.
|
||||
/// </summary>
|
||||
public const int MAX_BATCH_SIZE = 500;
|
||||
|
||||
/// <summary>
|
||||
/// How long the sender waits after a batch failed, so a runtime which is gone is not asked again and again.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan PAUSE_AFTER_FAILURE = TimeSpan.FromSeconds(1);
|
||||
|
||||
/// <summary>
|
||||
/// How long disposing waits for the waiting events to reach the runtime.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan DRAIN_TIMEOUT = TimeSpan.FromSeconds(2);
|
||||
|
||||
private readonly Channel<LogEventRequest> queue = Channel.CreateBounded<LogEventRequest>(new BoundedChannelOptions(CAPACITY) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait });
|
||||
private readonly HttpClient http;
|
||||
private readonly TimeSpan pauseAfterFailure;
|
||||
private readonly Task sender;
|
||||
|
||||
private int lostEvents;
|
||||
|
||||
/// <param name="http">The client which sends the batches. It needs a connection of its own, so the log events never wait in front of other calls.</param>
|
||||
/// <param name="pauseAfterFailure">How long the sender waits after a batch failed.</param>
|
||||
public RustLogForwarder(HttpClient http, TimeSpan pauseAfterFailure)
|
||||
{
|
||||
this.http = http;
|
||||
this.pauseAfterFailure = pauseAfterFailure;
|
||||
this.sender = Task.Run(this.SendAsync);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues a log event for the runtime. Never waits: when the queue is full, the event is dropped and counted.
|
||||
/// </summary>
|
||||
/// <param name="logEvent">The log event.</param>
|
||||
public void Enqueue(LogEventRequest logEvent)
|
||||
{
|
||||
if (!this.queue.Writer.TryWrite(logEvent))
|
||||
Interlocked.Increment(ref this.lostEvents);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Accepts no further events and sends the waiting ones.
|
||||
/// </summary>
|
||||
/// <returns>A task which ends once every waiting event was sent or lost.</returns>
|
||||
public Task StopAsync()
|
||||
{
|
||||
this.queue.Writer.TryComplete();
|
||||
return this.sender;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Gives the waiting events a moment to reach the runtime before the server ends:
|
||||
this.StopAsync().Wait(DRAIN_TIMEOUT);
|
||||
}
|
||||
|
||||
private async Task SendAsync()
|
||||
{
|
||||
var reader = this.queue.Reader;
|
||||
var batch = new List<LogEventRequest>(MAX_BATCH_SIZE + 1);
|
||||
while (await reader.WaitToReadAsync())
|
||||
{
|
||||
batch.Clear();
|
||||
while (batch.Count < MAX_BATCH_SIZE && reader.TryRead(out var logEvent))
|
||||
batch.Add(logEvent);
|
||||
|
||||
var eventsInBatch = batch.Count;
|
||||
var lostBefore = Interlocked.Exchange(ref this.lostEvents, 0);
|
||||
if (lostBefore > 0)
|
||||
batch.Add(CreateLostEventsNotice(lostBefore));
|
||||
|
||||
if (await this.TrySendAsync(batch))
|
||||
continue;
|
||||
|
||||
// The events of this batch are lost as well, and the next batch reports them together:
|
||||
Interlocked.Add(ref this.lostEvents, lostBefore + eventsInBatch);
|
||||
await Task.Delay(this.pauseAfterFailure);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> TrySendAsync(List<LogEventRequest> batch)
|
||||
{
|
||||
//
|
||||
// Nothing here may use a logger: logging means sending another event through this very
|
||||
// forwarder, and a broken connection to the runtime would feed itself. The console is the
|
||||
// only way left, which the developer sees while the server runs from the IDE.
|
||||
//
|
||||
try
|
||||
{
|
||||
using var response = await this.http.PostAsJsonAsync("/log/events", new LogEventsRequest(batch), RustService.JSON_OPTIONS);
|
||||
if (response.IsSuccessStatusCode)
|
||||
return true;
|
||||
|
||||
Console.WriteLine($"Failed to send {batch.Count} log events to the runtime: '{response.StatusCode}'.");
|
||||
return false;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine($"Failed to send {batch.Count} log events to the runtime: {TerminalLogger.DescribeException(e)}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static LogEventRequest CreateLostEventsNotice(int lostEvents) => new(
|
||||
TerminalLogger.FormatTransportTimestamp(DateTimeOffset.UtcNow),
|
||||
nameof(LogLevel.Warning),
|
||||
typeof(RustLogForwarder).FullName!,
|
||||
$"Dropped {lostEvents} log events because the runtime could not take them in time.",
|
||||
null,
|
||||
null);
|
||||
}
|
||||
@@ -126,6 +126,34 @@ public sealed partial class RustService
|
||||
return response;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Asks the runtime whether it is alive, over a connection of its own.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This check tells a runtime which is gone from a connection which failed: all other calls share one
|
||||
/// HTTP/2 connection, which a flood of requests can congest and which the runtime may close while it
|
||||
/// keeps running.
|
||||
/// </remarks>
|
||||
/// <param name="token">Ends the check when the server stops.</param>
|
||||
/// <returns>True when the runtime answered.</returns>
|
||||
public async Task<bool> IsRuntimeAliveAsync(CancellationToken token)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var response = await this.aliveHttp.GetAsync("/system/alive", token);
|
||||
if (response.IsSuccessStatusCode)
|
||||
return true;
|
||||
|
||||
this.logger?.LogWarning("The runtime refused the check whether it is alive: '{StatusCode}'.", response.StatusCode);
|
||||
return false;
|
||||
}
|
||||
catch (Exception e) when (!token.IsCancellationRequested)
|
||||
{
|
||||
this.logger?.LogWarning("The runtime did not answer the check whether it is alive: {Reason}", TerminalLogger.DescribeException(e));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requests the Rust runtime to exit the entire desktop application.
|
||||
/// </summary>
|
||||
|
||||
@@ -14,7 +14,7 @@ public sealed partial class RustService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sends a log event to the Rust runtime.
|
||||
/// Queues a log event for the Rust runtime.
|
||||
/// </summary>
|
||||
/// <param name="timestamp">When the log event happened, formatted by TerminalLogger.FormatTransportTimestamp.</param>
|
||||
/// <param name="level">The log level.</param>
|
||||
@@ -22,29 +22,11 @@ public sealed partial class RustService
|
||||
/// <param name="message">The log message.</param>
|
||||
/// <param name="exception">Optional exception message.</param>
|
||||
/// <param name="stackTrace">Optional exception stack trace.</param>
|
||||
/// <remarks>
|
||||
/// Never waits: the event joins the queue of RustLogForwarder, which sends it in a batch.
|
||||
/// </remarks>
|
||||
public void LogEvent(string timestamp, string level, string category, string message, string? exception = null, string? stackTrace = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
//
|
||||
// Fire-and-forget the log event to avoid blocking. This is the one place which deliberately
|
||||
// discards its task instead of observing it: observing means logging the failure, and logging
|
||||
// means sending another log event through this very method. A broken connection to Rust would
|
||||
// feed itself. The unobserved task exception handler in Program.cs remains the safety net here.
|
||||
//
|
||||
var request = new LogEventRequest(timestamp, level, category, message, exception, stackTrace);
|
||||
_ = this.http.PostAsJsonAsync("/log/event", request, JSON_OPTIONS);
|
||||
}
|
||||
catch
|
||||
{
|
||||
//
|
||||
// We don't expect this to ever happen because the HTTP client cannot raise exceptions in fire-and-forget mode.
|
||||
// This is because we don't await the task, so any exceptions thrown during the HTTP request are not propagated
|
||||
// back to the caller.
|
||||
//
|
||||
|
||||
Console.WriteLine("Failed to send log event to Rust service.");
|
||||
// Ignore errors to avoid log loops
|
||||
}
|
||||
this.logForwarder.Enqueue(new LogEventRequest(timestamp, level, category, message, exception, stackTrace));
|
||||
}
|
||||
}
|
||||
@@ -2,15 +2,15 @@
|
||||
|
||||
public sealed partial class RustService
|
||||
{
|
||||
public async Task<string> ReadUserLanguage(bool forceRequest = false)
|
||||
public async Task<string> ReadUserLanguage()
|
||||
{
|
||||
if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserLanguage))
|
||||
if (!string.IsNullOrWhiteSpace(this.cachedUserLanguage))
|
||||
return this.cachedUserLanguage;
|
||||
|
||||
await this.userLanguageLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserLanguage))
|
||||
if (!string.IsNullOrWhiteSpace(this.cachedUserLanguage))
|
||||
return this.cachedUserLanguage;
|
||||
|
||||
var response = await this.http.GetAsync("/system/language");
|
||||
@@ -33,15 +33,15 @@ public sealed partial class RustService
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<string> ReadUserName(bool forceRequest = false)
|
||||
public async Task<string> ReadUserName()
|
||||
{
|
||||
if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserName))
|
||||
if (!string.IsNullOrWhiteSpace(this.cachedUserName))
|
||||
return this.cachedUserName;
|
||||
|
||||
await this.userNameLock.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (!forceRequest && !string.IsNullOrWhiteSpace(this.cachedUserName))
|
||||
if (!string.IsNullOrWhiteSpace(this.cachedUserName))
|
||||
return this.cachedUserName;
|
||||
|
||||
var response = await this.http.GetAsync("/system/username");
|
||||
|
||||
@@ -17,7 +17,18 @@ public sealed partial class RustService : BackgroundService
|
||||
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(RustService).Namespace, nameof(RustService));
|
||||
|
||||
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(RustService).Namespace, nameof(RustService));
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// How long the runtime may take to answer whether it is alive. Its handler does no work, so
|
||||
/// anything longer means that the runtime cannot answer at the moment.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan ALIVE_CHECK_TIMEOUT = TimeSpan.FromSeconds(5);
|
||||
|
||||
/// <summary>
|
||||
/// How long the runtime may take to log one batch of log events.
|
||||
/// </summary>
|
||||
private static readonly TimeSpan LOG_TIMEOUT = TimeSpan.FromSeconds(30);
|
||||
|
||||
private readonly HttpClient http;
|
||||
|
||||
/// <summary>
|
||||
@@ -32,6 +43,23 @@ public sealed partial class RustService : BackgroundService
|
||||
/// </remarks>
|
||||
private readonly HttpClient extractionHttp;
|
||||
|
||||
/// <summary>
|
||||
/// A dedicated client for checking whether the runtime is alive.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// All other calls share one HTTP/2 connection. A flood of requests can congest it, and the
|
||||
/// runtime may close it, while the runtime itself keeps running. This client opens a connection
|
||||
/// of its own, so its check fails only when the runtime cannot accept a connection and answer.
|
||||
/// </remarks>
|
||||
private readonly HttpClient aliveHttp;
|
||||
|
||||
/// <summary>
|
||||
/// A dedicated client for the log events, so a burst of them never waits in front of other calls.
|
||||
/// </summary>
|
||||
private readonly HttpClient logHttp;
|
||||
|
||||
private readonly RustLogForwarder logForwarder;
|
||||
|
||||
private readonly SemaphoreSlim fileDialogLock = new(1, 1);
|
||||
private readonly SemaphoreSlim userLanguageLock = new(1, 1);
|
||||
private readonly SemaphoreSlim userNameLock = new(1, 1);
|
||||
@@ -88,6 +116,9 @@ public sealed partial class RustService : BackgroundService
|
||||
// extraction client below is visible:
|
||||
this.http = CreateHttpClient(apiPort, certificateFingerprint, TimeSpan.FromSeconds(100));
|
||||
this.extractionHttp = CreateHttpClient(apiPort, certificateFingerprint, Timeout.InfiniteTimeSpan);
|
||||
this.aliveHttp = CreateHttpClient(apiPort, certificateFingerprint, ALIVE_CHECK_TIMEOUT);
|
||||
this.logHttp = CreateHttpClient(apiPort, certificateFingerprint, LOG_TIMEOUT);
|
||||
this.logForwarder = new(this.logHttp, RustLogForwarder.PAUSE_AFTER_FAILURE);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -104,6 +135,9 @@ public sealed partial class RustService : BackgroundService
|
||||
this.certificateFingerprint = string.Empty;
|
||||
this.http = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = TimeSpan.FromSeconds(100) };
|
||||
this.extractionHttp = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = Timeout.InfiniteTimeSpan };
|
||||
this.aliveHttp = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = ALIVE_CHECK_TIMEOUT };
|
||||
this.logHttp = new HttpClient(runtime, disposeHandler: false) { BaseAddress = new Uri("https://127.0.0.1"), Timeout = LOG_TIMEOUT };
|
||||
this.logForwarder = new(this.logHttp, RustLogForwarder.PAUSE_AFTER_FAILURE);
|
||||
}
|
||||
|
||||
private static HttpClient CreateHttpClient(string apiPort, string certificateFingerprint, TimeSpan timeout)
|
||||
@@ -160,8 +194,13 @@ public sealed partial class RustService : BackgroundService
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
// First, so the waiting log events still reach the runtime:
|
||||
this.logForwarder.Dispose();
|
||||
this.logHttp.Dispose();
|
||||
|
||||
this.http.Dispose();
|
||||
this.extractionHttp.Dispose();
|
||||
this.aliveHttp.Dispose();
|
||||
this.userLanguageLock.Dispose();
|
||||
this.userNameLock.Dispose();
|
||||
base.Dispose();
|
||||
|
||||
@@ -86,7 +86,7 @@ public sealed class TerminalLogger() : ConsoleFormatter(FORMATTER_NAME)
|
||||
textWriter.WriteLine();
|
||||
}
|
||||
|
||||
// Send log event to Rust via API (fire-and-forget):
|
||||
// Queue the log event for Rust, which receives it in a batch:
|
||||
if (RUST_SERVICE is not null)
|
||||
RUST_SERVICE.LogEvent(transportTimestamp, logLevel, category, message, exceptionMessage, stackTrace);
|
||||
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
- Fixed the tiles on the assistants page, which were narrower when their texts were short, so that the tiles did not line up in columns. All tiles now have the same width, and their start buttons sit at the same height.
|
||||
- Fixed the Mathematics prototype, which told the AI that a correct derivative or integral had failed its check when the values of the function were far larger than those of its derivative.
|
||||
- Fixed the Mathematics prototype getting stuck for a long time when it checked a result with a very large factorial or power. Meanwhile, no other calculation could run.
|
||||
- Fixed AI Studio ceasing to work when many files in a folder of a local data source changed within a short time, e.g., during a software build or while a sync tool updated the folder.
|
||||
- Upgraded several libraries to improve security.
|
||||
- Upgraded Tauri to v2.12.7.
|
||||
- Upgraded MudBlazor to v9.14.0.
|
||||
|
||||
Reference in new issue
Block a user