1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2024-10-18 06:42:50 +02:00

Compare commits

...

2 Commits

Author SHA1 Message Date
9971855bf8
Cache Minecraft server executable info 2023-02-28 01:45:35 +01:00
ffa0ff24fa
Move most verbose log messages to debug level 2023-02-28 00:07:54 +01:00
17 changed files with 236 additions and 189 deletions

View File

@ -26,7 +26,7 @@ sealed class MinecraftServerExecutableDownloader {
public void Register(MinecraftServerExecutableDownloadListener listener) { public void Register(MinecraftServerExecutableDownloadListener listener) {
++listeners; ++listeners;
Logger.Verbose("Registered download listener, current listener count: {Listeners}", listeners); Logger.Debug("Registered download listener, current listener count: {Listeners}", listeners);
DownloadProgress += listener.DownloadProgressEventHandler; DownloadProgress += listener.DownloadProgressEventHandler;
listener.CancellationToken.Register(Unregister, listener); listener.CancellationToken.Register(Unregister, listener);
@ -37,11 +37,11 @@ sealed class MinecraftServerExecutableDownloader {
DownloadProgress -= listener.DownloadProgressEventHandler; DownloadProgress -= listener.DownloadProgressEventHandler;
if (--listeners <= 0) { if (--listeners <= 0) {
Logger.Verbose("Unregistered last download listener, cancelling download."); Logger.Debug("Unregistered last download listener, cancelling download.");
cancellationTokenSource.Cancel(); cancellationTokenSource.Cancel();
} }
else { else {
Logger.Verbose("Unregistered download listener, current listener count: {Listeners}", listeners); Logger.Debug("Unregistered download listener, current listener count: {Listeners}", listeners);
} }
} }
@ -50,7 +50,7 @@ sealed class MinecraftServerExecutableDownloader {
} }
private void OnCompleted(Task task) { private void OnCompleted(Task task) {
Logger.Verbose("Download task completed."); Logger.Debug("Download task completed.");
Completed?.Invoke(this, EventArgs.Empty); Completed?.Invoke(this, EventArgs.Empty);
Completed = null; Completed = null;
DownloadProgress = null; DownloadProgress = null;

View File

@ -84,7 +84,7 @@ public sealed class ServerStatusProtocol {
return null; return null;
} }
logger.Verbose("Detected {OnlinePlayerCount} online player(s).", onlinePlayerCount); logger.Debug("Detected {OnlinePlayerCount} online player(s).", onlinePlayerCount);
return onlinePlayerCount; return onlinePlayerCount;
} finally { } finally {
ArrayPool<byte>.Shared.Return(messageBuffer); ArrayPool<byte>.Shared.Return(messageBuffer);

View File

@ -69,7 +69,7 @@ public sealed class RpcLauncher : RpcRuntime<ClientSocket> {
} catch (OperationCanceledException) { } catch (OperationCanceledException) {
// Ignore. // Ignore.
} finally { } finally {
logger.Verbose("ZeroMQ client stopped receiving messages."); logger.Debug("ZeroMQ client stopped receiving messages.");
disconnectSemaphore.Wait(CancellationToken.None); disconnectSemaphore.Wait(CancellationToken.None);
keepAliveLoop.Cancel(); keepAliveLoop.Cancel();

View File

@ -69,7 +69,7 @@ sealed class BackupArchiver {
return null; return null;
} }
logger.Verbose("Created world backup: {FilePath}", backupFilePath); logger.Debug("Created world backup: {FilePath}", backupFilePath);
return backupFilePath; return backupFilePath;
} }
@ -135,7 +135,7 @@ sealed class BackupArchiver {
foreach (FileInfo file in sourceFolder.EnumerateFiles()) { foreach (FileInfo file in sourceFolder.EnumerateFiles()) {
var filePath = relativePath.Add(file.Name); var filePath = relativePath.Add(file.Name);
if (IsFileSkipped(filePath)) { if (IsFileSkipped(filePath)) {
logger.Verbose("Skipping file: {File}", string.Join('/', filePath)); logger.Debug("Skipping file: {File}", string.Join('/', filePath));
continue; continue;
} }
@ -150,7 +150,7 @@ sealed class BackupArchiver {
foreach (DirectoryInfo directory in sourceFolder.EnumerateDirectories()) { foreach (DirectoryInfo directory in sourceFolder.EnumerateDirectories()) {
var folderPath = relativePath.Add(directory.Name); var folderPath = relativePath.Add(directory.Name);
if (IsFolderSkipped(folderPath)) { if (IsFolderSkipped(folderPath)) {
logger.Verbose("Skipping folder: {Folder}", string.Join('/', folderPath)); logger.Debug("Skipping folder: {Folder}", string.Join('/', folderPath));
continue; continue;
} }

View File

@ -59,7 +59,7 @@ static class BackupCompressor {
static void OnZstdOutput(object? sender, DataReceivedEventArgs e) { static void OnZstdOutput(object? sender, DataReceivedEventArgs e) {
if (!string.IsNullOrWhiteSpace(e.Data)) { if (!string.IsNullOrWhiteSpace(e.Data)) {
ZstdLogger.Verbose("[Output] {Line}", e.Data); ZstdLogger.Debug("[Output] {Line}", e.Data);
} }
} }

View File

@ -79,7 +79,7 @@ sealed class BackupScheduler : CancellableBackgroundTask {
await Task.Delay(TimeSpan.FromSeconds(10), CancellationToken); await Task.Delay(TimeSpan.FromSeconds(10), CancellationToken);
Logger.Verbose("Waiting for server output before checking for online players again..."); Logger.Debug("Waiting for server output before checking for online players again...");
await serverOutputWhileWaitingForOnlinePlayers.WaitHandle.WaitOneAsync(CancellationToken); await serverOutputWhileWaitingForOnlinePlayers.WaitHandle.WaitOneAsync(CancellationToken);
} }
} finally { } finally {
@ -90,7 +90,7 @@ sealed class BackupScheduler : CancellableBackgroundTask {
private void ServerOutputListener(object? sender, string line) { private void ServerOutputListener(object? sender, string line) {
if (!serverOutputWhileWaitingForOnlinePlayers.IsSet) { if (!serverOutputWhileWaitingForOnlinePlayers.IsSet) {
serverOutputWhileWaitingForOnlinePlayers.Set(); serverOutputWhileWaitingForOnlinePlayers.Set();
Logger.Verbose("Detected server output, signalling to check for online players again."); Logger.Debug("Detected server output, signalling to check for online players again.");
} }
} }
} }

View File

@ -59,19 +59,19 @@ sealed partial class BackupServerCommandDispatcher : IDisposable {
if (!automaticSavingDisabled.Task.IsCompleted) { if (!automaticSavingDisabled.Task.IsCompleted) {
if (info == "Automatic saving is now disabled") { if (info == "Automatic saving is now disabled") {
logger.Verbose("Detected that automatic saving is disabled."); logger.Debug("Detected that automatic saving is disabled.");
automaticSavingDisabled.SetResult(); automaticSavingDisabled.SetResult();
} }
} }
else if (!savedTheGame.Task.IsCompleted) { else if (!savedTheGame.Task.IsCompleted) {
if (info == "Saved the game") { if (info == "Saved the game") {
logger.Verbose("Detected that the game is saved."); logger.Debug("Detected that the game is saved.");
savedTheGame.SetResult(); savedTheGame.SetResult();
} }
} }
else if (!automaticSavingEnabled.Task.IsCompleted) { else if (!automaticSavingEnabled.Task.IsCompleted) {
if (info == "Automatic saving is now enabled") { if (info == "Automatic saving is now enabled") {
logger.Verbose("Detected that automatic saving is enabled."); logger.Debug("Detected that automatic saving is enabled.");
automaticSavingEnabled.SetResult(); automaticSavingEnabled.SetResult();
} }
} }

View File

@ -78,7 +78,7 @@ sealed class Instance : IDisposable {
disposable.Dispose(); disposable.Dispose();
} }
logger.Verbose("Transitioning instance state to: {NewState}", newState.GetType().Name); logger.Debug("Transitioning instance state to: {NewState}", newState.GetType().Name);
var wasRunning = IsRunning; var wasRunning = IsRunning;
currentState = newState; currentState = newState;
@ -170,12 +170,12 @@ sealed class Instance : IDisposable {
if (!instance.IsRunning) { if (!instance.IsRunning) {
// Only InstanceSessionManager is allowed to transition an instance out of a non-running state. // Only InstanceSessionManager is allowed to transition an instance out of a non-running state.
instance.logger.Verbose("Cancelled state transition to {State} because instance is not running.", state.GetType().Name); instance.logger.Debug("Cancelled state transition to {State} because instance is not running.", state.GetType().Name);
return; return;
} }
if (state is not InstanceNotRunningState && shutdownCancellationToken.IsCancellationRequested) { if (state is not InstanceNotRunningState && shutdownCancellationToken.IsCancellationRequested) {
instance.logger.Verbose("Cancelled state transition to {State} due to Agent shutdown.", state.GetType().Name); instance.logger.Debug("Cancelled state transition to {State} due to Agent shutdown.", state.GetType().Name);
return; return;
} }

View File

@ -16,7 +16,7 @@ sealed class InstanceSession : IDisposable {
} }
private void SessionOutput(object? sender, string line) { private void SessionOutput(object? sender, string line) {
context.Logger.Verbose("[Server] {Line}", line); context.Logger.Debug("[Server] {Line}", line);
logSender.Enqueue(line); logSender.Enqueue(line);
} }

View File

@ -110,7 +110,7 @@ sealed class InstanceRunningState : IInstanceState {
} }
} }
} catch (OperationCanceledException) { } catch (OperationCanceledException) {
context.Logger.Verbose("Cancelled delayed stop."); context.Logger.Debug("Cancelled delayed stop.");
return; return;
} catch (ObjectDisposedException) { } catch (ObjectDisposedException) {
return; return;

View File

@ -0,0 +1,164 @@
using System.Collections.Immutable;
using System.Net.Http.Json;
using System.Text.Json;
using Phantom.Common.Data.Minecraft;
using Phantom.Common.Logging;
using Phantom.Utils.Cryptography;
using Phantom.Utils.IO;
using Phantom.Utils.Runtime;
using Serilog;
namespace Phantom.Server.Minecraft;
sealed class MinecraftVersionApi : IDisposable {
private static readonly ILogger Logger = PhantomLogger.Create<MinecraftVersionApi>();
private const string VersionManifestUrl = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
private readonly HttpClient http = new ();
public void Dispose() {
http.Dispose();
}
public async Task<ImmutableArray<MinecraftVersion>> GetVersions(CancellationToken cancellationToken) {
return await FetchVersions(cancellationToken) ?? ImmutableArray<MinecraftVersion>.Empty;
}
private async Task<ImmutableArray<MinecraftVersion>?> FetchVersions(CancellationToken cancellationToken) {
return await FetchOrFailSilently(async () => {
var versionManifest = await FetchJson(VersionManifestUrl, "version manifest", cancellationToken);
return GetVersionsFromManifest(versionManifest);
});
}
public async Task<FileDownloadInfo?> GetServerExecutableInfo(ImmutableArray<MinecraftVersion> versions, string version, CancellationToken cancellationToken) {
var versionObject = versions.FirstOrDefault(v => v.Id == version);
if (versionObject == null) {
Logger.Error("Version {Version} was not found in version manifest.", version);
return null;
}
return await FetchOrFailSilently(async () => {
var versionMetadata = await FetchJson(versionObject.MetadataUrl, "version metadata", cancellationToken);
return GetServerExecutableInfoFromMetadata(versionMetadata);
});
}
private static async Task<T?> FetchOrFailSilently<T>(Func<Task<T?>> task) {
try {
return await task();
} catch (StopProcedureException) {
return default;
} catch (Exception e) {
Logger.Error(e, "An unexpected error occurred.");
return default;
}
}
private async Task<JsonElement> FetchJson(string url, string description, CancellationToken cancellationToken) {
Logger.Debug("Fetching {Description} JSON from: {Url}", description, url);
try {
return await http.GetFromJsonAsync<JsonElement>(url, cancellationToken);
} catch (HttpRequestException e) {
Logger.Error(e, "Unable to download {Description}.", description);
throw StopProcedureException.Instance;
} catch (Exception e) {
Logger.Error(e, "Unable to parse {Description} as JSON.", description);
throw StopProcedureException.Instance;
}
}
private static ImmutableArray<MinecraftVersion> GetVersionsFromManifest(JsonElement versionManifest) {
JsonElement versionsElement = GetJsonPropertyOrThrow(versionManifest, "versions", JsonValueKind.Array, "version manifest");
var foundVersions = ImmutableArray.CreateBuilder<MinecraftVersion>(versionsElement.GetArrayLength());
foreach (var versionElement in versionsElement.EnumerateArray()) {
try {
foundVersions.Add(GetVersionFromManifestEntry(versionElement));
} catch (StopProcedureException) {}
}
return foundVersions.MoveToImmutable();
}
private static MinecraftVersion GetVersionFromManifestEntry(JsonElement versionElement) {
JsonElement idElement = GetJsonPropertyOrThrow(versionElement, "id", JsonValueKind.String, "version entry in version manifest");
string id = idElement.GetString() ?? throw new InvalidOperationException();
JsonElement typeElement = GetJsonPropertyOrThrow(versionElement, "type", JsonValueKind.String, "version entry in version manifest");
string? typeString = typeElement.GetString();
var type = MinecraftVersionTypes.FromString(typeString);
if (type == MinecraftVersionType.Other) {
Logger.Warning("Unknown version type: {Type} ({Version})", typeString, id);
}
JsonElement urlElement = GetJsonPropertyOrThrow(versionElement, "url", JsonValueKind.String, "version entry in version manifest");
string? url = urlElement.GetString();
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) {
Logger.Error("The \"url\" key in version entry in version manifest does not contain a valid URL: {Url}", url);
throw StopProcedureException.Instance;
}
if (uri.Scheme != "https" || !uri.AbsolutePath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) {
Logger.Error("The \"url\" key in version entry in version manifest does not contain an accepted URL: {Url}", url);
throw StopProcedureException.Instance;
}
return new MinecraftVersion(id, type, url);
}
private static FileDownloadInfo GetServerExecutableInfoFromMetadata(JsonElement versionMetadata) {
JsonElement downloadsElement = GetJsonPropertyOrThrow(versionMetadata, "downloads", JsonValueKind.Object, "version metadata");
JsonElement serverElement = GetJsonPropertyOrThrow(downloadsElement, "server", JsonValueKind.Object, "downloads object in version metadata");
JsonElement urlElement = GetJsonPropertyOrThrow(serverElement, "url", JsonValueKind.String, "downloads.server object in version metadata");
string? url = urlElement.GetString();
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) {
Logger.Error("The \"url\" key in downloads.server object in version metadata does not contain a valid URL: {Url}", url);
throw StopProcedureException.Instance;
}
if (uri.Scheme != "https" || !uri.AbsolutePath.EndsWith(".jar", StringComparison.OrdinalIgnoreCase)) {
Logger.Error("The \"url\" key in downloads.server object in version metadata does not contain a accepted URL: {Url}", url);
throw StopProcedureException.Instance;
}
JsonElement sizeElement = GetJsonPropertyOrThrow(serverElement, "size", JsonValueKind.Number, "downloads.server object in version metadata");
ulong size;
try {
size = sizeElement.GetUInt64();
} catch (FormatException) {
Logger.Error("The \"size\" key in downloads.server object in version metadata contains an invalid file size: {Size}", sizeElement);
throw StopProcedureException.Instance;
}
JsonElement sha1Element = GetJsonPropertyOrThrow(serverElement, "sha1", JsonValueKind.String, "downloads.server object in version metadata");
Sha1String hash;
try {
hash = Sha1String.FromString(sha1Element.GetString());
} catch (Exception) {
Logger.Error("The \"sha1\" key in downloads.server object in version metadata does not contain a valid SHA-1 hash: {Sha1}", sha1Element.GetString());
throw StopProcedureException.Instance;
}
return new FileDownloadInfo(url, hash, new FileSize(size));
}
private static JsonElement GetJsonPropertyOrThrow(JsonElement parentElement, string propertyKey, JsonValueKind expectedKind, string location) {
if (!parentElement.TryGetProperty(propertyKey, out var valueElement)) {
Logger.Error("Missing \"{Property}\" key in " + location + ".", propertyKey);
throw StopProcedureException.Instance;
}
if (valueElement.ValueKind != expectedKind) {
Logger.Error("The \"{Property}\" key in " + location + " does not contain a JSON {ExpectedType}. Actual type: {ActualType}", propertyKey, expectedKind, valueElement.ValueKind);
throw StopProcedureException.Instance;
}
return valueElement;
}
}

