mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-10-17 05:17:59 +00:00
Improved enterprise service (#493)
This commit is contained in:
1 parent
fcf511cea8
commit
6979a73e5c
12 files changed
+191
-118
No files matched your search
@@ -1,6 +1,8 @@
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace AIStudio.Tools;
|
||||
|
||||
public readonly record struct EnterpriseEnvironment(string ConfigurationServerUrl, Guid ConfigurationId)
|
||||
public readonly record struct EnterpriseEnvironment(string ConfigurationServerUrl, Guid ConfigurationId, EntityTagHeaderValue? ETag)
|
||||
{
|
||||
public bool IsActive => !string.IsNullOrEmpty(this.ConfigurationServerUrl) && this.ConfigurationId != Guid.Empty;
|
||||
}
|
||||
@@ -9,6 +9,7 @@ public enum Event
|
||||
CONFIGURATION_CHANGED,
|
||||
COLOR_THEME_CHANGED,
|
||||
STARTUP_PLUGIN_SYSTEM,
|
||||
STARTUP_ENTERPRISE_ENVIRONMENT,
|
||||
PLUGINS_RELOADED,
|
||||
SHOW_ERROR,
|
||||
SHOW_WARNING,
|
||||
|
||||
@@ -15,9 +15,17 @@ public sealed class MessageBus
|
||||
private readonly ConcurrentQueue<Message> messageQueue = new();
|
||||
private readonly SemaphoreSlim sendingSemaphore = new(1, 1);
|
||||
|
||||
private static ILogger<MessageBus>? LOG;
|
||||
|
||||
private MessageBus()
|
||||
{
|
||||
}
|
||||
|
||||
public void Initialize(ILogger<MessageBus> logger)
|
||||
{
|
||||
LOG = logger;
|
||||
LOG.LogInformation("Message bus initialized.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Define for which components and events you want to receive messages.
|
||||
@@ -48,7 +56,7 @@ public sealed class MessageBus
|
||||
public async Task SendMessage<T>(ComponentBase? sendingComponent, Event triggeredEvent, T? data = default)
|
||||
{
|
||||
this.messageQueue.Enqueue(new Message(sendingComponent, triggeredEvent, data));
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
await this.sendingSemaphore.WaitAsync();
|
||||
@@ -61,11 +69,16 @@ public sealed class MessageBus
|
||||
|
||||
var eventFilter = this.componentEvents[receiver];
|
||||
if (eventFilter.Length == 0 || eventFilter.Contains(triggeredEvent))
|
||||
|
||||
// We don't await the task here because we don't want to block the message bus:
|
||||
_ = receiver.ProcessMessage(message.SendingComponent, message.TriggeredEvent, message.Data);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG?.LogError(e, "Error while sending message.");
|
||||
}
|
||||
finally
|
||||
{
|
||||
this.sendingSemaphore.Release();
|
||||
|
||||
@@ -1,33 +1,61 @@
|
||||
using System.IO.Compression;
|
||||
using System.Net.Http.Headers;
|
||||
|
||||
namespace AIStudio.Tools.PluginSystem;
|
||||
|
||||
public static partial class PluginFactory
|
||||
{
|
||||
public static async Task<EntityTagHeaderValue?> DetermineConfigPluginETagAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
var serverUrl = configServerUrl.EndsWith('/') ? configServerUrl[..^1] : configServerUrl;
|
||||
var downloadUrl = $"{serverUrl}/{configPlugId}.zip";
|
||||
|
||||
using var http = new HttpClient();
|
||||
using var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
|
||||
var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
|
||||
return response.Headers.ETag;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogError(e, "An error occurred while determining the ETag for the configuration plugin.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<bool> TryDownloadingConfigPluginAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!IS_INITIALIZED)
|
||||
if(!IS_INITIALIZED)
|
||||
{
|
||||
LOG.LogWarning("Plugin factory is not yet initialized. Cannot download configuration plugin.");
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG.LogInformation($"Downloading configuration plugin with ID: {configPlugId} from server: {configServerUrl}");
|
||||
var serverUrl = configServerUrl.EndsWith('/') ? configServerUrl[..^1] : configServerUrl;
|
||||
var downloadUrl = $"{serverUrl}/{configPlugId}.zip";
|
||||
|
||||
LOG.LogInformation($"Try to download configuration plugin with ID='{configPlugId}' from server='{configServerUrl}' (GET {downloadUrl})");
|
||||
var tempDownloadFile = Path.GetTempFileName();
|
||||
try
|
||||
{
|
||||
using var httpClient = new HttpClient();
|
||||
var response = await httpClient.GetAsync($"{configServerUrl}/{configPlugId}.zip", cancellationToken);
|
||||
var response = await httpClient.GetAsync(downloadUrl, cancellationToken);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
await using var tempFileStream = File.Create(tempDownloadFile);
|
||||
await response.Content.CopyToAsync(tempFileStream, cancellationToken);
|
||||
await using(var tempFileStream = File.Create(tempDownloadFile))
|
||||
{
|
||||
await response.Content.CopyToAsync(tempFileStream, cancellationToken);
|
||||
}
|
||||
|
||||
var pluginDirectory = Path.Join(CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString());
|
||||
if(Directory.Exists(pluginDirectory))
|
||||
Directory.Delete(pluginDirectory, true);
|
||||
var configDirectory = Path.Join(CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString());
|
||||
if(Directory.Exists(configDirectory))
|
||||
Directory.Delete(configDirectory, true);
|
||||
|
||||
Directory.CreateDirectory(pluginDirectory);
|
||||
ZipFile.ExtractToDirectory(tempDownloadFile, pluginDirectory);
|
||||
Directory.CreateDirectory(configDirectory);
|
||||
ZipFile.ExtractToDirectory(tempDownloadFile, configDirectory);
|
||||
|
||||
LOG.LogInformation($"Configuration plugin with ID='{configPlugId}' downloaded and extracted successfully to '{pluginDirectory}'.");
|
||||
LOG.LogInformation($"Configuration plugin with ID='{configPlugId}' downloaded and extracted successfully to '{configDirectory}'.");
|
||||
}
|
||||
else
|
||||
LOG.LogError($"Failed to download the enterprise configuration plugin. HTTP Status: {response.StatusCode}");
|
||||
|
||||
@@ -46,6 +46,9 @@ public static partial class PluginFactory
|
||||
try
|
||||
{
|
||||
LOG.LogInformation($"File changed ({changeType}): {args.FullPath}. Reloading plugins...");
|
||||
|
||||
// Wait for parallel writes to finish:
|
||||
await Task.Delay(TimeSpan.FromSeconds(3));
|
||||
await LoadAll();
|
||||
await MessageBus.INSTANCE.SendMessage<bool>(null, Event.PLUGINS_RELOADED);
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ public static partial class PluginFactory
|
||||
if(IS_INITIALIZED)
|
||||
return false;
|
||||
|
||||
LOG.LogInformation("Initializing plugin factory...");
|
||||
DATA_DIR = SettingsManager.DataDirectory!;
|
||||
PLUGINS_ROOT = Path.Join(DATA_DIR, "plugins");
|
||||
INTERNAL_PLUGINS_ROOT = Path.Join(PLUGINS_ROOT, ".internal");
|
||||
@@ -37,7 +38,7 @@ public static partial class PluginFactory
|
||||
|
||||
HOT_RELOAD_WATCHER = new(PLUGINS_ROOT);
|
||||
IS_INITIALIZED = true;
|
||||
|
||||
LOG.LogInformation("Plugin factory initialized successfully.");
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,11 +2,15 @@ using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
public sealed class EnterpriseEnvironmentService(ILogger<TemporaryChatService> logger, RustService rustService) : BackgroundService
|
||||
public sealed class EnterpriseEnvironmentService(ILogger<EnterpriseEnvironmentService> logger, RustService rustService) : BackgroundService
|
||||
{
|
||||
public static EnterpriseEnvironment CURRENT_ENVIRONMENT;
|
||||
|
||||
|
||||
#if DEBUG
|
||||
private static readonly TimeSpan CHECK_INTERVAL = TimeSpan.FromMinutes(6);
|
||||
#else
|
||||
private static readonly TimeSpan CHECK_INTERVAL = TimeSpan.FromMinutes(16);
|
||||
#endif
|
||||
|
||||
#region Overrides of BackgroundService
|
||||
|
||||
@@ -14,7 +18,7 @@ public sealed class EnterpriseEnvironmentService(ILogger<TemporaryChatService> l
|
||||
{
|
||||
logger.LogInformation("The enterprise environment service was initialized.");
|
||||
|
||||
await this.StartUpdating();
|
||||
await this.StartUpdating(isFirstRun: true);
|
||||
while (!stoppingToken.IsCancellationRequested)
|
||||
{
|
||||
await Task.Delay(CHECK_INTERVAL, stoppingToken);
|
||||
@@ -24,7 +28,7 @@ public sealed class EnterpriseEnvironmentService(ILogger<TemporaryChatService> l
|
||||
|
||||
#endregion
|
||||
|
||||
private async Task StartUpdating()
|
||||
private async Task StartUpdating(bool isFirstRun = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
@@ -40,7 +44,8 @@ public sealed class EnterpriseEnvironmentService(ILogger<TemporaryChatService> l
|
||||
|
||||
var enterpriseConfigServerUrl = await rustService.EnterpriseEnvConfigServerUrl();
|
||||
var enterpriseConfigId = await rustService.EnterpriseEnvConfigId();
|
||||
var nextEnterpriseEnvironment = new EnterpriseEnvironment(enterpriseConfigServerUrl, enterpriseConfigId);
|
||||
var etag = await PluginFactory.DetermineConfigPluginETagAsync(enterpriseConfigId, enterpriseConfigServerUrl);
|
||||
var nextEnterpriseEnvironment = new EnterpriseEnvironment(enterpriseConfigServerUrl, enterpriseConfigId, etag);
|
||||
if (CURRENT_ENVIRONMENT != nextEnterpriseEnvironment)
|
||||
{
|
||||
logger.LogInformation("The enterprise environment has changed. Updating the current environment.");
|
||||
@@ -62,10 +67,16 @@ public sealed class EnterpriseEnvironmentService(ILogger<TemporaryChatService> l
|
||||
|
||||
default:
|
||||
logger.LogInformation($"AI Studio runs with an enterprise configuration id ('{enterpriseConfigId}') and configuration server URL ('{enterpriseConfigServerUrl}').");
|
||||
await PluginFactory.TryDownloadingConfigPluginAsync(enterpriseConfigId, enterpriseConfigServerUrl);
|
||||
|
||||
if(isFirstRun)
|
||||
MessageBus.INSTANCE.DeferMessage(null, Event.STARTUP_ENTERPRISE_ENVIRONMENT, new EnterpriseEnvironment(enterpriseConfigServerUrl, enterpriseConfigId, etag));
|
||||
else
|
||||
await PluginFactory.TryDownloadingConfigPluginAsync(enterpriseConfigId, enterpriseConfigServerUrl);
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
logger.LogInformation("The enterprise environment has not changed. No update required.");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user