Files
AI-Studio/app/MindWork AI Studio/Tools/PluginSystem/PluginFactory.Download.cs
T

151 lines
7.4 KiB
C#
Raw Normal View History

2025-06-02 20:08:25 +02:00
using System.Net.Http.Headers;
namespace AIStudio.Tools.PluginSystem;
public static partial class PluginFactory
{
2026-02-19 20:43:47 +01:00
public static async Task<(bool Success, EntityTagHeaderValue? ETag, string? Issue)> DetermineConfigPluginETagAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default)
2025-06-02 20:08:25 +02:00
{
if(configPlugId == Guid.Empty || string.IsNullOrWhiteSpace(configServerUrl))
2026-02-19 20:43:47 +01:00
return (false, null, "Configuration ID or server URL is missing.");
2025-06-02 20:08:25 +02:00
try
{
var serverUrl = configServerUrl.EndsWith('/') ? configServerUrl[..^1] : configServerUrl;
var downloadUrl = $"{serverUrl}/{configPlugId}.zip";
using var http = ExternalHttpClientTimeout.CreateHttpClient(ExternalHttpTrustPolicy.ALLOW_CUSTOM_ROOTS_WHEN_HOST_WHITELISTED);
2025-06-02 20:08:25 +02:00
using var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl);
var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
2026-02-19 20:43:47 +01:00
if (!response.IsSuccessStatusCode)
{
LOG.LogError($"Failed to determine the ETag for configuration plugin '{configPlugId}'. HTTP Status: {response.StatusCode}");
return (false, null, $"HTTP status: {response.StatusCode}");
}
return (true, response.Headers.ETag, null);
2025-06-02 20:08:25 +02:00
}
catch (Exception e)
{
LOG.LogError(e, "An error occurred while determining the ETag for the configuration plugin.");
2026-02-19 20:43:47 +01:00
return (false, null, e.Message);
2025-06-02 20:08:25 +02:00
}
}
public static async Task<bool> TryDownloadingConfigPluginAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default)
{
2026-02-19 20:43:47 +01:00
if(!IsInitialized)
2025-06-02 20:08:25 +02:00
{
LOG.LogWarning("Plugin factory is not yet initialized. Cannot download configuration plugin.");
return false;
2025-06-02 20:08:25 +02:00
}
2025-06-02 20:08:25 +02:00
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})");
string? downloadDirectory = null;
2026-02-19 20:43:47 +01:00
string? backupDirectory = null;
var wasSuccessful = false;
try
{
2025-06-09 14:06:54 +02:00
await LockHotReloadAsync();
// In the temporary folder of AI Studio, below the data directory: on the drive of the plugins, so the new configuration can move there:
downloadDirectory = TemporaryFiles.CreateDirectory();
var tempDownloadFile = Path.Join(downloadDirectory, $"{configPlugId}.zip");
var stagedDirectory = Path.Join(downloadDirectory, configPlugId.ToString());
using var httpClient = ExternalHttpClientTimeout.CreateHttpClient(ExternalHttpTrustPolicy.ALLOW_CUSTOM_ROOTS_WHEN_HOST_WHITELISTED);
// Only the headers, so the archive goes to the disk instead of into memory. The time limit of the client
// then covers the headers alone, so the token keeps it for the whole download:
using var downloadTimeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
downloadTimeout.CancelAfter(httpClient.Timeout);
using var response = await httpClient.GetAsync(downloadUrl, HttpCompletionOption.ResponseHeadersRead, downloadTimeout.Token);
2026-02-19 20:43:47 +01:00
if (!response.IsSuccessStatusCode)
{
LOG.LogError($"Failed to download the enterprise configuration plugin. HTTP Status: {response.StatusCode}");
2026-02-19 20:43:47 +01:00
return false;
}
await using(var tempFileStream = File.Create(tempDownloadFile))
{
await response.Content.CopyToAsync(tempFileStream, downloadTimeout.Token);
2026-02-19 20:43:47 +01:00
}
await ExtractConfigPluginArchiveAsync(tempDownloadFile, stagedDirectory, cancellationToken);
2026-02-19 20:43:47 +01:00
var configDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString());
2026-02-19 20:43:47 +01:00
if (Directory.Exists(configDirectory))
{
backupDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, $"{configPlugId}.backup-{Guid.NewGuid():N}");
2026-02-19 20:43:47 +01:00
Directory.Move(configDirectory, backupDirectory);
}
MoveDeploymentIntoPlace(stagedDirectory, configDirectory);
2026-02-19 20:43:47 +01:00
if (!string.IsNullOrWhiteSpace(backupDirectory) && Directory.Exists(backupDirectory))
Directory.Delete(backupDirectory, true);
LOG.LogInformation($"Configuration plugin with ID='{configPlugId}' downloaded and extracted successfully to '{configDirectory}'.");
wasSuccessful = true;
}
catch (Exception e)
{
LOG.LogError(e, "An error occurred while downloading or extracting the enterprise configuration plugin.");
2026-02-19 20:43:47 +01:00
var configDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString());
2026-02-19 20:43:47 +01:00
if (!string.IsNullOrWhiteSpace(backupDirectory) && Directory.Exists(backupDirectory) && !Directory.Exists(configDirectory))
{
try
{
Directory.Move(backupDirectory, configDirectory);
}
catch (Exception restoreException)
{
LOG.LogError(restoreException, "Failed to restore the previous configuration plugin after a failed update.");
}
}
}
finally
{
if (downloadDirectory is not null && Directory.Exists(downloadDirectory))
2026-02-19 20:43:47 +01:00
{
try
{
Directory.Delete(downloadDirectory, true);
2026-02-19 20:43:47 +01:00
}
catch (Exception e)
{
LOG.LogError(e, "Failed to delete the downloaded configuration plugin. The next start of AI Studio deletes it.");
2026-02-19 20:43:47 +01:00
}
}
2025-06-09 14:06:54 +02:00
UnlockHotReload();
}
2026-02-19 20:43:47 +01:00
return wasSuccessful;
}
/// <summary>
/// Moves a downloaded deployment of an organization from the temporary folder of AI Studio to its place.
/// </summary>
/// <remarks>
/// Unlike unpacking, Directory.Move creates no missing folders above its destination. The folder of the
/// deployments is missing on a new installation until the first deployment arrives, and once somebody deleted it.
/// </remarks>
/// <param name="stagedDirectory">The unpacked deployment.</param>
/// <param name="deploymentDirectory">The directory of the deployment, named after its configuration ID. It must not exist.</param>
internal static void MoveDeploymentIntoPlace(string stagedDirectory, string deploymentDirectory)
{
Directory.CreateDirectory(Path.GetDirectoryName(deploymentDirectory)!);
Directory.Move(stagedDirectory, deploymentDirectory);
}
private static async Task ExtractConfigPluginArchiveAsync(string sourceArchiveFileName, string destinationDirectory, CancellationToken token)
{
await PluginArchive.ExtractAsync(sourceArchiveFileName, destinationDirectory, token);
if (!Directory.EnumerateFiles(destinationDirectory, "plugin.lua", SearchOption.AllDirectories).Any())
throw new InvalidDataException("The enterprise configuration plugin archive does not contain a plugin.lua file.");
}
}