using System.Net.Http.Headers; namespace AIStudio.Tools.PluginSystem; public static partial class PluginFactory { public static async Task<(bool Success, EntityTagHeaderValue? ETag, string? Issue)> DetermineConfigPluginETagAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default) { if(configPlugId == Guid.Empty || string.IsNullOrWhiteSpace(configServerUrl)) return (false, null, "Configuration ID or server URL is missing."); 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); using var request = new HttpRequestMessage(HttpMethod.Get, downloadUrl); var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken); 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); } catch (Exception e) { LOG.LogError(e, "An error occurred while determining the ETag for the configuration plugin."); return (false, null, e.Message); } } public static async Task TryDownloadingConfigPluginAsync(Guid configPlugId, string configServerUrl, CancellationToken cancellationToken = default) { if(!IsInitialized) { LOG.LogWarning("Plugin factory is not yet initialized. Cannot download configuration plugin."); return false; } 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; string? backupDirectory = null; var wasSuccessful = false; try { 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); if (!response.IsSuccessStatusCode) { LOG.LogError($"Failed to download the enterprise configuration plugin. HTTP Status: {response.StatusCode}"); return false; } await using(var tempFileStream = File.Create(tempDownloadFile)) { await response.Content.CopyToAsync(tempFileStream, downloadTimeout.Token); } await ExtractConfigPluginArchiveAsync(tempDownloadFile, stagedDirectory, cancellationToken); var configDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString()); if (Directory.Exists(configDirectory)) { backupDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, $"{configPlugId}.backup-{Guid.NewGuid():N}"); Directory.Move(configDirectory, backupDirectory); } MoveDeploymentIntoPlace(stagedDirectory, configDirectory); 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."); var configDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, configPlugId.ToString()); 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)) { try { Directory.Delete(downloadDirectory, true); } catch (Exception e) { LOG.LogError(e, "Failed to delete the downloaded configuration plugin. The next start of AI Studio deletes it."); } } UnlockHotReload(); } return wasSuccessful; } /// /// Moves a downloaded deployment of an organization from the temporary folder of AI Studio to its place. /// /// /// 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. /// /// The unpacked deployment. /// The directory of the deployment, named after its configuration ID. It must not exist. 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."); } }