View File

@ -1,12 +1,7 @@
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Http.Json;
using System.Text.Json;
using Phantom.Common.Data.Minecraft; using Phantom.Common.Data.Minecraft;
using Phantom.Common.Logging; using Phantom.Common.Logging;
using Phantom.Utils.Cryptography;
using Phantom.Utils.IO;
using Phantom.Utils.Runtime;
using Serilog; using Serilog;
namespace Phantom.Server.Minecraft; namespace Phantom.Server.Minecraft;
@ -15,178 +10,66 @@ public sealed class MinecraftVersions : IDisposable {
private static readonly ILogger Logger = PhantomLogger.Create<MinecraftVersions>(); private static readonly ILogger Logger = PhantomLogger.Create<MinecraftVersions>();
private static readonly TimeSpan CacheRetentionTime = TimeSpan.FromMinutes(10); private static readonly TimeSpan CacheRetentionTime = TimeSpan.FromMinutes(10);
private const string VersionManifestUrl = "https://launchermeta.mojang.com/mc/game/version_manifest.json"; private readonly MinecraftVersionApi api = new ();
private readonly HttpClient http = new ();
private readonly Stopwatch cacheTimer = new (); private readonly Stopwatch cacheTimer = new ();
private readonly SemaphoreSlim cachedVersionsSemaphore = new (1, 1); private readonly SemaphoreSlim cacheSemaphore = new (1, 1);
private bool IsCacheNotExpired => cacheTimer.IsRunning && cacheTimer.Elapsed < CacheRetentionTime;
private ImmutableArray<MinecraftVersion>? cachedVersions; private ImmutableArray<MinecraftVersion>? cachedVersions;
private ImmutableArray<MinecraftVersion>? CachedVersionsUnlessExpired => cacheTimer.IsRunning && cacheTimer.Elapsed < CacheRetentionTime ? cachedVersions : null; private readonly Dictionary<string, FileDownloadInfo?> cachedServerExecutables = new ();
public void Dispose() { public void Dispose() {
http.Dispose(); api.Dispose();
cachedVersionsSemaphore.Dispose(); cacheSemaphore.Dispose();
} }
public async Task<ImmutableArray<MinecraftVersion>> GetVersions(CancellationToken cancellationToken) { public async Task<ImmutableArray<MinecraftVersion>> GetVersions(CancellationToken cancellationToken) {
if (CachedVersionsUnlessExpired is {} earlyResult) { return await GetCachedObject(() => cachedVersions != null, () => cachedVersions.GetValueOrDefault(), v => cachedVersions = v, LoadVersions, cancellationToken);
return earlyResult;
} }
await cachedVersionsSemaphore.WaitAsync(cancellationToken); private async Task<ImmutableArray<MinecraftVersion>> LoadVersions(CancellationToken cancellationToken) {
try { ImmutableArray<MinecraftVersion> versions = await api.GetVersions(cancellationToken);
if (CachedVersionsUnlessExpired is {} racedResult) {
return racedResult;
}
ImmutableArray<MinecraftVersion> versions = await FetchVersions(cancellationToken) ?? ImmutableArray<MinecraftVersion>.Empty;
Logger.Information("Refreshed Minecraft version cache, {Versions} version(s) found.", versions.Length); Logger.Information("Refreshed Minecraft version cache, {Versions} version(s) found.", versions.Length);
cachedVersions = versions;
cacheTimer.Restart();
return versions; return versions;
} finally {
cachedVersionsSemaphore.Release();
}
}
private async Task<ImmutableArray<MinecraftVersion>?> FetchVersions(CancellationToken cancellationToken) {
return await FetchOrFailSilently(async () => {
var versionManifest = await FetchJson(http, VersionManifestUrl, "version manifest", cancellationToken);
return GetVersionsFromManifest(versionManifest);
});
} }
public async Task<FileDownloadInfo?> GetServerExecutableInfo(string version, CancellationToken cancellationToken) { public async Task<FileDownloadInfo?> GetServerExecutableInfo(string version, CancellationToken cancellationToken) {
return await FetchOrFailSilently(async () => {
var versions = await GetVersions(cancellationToken); var versions = await GetVersions(cancellationToken);
var versionObject = versions.FirstOrDefault(v => v.Id == version); return await GetCachedObject(() => cachedServerExecutables.ContainsKey(version), () => cachedServerExecutables[version], v => cachedServerExecutables[version] = v, ct => LoadServerExecutableInfo(versions, version, ct), cancellationToken);
if (versionObject == null) {
Logger.Error("Version {Version} was not found in version manifest.", version);
return null;
} }
var versionMetadata = await FetchJson(http, versionObject.MetadataUrl, "version metadata", cancellationToken); private async Task<FileDownloadInfo?> LoadServerExecutableInfo(ImmutableArray<MinecraftVersion> versions, string version, CancellationToken cancellationToken) {
return GetServerExecutableInfoFromMetadata(versionMetadata); var info = await api.GetServerExecutableInfo(versions, version, cancellationToken);
});
if (info == null) {
Logger.Information("Refreshed Minecraft {Version} server executable cache, no file found.", version);
}
else {
Logger.Information("Refreshed Minecraft {Version} server executable cache, found file: {Url}.", version, info.DownloadUrl);
} }
private static async Task<T?> FetchOrFailSilently<T>(Func<Task<T?>> task) { return info;
}
private async Task<T> GetCachedObject<T>(Func<bool> isLoaded, Func<T> fieldGetter, Action<T> fieldSetter, Func<CancellationToken, Task<T>> fieldLoader, CancellationToken cancellationToken) {
if (IsCacheNotExpired && isLoaded()) {
return fieldGetter();
}
await cacheSemaphore.WaitAsync(cancellationToken);
try { try {
return await task(); if (IsCacheNotExpired && isLoaded()) {
} catch (StopProcedureException) { return fieldGetter();
return default;
} catch (Exception e) {
Logger.Error(e, "An unexpected error occurred.");
return default;
}
} }
private static async Task<JsonElement> FetchJson(HttpClient http, string url, string description, CancellationToken cancellationToken) { T result = await fieldLoader(cancellationToken);
Logger.Information("Fetching {Description} JSON from: {Url}", description, url); fieldSetter(result);
try { cacheTimer.Restart();
return await http.GetFromJsonAsync<JsonElement>(url, cancellationToken); return result;
} catch (HttpRequestException e) { } finally {
Logger.Error(e, "Unable to download {Description}.", description); cacheSemaphore.Release();
throw StopProcedureException.Instance;
} catch (Exception e) {
Logger.Error(e, "Unable to parse {Description} as JSON.", description);
throw StopProcedureException.Instance;
} }
} }
private static ImmutableArray<MinecraftVersion> GetVersionsFromManifest(JsonElement versionManifest) {
JsonElement versionsElement = GetJsonPropertyOrThrow(versionManifest, "versions", JsonValueKind.Array, "version manifest");
var foundVersions = ImmutableArray.CreateBuilder<MinecraftVersion>(versionsElement.GetArrayLength());
foreach (var versionElement in versionsElement.EnumerateArray()) {
try {
foundVersions.Add(GetVersionFromManifestEntry(versionElement));
} catch (StopProcedureException) {}
}
return foundVersions.MoveToImmutable();
}
private static MinecraftVersion GetVersionFromManifestEntry(JsonElement versionElement) {
JsonElement idElement = GetJsonPropertyOrThrow(versionElement, "id", JsonValueKind.String, "version entry in version manifest");
string id = idElement.GetString() ?? throw new InvalidOperationException();
JsonElement typeElement = GetJsonPropertyOrThrow(versionElement, "type", JsonValueKind.String, "version entry in version manifest");
string? typeString = typeElement.GetString();
var type = MinecraftVersionTypes.FromString(typeString);
if (type == MinecraftVersionType.Other) {
Logger.Verbose("Unknown version type: {Type} ({Version})", typeString, id);
}
JsonElement urlElement = GetJsonPropertyOrThrow(versionElement, "url", JsonValueKind.String, "version entry in version manifest");
string? url = urlElement.GetString();
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) {
Logger.Error("The \"url\" key in version entry in version manifest does not contain a valid URL: {Url}", url);
throw StopProcedureException.Instance;
}
if (uri.Scheme != "https" || !uri.AbsolutePath.EndsWith(".json", StringComparison.OrdinalIgnoreCase)) {
Logger.Error("The \"url\" key in version entry in version manifest does not contain an accepted URL: {Url}", url);
throw StopProcedureException.Instance;
}
return new MinecraftVersion(id, type, url);
}
private static FileDownloadInfo GetServerExecutableInfoFromMetadata(JsonElement versionMetadata) {
JsonElement downloadsElement = GetJsonPropertyOrThrow(versionMetadata, "downloads", JsonValueKind.Object, "version metadata");
JsonElement serverElement = GetJsonPropertyOrThrow(downloadsElement, "server", JsonValueKind.Object, "downloads object in version metadata");
JsonElement urlElement = GetJsonPropertyOrThrow(serverElement, "url", JsonValueKind.String, "downloads.server object in version metadata");
string? url = urlElement.GetString();
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri)) {
Logger.Error("The \"url\" key in downloads.server object in version metadata does not contain a valid URL: {Url}", url);
throw StopProcedureException.Instance;
}
if (uri.Scheme != "https" || !uri.AbsolutePath.EndsWith(".jar", StringComparison.OrdinalIgnoreCase)) {
Logger.Error("The \"url\" key in downloads.server object in version metadata does not contain a accepted URL: {Url}", url);
throw StopProcedureException.Instance;
}
JsonElement sizeElement = GetJsonPropertyOrThrow(serverElement, "size", JsonValueKind.Number, "downloads.server object in version metadata");
ulong size;
try {
size = sizeElement.GetUInt64();
} catch (FormatException) {
Logger.Error("The \"size\" key in downloads.server object in version metadata contains an invalid file size: {Size}", sizeElement);
throw StopProcedureException.Instance;
}
JsonElement sha1Element = GetJsonPropertyOrThrow(serverElement, "sha1", JsonValueKind.String, "downloads.server object in version metadata");
Sha1String hash;
try {
hash = Sha1String.FromString(sha1Element.GetString());
} catch (Exception) {
Logger.Error("The \"sha1\" key in downloads.server object in version metadata does not contain a valid SHA-1 hash: {Sha1}", sha1Element.GetString());
throw StopProcedureException.Instance;
}
return new FileDownloadInfo(url, hash, new FileSize(size));
}
private static JsonElement GetJsonPropertyOrThrow(JsonElement parentElement, string propertyKey, JsonValueKind expectedKind, string location) {
if (!parentElement.TryGetProperty(propertyKey, out var valueElement)) {
Logger.Error("Missing \"{Property}\" key in " + location + ".", propertyKey);
throw StopProcedureException.Instance;
}
if (valueElement.ValueKind != expectedKind) {
Logger.Error("The \"{Property}\" key in " + location + " does not contain a JSON {ExpectedType}. Actual type: {ActualType}", propertyKey, expectedKind, valueElement.ValueKind);
throw StopProcedureException.Instance;
}
return valueElement;
}
} }

View File

@ -46,7 +46,7 @@ public sealed class RpcLauncher : RpcRuntime<ServerSocket> {
void OnConnectionClosed(object? sender, RpcClientConnectionClosedEventArgs e) { void OnConnectionClosed(object? sender, RpcClientConnectionClosedEventArgs e) {
clients.Remove(e.RoutingId); clients.Remove(e.RoutingId);
logger.Verbose("Closed connection to {RoutingId}.", e.RoutingId); logger.Debug("Closed connection to {RoutingId}.", e.RoutingId);
} }
while (!cancellationToken.IsCancellationRequested) { while (!cancellationToken.IsCancellationRequested) {

View File

@ -40,7 +40,7 @@ public sealed class PhantomLoginManager {
var result = await signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true); var result = await signInManager.CheckPasswordSignInAsync(user, password, lockoutOnFailure: true);
if (result == SignInResult.Success) { if (result == SignInResult.Success) {
Logger.Verbose("Created login token for {Username}.", username); Logger.Debug("Created login token for {Username}.", username);
string token = TokenGenerator.Create(60); string token = TokenGenerator.Create(60);
loginStore.Add(token, user, password, returnUrl ?? string.Empty); loginStore.Add(token, user, password, returnUrl ?? string.Empty);

View File

@ -30,7 +30,7 @@ public sealed class PhantomLoginStore {
foreach (var (token, entry) in loginEntries) { foreach (var (token, entry) in loginEntries) {
if (entry.IsExpired) { if (entry.IsExpired) {
Logger.Verbose("Expired login entry for {Username}.", entry.User.UserName); Logger.Debug("Expired login entry for {Username}.", entry.User.UserName);
loginEntries.TryRemove(token, out _); loginEntries.TryRemove(token, out _);
} }
} }
@ -50,7 +50,7 @@ public sealed class PhantomLoginStore {
} }
if (entry.IsExpired) { if (entry.IsExpired) {
Logger.Verbose("Expired login entry for {Username}.", entry.User.UserName); Logger.Debug("Expired login entry for {Username}.", entry.User.UserName);
return null; return null;
} }

View File

@ -15,7 +15,7 @@ public abstract class CancellableBackgroundTask {
} }
private async Task Run() { private async Task Run() {
Logger.Verbose("Task started."); Logger.Debug("Task started.");
try { try {
await RunTask(); await RunTask();
@ -25,7 +25,7 @@ public abstract class CancellableBackgroundTask {
Logger.Fatal(e, "Caught exception in task."); Logger.Fatal(e, "Caught exception in task.");
} finally { } finally {
cancellationTokenSource.Dispose(); cancellationTokenSource.Dispose();
Logger.Verbose("Task stopped."); Logger.Debug("Task stopped.");
} }
} }

View File

@ -50,7 +50,7 @@ public sealed class OneShotProcess {
return false; return false;
} }
logger.Verbose("Process finished successfully."); logger.Debug("Process finished successfully.");
return true; return true;
} }