mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-04 10:06:27 +00:00
Moved temporary files into a folder of their own below the data directory (#1245)
This commit is contained in:
1 parent
ddfc632b63
commit
12d3e1ec6c
52 files changed
+1219
-396
No files matched your search
@@ -1,4 +1,3 @@
|
||||
using AIStudio.Tools.OpenXml;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
|
||||
namespace AIStudio.Tools.DataBackup;
|
||||
@@ -57,12 +56,9 @@ public static class DataBackupContents
|
||||
new(DataBackupLocation.DATA_DIRECTORY, "plugins/.config/", DataBackupEntryKind.ORGANIZATION_PLUGINS),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, "plugins/.config-tests/", DataBackupEntryKind.ORGANIZATION_PLUGINS),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, "plugins/.lock", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, ".plugin-staging/", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, StagedDocument.DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, ".plugin-install-backups/", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, ".plugin-delete-backups/", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, "media-staging/", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, "mailAttachments/", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, TemporaryFiles.DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, "mindwork_ai_studio.pid", DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, DataBackupFormat.STAGING_DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
|
||||
new(DataBackupLocation.DATA_DIRECTORY, DataRestoreFormat.PENDING_DIRECTORY, DataBackupEntryKind.TEMPORARY_FILES),
|
||||
|
||||
+3
@@ -7,8 +7,11 @@ internal sealed class IndexStoreDesignTimeDbContextFactory : IDesignTimeDbContex
|
||||
public IndexStoreDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var databasePath = args.FirstOrDefault(argument => argument.EndsWith(".sqlite3", StringComparison.OrdinalIgnoreCase));
|
||||
// Only dotnet ef runs this, while it creates a migration, so neither AI Studio nor its data directory is there:
|
||||
#pragma warning disable MWAIS0019
|
||||
if (string.IsNullOrWhiteSpace(databasePath))
|
||||
databasePath = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-rag-index-design.sqlite3");
|
||||
#pragma warning restore MWAIS0019
|
||||
|
||||
return new IndexStoreDbContext(IndexStoreDbContext.CreateOptions(databasePath));
|
||||
}
|
||||
|
||||
+3
@@ -7,8 +7,11 @@ internal sealed class ProvenanceStoreDesignTimeDbContextFactory : IDesignTimeDbC
|
||||
public ProvenanceStoreDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var databasePath = args.FirstOrDefault(argument => argument.EndsWith(".sqlite3", StringComparison.OrdinalIgnoreCase));
|
||||
// Only dotnet ef runs this, while it creates a migration, so neither AI Studio nor its data directory is there:
|
||||
#pragma warning disable MWAIS0019
|
||||
if (string.IsNullOrWhiteSpace(databasePath))
|
||||
databasePath = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-provenance-design.sqlite3");
|
||||
#pragma warning restore MWAIS0019
|
||||
|
||||
return new ProvenanceStoreDbContext(ProvenanceStoreDbContext.CreateOptions(databasePath));
|
||||
}
|
||||
|
||||
@@ -58,8 +58,8 @@ the repository root and to `app/AGENTS.md`, which apply here as well.
|
||||
with the SDK: it reads and writes through a `PackageSkeleton` from `app/MindWork AI Studio/Tools/OpenXml/`, which
|
||||
holds only the XML of the source. The writer changes the DOM of the skeleton, opened for reading only, and the
|
||||
skeleton writes a new archive with the changed parts, in which every other entry streams through as it is, a stored
|
||||
one stays stored. Skeleton and new document come about in `StagedDocument`s below the data directory, not in the
|
||||
temporary folder, and `TargetFile` streams the new document into the file the user chose. A writer therefore changes
|
||||
one stays stored. Skeleton and new document come about in `StagedDocument`s in the temporary folder of AI Studio below the
|
||||
data directory (`TemporaryFiles`), not in the one of the system, and `TargetFile` streams the new document into the file the user chose. A writer therefore changes
|
||||
only the XML of existing parts and never adds or removes parts or relationships. A new Office format brings only its
|
||||
reader, its writer, and the element of each paragraph (`ElementOf`).
|
||||
|
||||
|
||||
@@ -1,31 +1,22 @@
|
||||
using AIStudio.Settings;
|
||||
|
||||
namespace AIStudio.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// A file below the data directory, in which a new Office document or a piece of it comes about, such as the skeleton
|
||||
/// of a document or a picture for it, before the document goes into the file the user chose, see TargetFile.
|
||||
/// A file in the temporary folder of AI Studio, in which a new Office document or a piece of it comes about, such as
|
||||
/// the skeleton of a document or a picture for it, before the document goes into the file the user chose, see
|
||||
/// TargetFile.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The folder lies below the data directory rather than in the temporary folder of the system: on many Linux
|
||||
/// systems, the temporary folder lives in memory (tmpfs), and a document with videos takes hundreds of megabytes.
|
||||
/// A backup leaves the folder out, see DataBackupContents.
|
||||
/// The temporary folder of AI Studio lies below the data directory rather than in the temporary folder of the system:
|
||||
/// on many Linux systems, the temporary folder lives in memory (tmpfs), and a document with videos takes hundreds of
|
||||
/// megabytes, see TemporaryFiles.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Disposing the file removes it. A file left behind, e.g., after a crash, is removed by the next document which
|
||||
/// comes about here, once it is a day old. Tests, which have no data directory, use the temporary folder.
|
||||
/// Disposing the file removes it. A file left behind, e.g., after a crash, is gone with the next start of AI Studio.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class StagedDocument : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// The folder below the data directory, see DataBackupContents.
|
||||
/// </summary>
|
||||
public const string DIRECTORY = ".document-staging/";
|
||||
|
||||
private static readonly TimeSpan AGE_OF_LEFTOVERS = TimeSpan.FromDays(1);
|
||||
|
||||
private readonly ILogger logger;
|
||||
|
||||
private StagedDocument(string filePath, ILogger logger)
|
||||
@@ -40,19 +31,12 @@ internal sealed class StagedDocument : IDisposable
|
||||
public string FilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Reserves a file for a new document and removes what earlier documents left behind.
|
||||
/// Reserves a file for a new document.
|
||||
/// </summary>
|
||||
/// <param name="fileExtension">The extension of the document, including the leading dot.</param>
|
||||
/// <param name="logger">Where to report a file which cannot be removed.</param>
|
||||
/// <returns>The file, which does not exist yet.</returns>
|
||||
public static StagedDocument Create(string fileExtension, ILogger logger)
|
||||
{
|
||||
var directory = Path.Join(SettingsManager.DataDirectory ?? Path.GetTempPath(), DIRECTORY);
|
||||
Directory.CreateDirectory(directory);
|
||||
RemoveLeftovers(directory, logger);
|
||||
|
||||
return new StagedDocument(Path.Join(directory, $"{Guid.NewGuid():N}{fileExtension}"), logger);
|
||||
}
|
||||
public static StagedDocument Create(string fileExtension, ILogger logger) => new(TemporaryFiles.GetFilePath(fileExtension), logger);
|
||||
|
||||
/// <summary>
|
||||
/// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync.
|
||||
@@ -65,17 +49,4 @@ internal sealed class StagedDocument : IDisposable
|
||||
/// Removes the file.
|
||||
/// </summary>
|
||||
public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger);
|
||||
|
||||
/// <summary>
|
||||
/// Removes the files which are older than a day, e.g., after a crash.
|
||||
/// </summary>
|
||||
private static void RemoveLeftovers(string directory, ILogger logger)
|
||||
{
|
||||
var oldest = DateTime.UtcNow - AGE_OF_LEFTOVERS;
|
||||
foreach (var file in new DirectoryInfo(directory).EnumerateFiles())
|
||||
{
|
||||
if (file.LastWriteTimeUtc < oldest)
|
||||
TargetFile.DeleteQuietly(file.FullName, logger);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Formats.Tar;
|
||||
using System.IO.Compression;
|
||||
using System.Text.RegularExpressions;
|
||||
@@ -40,6 +41,16 @@ public static partial class Pandoc
|
||||
/// </summary>
|
||||
private static bool HAS_LOGGED_SUCCESSFUL_CHECK_ONCE;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks whether a missing Pandoc was already logged since the last check which could start it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Most users have no Pandoc until they install it through AI Studio. That is a stable state, not a failure, so
|
||||
/// it is logged once, like <see cref="HAS_LOGGED_EXECUTABLE_ONCE"/>. A check which can start Pandoc resets it, so
|
||||
/// that a Pandoc which disappears later shows up in the log again.
|
||||
/// </remarks>
|
||||
private static bool HAS_LOGGED_MISSING_ONCE;
|
||||
|
||||
private static readonly HttpClient WEB_CLIENT = new();
|
||||
private static readonly SemaphoreSlim INSTALLATION_LOCK = new(1, 1);
|
||||
|
||||
@@ -78,6 +89,8 @@ public static partial class Pandoc
|
||||
return new(false, TB("Was not able to check the Pandoc installation."), false, string.Empty, preparedProcess.IsLocal);
|
||||
}
|
||||
|
||||
HAS_LOGGED_MISSING_ONCE = false;
|
||||
|
||||
// Read output streams asynchronously while the process runs (prevents deadlock):
|
||||
var outputTask = process.StandardOutput.ReadToEndAsync();
|
||||
var errorTask = process.StandardError.ReadToEndAsync();
|
||||
@@ -138,12 +151,29 @@ public static partial class Pandoc
|
||||
if (showMessages)
|
||||
await MessageBus.INSTANCE.SendError(new(@AppIcons.PANDOC_UNAVAILABLE, TB("Pandoc doesn't seem to be installed.")));
|
||||
|
||||
LOG.LogError(e, "Pandoc availability check failed. This usually means Pandoc is not installed or not in the system PATH.");
|
||||
if (!IsMissingExecutable(e))
|
||||
LOG.LogError(e, "The Pandoc availability check failed, but not because Pandoc is missing.");
|
||||
else if (!HAS_LOGGED_MISSING_ONCE)
|
||||
{
|
||||
LOG.LogInformation("Pandoc is not installed: AI Studio found it neither in its data directory nor on the system PATH.");
|
||||
HAS_LOGGED_MISSING_ONCE = true;
|
||||
}
|
||||
|
||||
return new(false, TB("Pandoc doesn't seem to be installed."), false, string.Empty, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Whether starting a process failed because its executable does not exist.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Windows reports ERROR_FILE_NOT_FOUND, macOS and Linux report ENOENT; both have the number 2. Any other failure, such as
|
||||
/// a denied access or a damaged executable, means that something exists which cannot be started.
|
||||
/// </remarks>
|
||||
/// <param name="exception">What Process.Start threw.</param>
|
||||
/// <returns>True, when the executable does not exist.</returns>
|
||||
internal static bool IsMissingExecutable(Exception exception) => exception is Win32Exception { NativeErrorCode: 2 };
|
||||
|
||||
/// <summary>
|
||||
/// Automatically decompresses the latest pandoc archive into AiStudio's data directory
|
||||
/// </summary>
|
||||
@@ -155,17 +185,21 @@ public static partial class Pandoc
|
||||
|
||||
var latestVersion = await FetchLatestVersionAsync();
|
||||
var installDir = await GetPandocDataFolder(rustService);
|
||||
var installParentDir = Path.GetDirectoryName(installDir) ?? Path.GetTempPath();
|
||||
var stagingDir = Path.Combine(installParentDir, $"pandoc-install-{Guid.NewGuid():N}");
|
||||
var pandocTempDownloadFile = Path.GetTempFileName();
|
||||
|
||||
string? downloadDir = null;
|
||||
|
||||
LOG.LogInformation("Trying to install Pandoc v{0} to '{1}'...", latestVersion, installDir);
|
||||
|
||||
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(installParentDir))
|
||||
Directory.CreateDirectory(installParentDir);
|
||||
|
||||
//
|
||||
// The archive and the new Pandoc stay in the temporary folder of AI Studio until the new Pandoc is
|
||||
// complete, so an interrupted installation leaves nothing next to the installation. The folder lies
|
||||
// below the data directory, on the same drive as the installation, so the new Pandoc can move there:
|
||||
//
|
||||
downloadDir = TemporaryFiles.CreateDirectory();
|
||||
var pandocTempDownloadFile = Path.Combine(downloadDir, "archive");
|
||||
var stagingDir = Path.Combine(downloadDir, "pandoc");
|
||||
|
||||
//
|
||||
// Download the latest Pandoc archive from GitHub:
|
||||
//
|
||||
@@ -177,7 +211,10 @@ public static partial class Pandoc
|
||||
return;
|
||||
}
|
||||
|
||||
using var response = await WEB_CLIENT.GetAsync(uri);
|
||||
// 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 = new CancellationTokenSource(WEB_CLIENT.Timeout);
|
||||
using var response = await WEB_CLIENT.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, downloadTimeout.Token);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
{
|
||||
await MessageBus.INSTANCE.SendError(new(AppIcons.ERROR, TB("AI Studio couldn't install Pandoc because the archive was not found.")));
|
||||
@@ -188,7 +225,7 @@ public static partial class Pandoc
|
||||
// Download the archive to the temporary file:
|
||||
await using (var tempFileStream = File.Create(pandocTempDownloadFile))
|
||||
{
|
||||
await response.Content.CopyToAsync(tempFileStream);
|
||||
await response.Content.CopyToAsync(tempFileStream, downloadTimeout.Token);
|
||||
await tempFileStream.FlushAsync();
|
||||
}
|
||||
|
||||
@@ -238,10 +275,8 @@ public static partial class Pandoc
|
||||
}
|
||||
finally
|
||||
{
|
||||
TryDeleteFile(pandocTempDownloadFile);
|
||||
|
||||
if (Directory.Exists(stagingDir))
|
||||
await TryDeleteFolderAsync(stagingDir);
|
||||
if (downloadDir is not null)
|
||||
await TryDeleteFolderAsync(downloadDir);
|
||||
|
||||
INSTALLATION_LOCK.Release();
|
||||
}
|
||||
@@ -337,21 +372,6 @@ public static partial class Pandoc
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryDeleteFile(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LOG.LogWarning(ex, "Was not able to delete temporary Pandoc archive: '{Path}'.", path);
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task TryDeleteFolderAsync(string path)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(path) || !Directory.Exists(path))
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
@@ -34,29 +33,21 @@ public static class PandocExport
|
||||
if (!format.UsesPandoc)
|
||||
throw new ArgumentOutOfRangeException(nameof(format), format, "Pandoc cannot write this format.");
|
||||
|
||||
var tempMarkdownFilePath = string.Empty;
|
||||
try
|
||||
{
|
||||
var tempMarkdownFile = Guid.NewGuid().ToString();
|
||||
tempMarkdownFilePath = Path.Combine(Path.GetTempPath(), tempMarkdownFile);
|
||||
|
||||
// Write text content to a temporary file. Pandoc expects UTF-8 without a byte order
|
||||
// mark; a mark would end up as a stray character at the start of the document:
|
||||
await File.WriteAllTextAsync(tempMarkdownFilePath, markdownText, new UTF8Encoding(false), token);
|
||||
|
||||
// Call Pandoc to create the document:
|
||||
// Call Pandoc to create the document. It reads the text from its standard input, so the text needs no temporary file:
|
||||
var pandocBuilder = PandocProcessBuilder
|
||||
.Create()
|
||||
.UseStandaloneMode()
|
||||
.WithInputFormat("gfm+emoji+tex_math_dollars")
|
||||
.WithOutputFormat(format.PandocOutputFormat)
|
||||
.WithOutputFile(targetFilePath)
|
||||
.WithInputFile(tempMarkdownFilePath);
|
||||
.WithStandardInput();
|
||||
|
||||
//
|
||||
// The document is named after the file it is written to. Set as metadata, the name
|
||||
// reaches the page as a string which Pandoc escapes; only a file named true or false
|
||||
// is read as a switch and keeps the temporary name.
|
||||
// is read as a switch, and the page gets the title Pandoc falls back to.
|
||||
//
|
||||
if (format.NeedsPageTitle)
|
||||
pandocBuilder.AddArgument("-M").AddArgument($"pagetitle={Path.GetFileNameWithoutExtension(targetFilePath)}");
|
||||
@@ -74,6 +65,16 @@ public static class PandocExport
|
||||
var outputTask = process.StandardOutput.ReadToEndAsync(token);
|
||||
var errorTask = process.StandardError.ReadToEndAsync(token);
|
||||
|
||||
try
|
||||
{
|
||||
await using var input = process.StandardInput;
|
||||
await input.WriteAsync(markdownText.AsMemory(), token);
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
// Pandoc stopped reading before the end of the text, e.g., over an invalid argument. Its exit code and error output below tell why.
|
||||
}
|
||||
|
||||
// Wait for the process to exit AND for streams to be fully read:
|
||||
await process.WaitForExitAsync(token);
|
||||
await outputTask;
|
||||
@@ -93,21 +94,6 @@ public static class PandocExport
|
||||
LOGGER.LogError(ex, "Error during {ExportFormat} conversion.", format);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Try to remove the temp file:
|
||||
if (!string.IsNullOrWhiteSpace(tempMarkdownFilePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(tempMarkdownFilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
LOGGER.LogWarning("Was not able to delete the temporary file '{TempFilePath}'.", tempMarkdownFilePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Diagnostics;
|
||||
using System.Text;
|
||||
|
||||
using AIStudio.Tools.Rust;
|
||||
using AIStudio.Tools.Services;
|
||||
@@ -17,26 +18,33 @@ public sealed class PandocProcessBuilder
|
||||
// Tracks whether the first log has been written to avoid log spam on repeated calls:
|
||||
private static bool HAS_LOGGED_ONCE;
|
||||
|
||||
private string? providedInputFile;
|
||||
private string? providedOutputFile;
|
||||
private string? providedInputFormat;
|
||||
private string? providedOutputFormat;
|
||||
private bool useStandaloneMode;
|
||||
|
||||
private bool readsStandardInput;
|
||||
|
||||
private readonly List<string> additionalArguments = new();
|
||||
|
||||
|
||||
private PandocProcessBuilder()
|
||||
{
|
||||
}
|
||||
|
||||
|
||||
public static PandocProcessBuilder Create() => new();
|
||||
|
||||
public PandocProcessBuilder WithInputFile(string inputFile)
|
||||
|
||||
/// <summary>
|
||||
/// Lets Pandoc read its input from the standard input of the process, in UTF-8 without a byte order mark,
|
||||
/// which Pandoc expects; a mark would end up as a stray character at the start of the document.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A text which AI Studio holds anyway thus needs no temporary file, see TemporaryFiles.
|
||||
/// </remarks>
|
||||
public PandocProcessBuilder WithStandardInput()
|
||||
{
|
||||
this.providedInputFile = inputFile;
|
||||
this.readsStandardInput = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
|
||||
public PandocProcessBuilder WithOutputFile(string outputFile)
|
||||
{
|
||||
this.providedOutputFile = outputFile;
|
||||
@@ -79,14 +87,17 @@ public sealed class PandocProcessBuilder
|
||||
CreateNoWindow = true
|
||||
};
|
||||
|
||||
if (this.readsStandardInput)
|
||||
{
|
||||
startInfo.RedirectStandardInput = true;
|
||||
startInfo.StandardInputEncoding = new UTF8Encoding(false);
|
||||
}
|
||||
|
||||
// Use argument tokens instead of a single command string so paths with spaces
|
||||
// or Unicode characters are passed to Pandoc unchanged on all platforms.
|
||||
if (this.useStandaloneMode)
|
||||
startInfo.ArgumentList.Add("--standalone");
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(this.providedInputFile))
|
||||
startInfo.ArgumentList.Add(this.providedInputFile);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(this.providedInputFormat))
|
||||
{
|
||||
startInfo.ArgumentList.Add("-f");
|
||||
@@ -149,8 +160,9 @@ public sealed class PandocProcessBuilder
|
||||
}
|
||||
else if (!Directory.Exists(localInstallationRootDirectory))
|
||||
{
|
||||
// The usual case until the user installs Pandoc through AI Studio, so no warning:
|
||||
if (shouldLog)
|
||||
LOGGER.LogWarning("The local Pandoc installation directory does not exist: '{LocalInstallationRootDirectory}'.", localInstallationRootDirectory);
|
||||
LOGGER.LogInformation("The local Pandoc installation directory does not exist: '{LocalInstallationRootDirectory}'.", localInstallationRootDirectory);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -223,7 +235,7 @@ public sealed class PandocProcessBuilder
|
||||
// When no local installation was found, we assume that the pandoc executable is in the system PATH:
|
||||
//
|
||||
if (shouldLog)
|
||||
LOGGER.LogWarning("Falling back to system PATH for the Pandoc executable: '{ExecutableName}'.", PandocExecutableName);
|
||||
LOGGER.LogInformation("Falling back to system PATH for the Pandoc executable: '{ExecutableName}'.", PandocExecutableName);
|
||||
|
||||
return new(PandocExecutableName, false);
|
||||
}
|
||||
|
||||
@@ -44,15 +44,24 @@ public static partial class PluginFactory
|
||||
var downloadUrl = $"{serverUrl}/{configPlugId}.zip";
|
||||
|
||||
LOG.LogInformation($"Try to download configuration plugin with ID='{configPlugId}' from server='{configServerUrl}' (GET {downloadUrl})");
|
||||
var tempDownloadFile = Path.GetTempFileName();
|
||||
var stagedDirectory = Path.Join(ENTERPRISE_CONFIGURATION_PLUGINS_ROOT, $"{configPlugId}.staging-{Guid.NewGuid():N}");
|
||||
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);
|
||||
var response = await httpClient.GetAsync(downloadUrl, cancellationToken);
|
||||
// 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}");
|
||||
@@ -61,7 +70,7 @@ public static partial class PluginFactory
|
||||
|
||||
await using(var tempFileStream = File.Create(tempDownloadFile))
|
||||
{
|
||||
await response.Content.CopyToAsync(tempFileStream, cancellationToken);
|
||||
await response.Content.CopyToAsync(tempFileStream, downloadTimeout.Token);
|
||||
}
|
||||
|
||||
await ExtractConfigPluginArchiveAsync(tempDownloadFile, stagedDirectory, cancellationToken);
|
||||
@@ -73,7 +82,7 @@ public static partial class PluginFactory
|
||||
Directory.Move(configDirectory, backupDirectory);
|
||||
}
|
||||
|
||||
Directory.Move(stagedDirectory, configDirectory);
|
||||
MoveDeploymentIntoPlace(stagedDirectory, configDirectory);
|
||||
if (!string.IsNullOrWhiteSpace(backupDirectory) && Directory.Exists(backupDirectory))
|
||||
Directory.Delete(backupDirectory, true);
|
||||
|
||||
@@ -99,36 +108,39 @@ public static partial class PluginFactory
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (Directory.Exists(stagedDirectory))
|
||||
if (downloadDirectory is not null && Directory.Exists(downloadDirectory))
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(stagedDirectory, true);
|
||||
Directory.Delete(downloadDirectory, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogError(e, "Failed to delete the staged configuration plugin directory.");
|
||||
LOG.LogError(e, "Failed to delete the downloaded configuration plugin. The next start of AI Studio deletes it.");
|
||||
}
|
||||
}
|
||||
|
||||
if (File.Exists(tempDownloadFile))
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(tempDownloadFile);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
LOG.LogError(e, "Failed to delete the temporary download file.");
|
||||
}
|
||||
}
|
||||
|
||||
UnlockHotReload();
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -29,8 +29,12 @@ public static partial class PluginFactory
|
||||
{
|
||||
var directoryName = Path.GetFileName(configurationDirectory);
|
||||
|
||||
// A download in flight stages and backs up next to the configuration directories. Those
|
||||
// directories belong to a running update, not to a withdrawn configuration:
|
||||
//
|
||||
// A download in flight backs up the previous configuration next to the configuration
|
||||
// directories. Such a directory belongs to a running update, not to a withdrawn
|
||||
// configuration. Earlier versions also staged the new configuration here; what they left
|
||||
// behind goes the way of every other directory which is no configuration:
|
||||
//
|
||||
if (IsTransientDownloadDirectory(directoryName))
|
||||
continue;
|
||||
|
||||
@@ -50,9 +54,7 @@ public static partial class PluginFactory
|
||||
/// Checks whether a directory below the enterprise configuration directory belongs to a running
|
||||
/// download instead of to an installed configuration.
|
||||
/// </summary>
|
||||
private static bool IsTransientDownloadDirectory(string directoryName) =>
|
||||
directoryName.Contains(".staging-", StringComparison.OrdinalIgnoreCase) ||
|
||||
directoryName.Contains(".backup-", StringComparison.OrdinalIgnoreCase);
|
||||
private static bool IsTransientDownloadDirectory(string directoryName) => directoryName.Contains(".backup-", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// Unloads every plugin stored in the given directory and deletes the directory afterwards.
|
||||
|
||||
@@ -1052,8 +1052,6 @@ public sealed partial class DataSourceEmbeddingService(SettingsManager settingsM
|
||||
if (!await WaitForFirstPluginLoadAsync(PluginFactory.FirstLoadCompleted, FIRST_PLUGIN_LOAD_TIMEOUT, token))
|
||||
logger.LogWarning("The plugins were not loaded within {TimeoutSeconds:F0} seconds. Indexing starts with the settings as they are, without what the configuration of an organization may add later.", FIRST_PLUGIN_LOAD_TIMEOUT.TotalSeconds);
|
||||
|
||||
// Before the first run: from then on, a sync may be writing an attachment there.
|
||||
MailAttachmentFiles.DeleteLeftovers(logger);
|
||||
await this.DeleteOrphanedMailboxIndexesAsync(token);
|
||||
|
||||
logger.LogInformation("Embedding background service is ready. Running the initial persisted hash check before activating file watchers.");
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
using AIStudio.Settings;
|
||||
|
||||
namespace AIStudio.Tools.Services.Indexing;
|
||||
|
||||
/// <summary>
|
||||
@@ -10,27 +8,18 @@ namespace AIStudio.Tools.Services.Indexing;
|
||||
/// for as long as its text is read, and is deleted right after. Their names are random: the
|
||||
/// runtime logs the path it reads, and the name of an attachment may name a person.
|
||||
///
|
||||
/// Whatever a crash left behind is deleted when AI Studio starts again, before the first mailbox
|
||||
/// is synced. That is why the files live in a directory of their own within the data directory of
|
||||
/// AI Studio, rather than in the temporary directory of the OS: deleting everything in it touches
|
||||
/// no file of another program.
|
||||
/// The files lie in the temporary folder of AI Studio, see TemporaryFiles. Whatever a crash left
|
||||
/// behind is deleted when AI Studio starts again.
|
||||
/// </remarks>
|
||||
internal static class MailAttachmentFiles
|
||||
{
|
||||
private const string DIRECTORY_NAME = "mailAttachments";
|
||||
|
||||
/// <summary>
|
||||
/// Makes up the path of a file for one attachment, and creates the directory it lies in.
|
||||
/// Makes up the path of a file for one attachment.
|
||||
/// </summary>
|
||||
/// <param name="extension">The extension of the attachment, checked against the known document types beforehand, without a dot.</param>
|
||||
/// <returns>The path, where no file exists yet.</returns>
|
||||
/// <exception cref="InvalidOperationException">The data directory is not known yet.</exception>
|
||||
public static string CreatePath(string extension)
|
||||
{
|
||||
var directory = GetDirectory() ?? throw new InvalidOperationException("The data directory is not known yet.");
|
||||
Directory.CreateDirectory(directory);
|
||||
return Path.Join(directory, $"{Guid.NewGuid():N}.{extension}");
|
||||
}
|
||||
/// <exception cref="InvalidOperationException">AI Studio has not set its temporary folder yet.</exception>
|
||||
public static string CreatePath(string extension) => TemporaryFiles.GetFilePath($".{extension}");
|
||||
|
||||
/// <summary>
|
||||
/// Deletes the file of one attachment, should it exist.
|
||||
@@ -48,31 +37,4 @@ internal static class MailAttachmentFiles
|
||||
logger.LogWarning(exception, "The temporary file '{Path}' of a mail attachment could not be deleted. It is deleted on the next start.", path);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes every file an earlier session of AI Studio left behind.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Only to be called before any mailbox is synced, since it deletes the files of a running sync as well.
|
||||
/// </remarks>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public static void DeleteLeftovers(ILogger logger)
|
||||
{
|
||||
if (GetDirectory() is not { } directory || !Directory.Exists(directory))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
logger.LogInformation("Deleted the temporary files of mail attachments an earlier session left behind.");
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "The temporary files of mail attachments in '{Directory}' could not be deleted.", directory);
|
||||
}
|
||||
}
|
||||
|
||||
private static string? GetDirectory() => string.IsNullOrWhiteSpace(SettingsManager.DataDirectory)
|
||||
? null
|
||||
: Path.Join(SettingsManager.DataDirectory, DIRECTORY_NAME);
|
||||
}
|
||||
@@ -498,8 +498,8 @@ public sealed class MediaTranscriptionService(
|
||||
/// <returns>A typed terminal result.</returns>
|
||||
private async Task<MediaTranscriptionResult> TranscribeCoreAsync(string mediaPath, MediaOperation operation, bool updateImportState, TranscriptionProvider? checkedProvider = null)
|
||||
{
|
||||
var normalizedPath = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-media", $"{operation.Id:N}.webm");
|
||||
Directory.CreateDirectory(Path.GetDirectoryName(normalizedPath)!);
|
||||
// Hours of a recording take hundreds of megabytes, see TemporaryFiles:
|
||||
var normalizedPath = TemporaryFiles.GetFilePath(".webm");
|
||||
|
||||
// Logged next to the operation ID: users recognize the file they picked, whereas an ID only
|
||||
// helps when correlating log lines. The name alone is enough and keeps full paths out of
|
||||
@@ -928,7 +928,10 @@ public sealed class MediaTranscriptionService(
|
||||
|
||||
try
|
||||
{
|
||||
// In the temporary folder of the system, unlike the upload: AI Studio empties its own one whenever it starts, and a diagnostic has to outlast a restart:
|
||||
#pragma warning disable MWAIS0019
|
||||
var diagnosticDirectory = Path.Combine(Path.GetTempPath(), "mindwork-ai-studio-media", "diagnostics");
|
||||
#pragma warning restore MWAIS0019
|
||||
Directory.CreateDirectory(diagnosticDirectory);
|
||||
var diagnosticPath = Path.Combine(diagnosticDirectory, $"{operationId:N}.webm");
|
||||
File.Move(normalizedPath, diagnosticPath, overwrite: true);
|
||||
|
||||
@@ -84,7 +84,7 @@ public sealed partial class PluginInstallService
|
||||
return PluginValidationResult.Failure(TB("The plugin system is not initialized yet."));
|
||||
|
||||
var pluginCode = lua.Trim();
|
||||
if (!this.TryCreateStagingDirectory(ASSISTANT_BUILDER_DIRECTORY_PREFIX, out var stagingDirectory, out var stagingIssue))
|
||||
if (!this.TryCreateStagingDirectory(out var stagingDirectory, out var stagingIssue))
|
||||
return PluginValidationResult.Failure(stagingIssue);
|
||||
|
||||
try
|
||||
|
||||
@@ -8,70 +8,43 @@ public sealed partial class PluginInstallService
|
||||
/// Creates a staging directory for a plugin that is about to be installed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The staging directory lives below the data directory, never below the temporary directory of
|
||||
/// the operating system. Installing means moving the staged plugin into the plugins directory,
|
||||
/// and a directory move cannot cross a file system boundary. Flatpak is the case where this
|
||||
/// always applies: its temporary directory is a tmpfs inside the sandbox, while the data
|
||||
/// directory lives in the home directory of the user.<br/><br/>
|
||||
/// The staging directory lives in the temporary folder of AI Studio below the data directory
|
||||
/// (TemporaryFiles), never below the temporary directory of the operating system. Installing means
|
||||
/// moving the staged plugin into the plugins directory, and a directory move cannot cross a file
|
||||
/// system boundary. Flatpak is the case where this always applies: its temporary directory is a
|
||||
/// tmpfs inside the sandbox, while the data directory lives in the home directory of the user.
|
||||
/// Whatever a crash leaves behind is gone with the next start of AI Studio.<br/><br/>
|
||||
/// It lives next to the plugins directory, not inside it: the plugin loader searches the plugins
|
||||
/// directory recursively, so a half-written plugin there would be loaded while it is still being
|
||||
/// staged.
|
||||
/// </remarks>
|
||||
/// <param name="prefix">The prefix of the staging directory name, naming the caller.</param>
|
||||
/// <param name="stagingDirectory">The created staging directory.</param>
|
||||
/// <param name="issue">A user-facing issue when the staging directory could not be created.</param>
|
||||
/// <returns>True when the staging directory exists, false otherwise.</returns>
|
||||
private bool TryCreateStagingDirectory(string prefix, out string stagingDirectory, out string issue)
|
||||
private bool TryCreateStagingDirectory(out string stagingDirectory, out string issue)
|
||||
{
|
||||
stagingDirectory = string.Empty;
|
||||
issue = string.Empty;
|
||||
|
||||
var dataDirectory = SettingsManager.DataDirectory;
|
||||
if (string.IsNullOrWhiteSpace(dataDirectory))
|
||||
if (string.IsNullOrWhiteSpace(SettingsManager.DataDirectory))
|
||||
{
|
||||
issue = TB("The AI Studio data directory is not initialized yet.");
|
||||
return false;
|
||||
}
|
||||
|
||||
var stagingRoot = Path.Join(dataDirectory, STAGING_DIRECTORY);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(stagingRoot);
|
||||
this.CleanUpExpiredStagingDirectories(stagingRoot);
|
||||
|
||||
stagingDirectory = Path.Join(stagingRoot, $"{prefix}.staging-{Guid.NewGuid():N}");
|
||||
Directory.CreateDirectory(stagingDirectory);
|
||||
stagingDirectory = TemporaryFiles.CreateDirectory();
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogError(e, "Failed to create the plugin staging directory below '{StagingRoot}'.", stagingRoot);
|
||||
stagingDirectory = string.Empty;
|
||||
this.logger.LogError(e, "Failed to create the plugin staging directory in the temporary folder of AI Studio.");
|
||||
issue = string.Format(TB("Unexpected error: {0}"), e.Message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes staging directories which an earlier installation left behind, e.g. after a crash.
|
||||
/// </summary>
|
||||
private void CleanUpExpiredStagingDirectories(string stagingRoot)
|
||||
{
|
||||
var expiry = DateTime.UtcNow.AddHours(-STAGING_RETENTION_HOURS);
|
||||
foreach (var leftOverDirectory in Directory.EnumerateDirectories(stagingRoot, "*", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (Directory.GetLastWriteTimeUtc(leftOverDirectory) < expiry)
|
||||
Directory.Delete(leftOverDirectory, true);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
this.logger.LogWarning(e, "Failed to delete the left-over plugin staging directory '{StagingDirectory}'.", leftOverDirectory);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Moves a directory and falls back to copying it when the move crosses a file system boundary.
|
||||
/// </summary>
|
||||
|
||||
@@ -42,7 +42,7 @@ public sealed partial class PluginInstallService
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
if (!this.TryCreateStagingDirectory(PLUGIN_IMPORT_DIRECTORY_PREFIX, out stagingDirectory, out var stagingIssue))
|
||||
if (!this.TryCreateStagingDirectory(out stagingDirectory, out var stagingIssue))
|
||||
return Error(stagingIssue);
|
||||
|
||||
await PluginArchive.ExtractAsync(archivePath, stagingDirectory, token);
|
||||
|
||||
@@ -24,12 +24,8 @@ public sealed partial class PluginInstallService
|
||||
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(PluginInstallService).Namespace, nameof(PluginInstallService));
|
||||
|
||||
private const string PLUGIN_FILE_NAME = "plugin.lua";
|
||||
private const string ASSISTANT_BUILDER_DIRECTORY_PREFIX = "assistant-builder";
|
||||
private const string PLUGIN_IMPORT_DIRECTORY_PREFIX = "plugin-import";
|
||||
private const string DELETE_BACKUP_DIRECTORY = ".plugin-delete-backups";
|
||||
private const string INSTALL_BACKUP_DIRECTORY = ".plugin-install-backups";
|
||||
private const string STAGING_DIRECTORY = ".plugin-staging";
|
||||
private const int STAGING_RETENTION_HOURS = 24;
|
||||
private const int DIRECTORY_PREFIX_MAX_LEN = 80;
|
||||
|
||||
private readonly ILogger<PluginInstallService> logger;
|
||||
|
||||
@@ -17,13 +17,6 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
|
||||
private const string PLUGIN_FILE_NAME = "plugin.lua";
|
||||
|
||||
/// <remarks>
|
||||
/// Keep in sync with SHARE_DIRECTORY_NAME in runtime/src/share_sheet.rs: the runtime only hands
|
||||
/// archives from a directory with this name to the native share sheet.
|
||||
/// </remarks>
|
||||
private const string TEMPORARY_ARCHIVE_DIRECTORY = "mindwork-ai-studio-plugin-shares";
|
||||
|
||||
private const int TEMPORARY_ARCHIVE_RETENTION_HOURS = 24;
|
||||
private const int FILE_NAME_PREFIX_MAX_LEN = 80;
|
||||
|
||||
/// <summary>
|
||||
@@ -37,8 +30,8 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
/// The archive contains the plugin root contents, so <c>plugin.lua</c> is located at the archive root.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// On Windows and macOS, the archive is created in a temporary directory and handed over to the
|
||||
/// native share sheet. Linux has no such share sheet, since the XDG desktop portals do not provide
|
||||
/// On Windows and macOS, the archive is created in the temporary folder of AI Studio and handed over
|
||||
/// to the native share sheet. Linux has no such share sheet, since the XDG desktop portals do not provide
|
||||
/// a share interface. Thus, the archive is exported to a location of the user's choice there. The
|
||||
/// same happens on Windows and macOS once the share sheet failed or did not respond, until AI
|
||||
/// Studio restarts.
|
||||
@@ -162,22 +155,25 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates the plugin archive in a temporary directory and opens the native share sheet for it.
|
||||
/// Creates the plugin archive in the temporary folder of AI Studio and opens the native share sheet for it.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The runtime hands only archives from the temporary folder of AI Studio to the share sheet, see
|
||||
/// TemporaryFiles. The archive gets a folder of its own there, so it can carry the name of the plugin,
|
||||
/// which the recipient sees, just like an exported archive.
|
||||
/// </remarks>
|
||||
/// <param name="plugin">The local plugin to archive and share.</param>
|
||||
/// <param name="pluginRoot">The validated plugin root directory.</param>
|
||||
/// <param name="token">Cancellation token for archive creation.</param>
|
||||
/// <returns>The share result, including the retained temporary archive path when successful.</returns>
|
||||
private async Task<PluginShareResult> ShareViaNativeSheetAsync(IAvailablePlugin plugin, string pluginRoot, CancellationToken token)
|
||||
{
|
||||
var archiveDirectory = Path.Join(Path.GetTempPath(), TEMPORARY_ARCHIVE_DIRECTORY);
|
||||
var archivePath = Path.Join(archiveDirectory, $"{CreateSafeFileNamePrefix(plugin.Name)}-{plugin.Id:N}-{Guid.NewGuid():N}{PluginArchive.PLUGIN_FILE_EXTENSION}");
|
||||
|
||||
string? archiveDirectory = null;
|
||||
try
|
||||
{
|
||||
token.ThrowIfCancellationRequested();
|
||||
Directory.CreateDirectory(archiveDirectory);
|
||||
this.CleanUpExpiredArchives(archiveDirectory);
|
||||
archiveDirectory = TemporaryFiles.CreateDirectory();
|
||||
var archivePath = Path.Join(archiveDirectory, $"{CreateSafeFileNamePrefix(plugin.Name)}{PluginArchive.PLUGIN_FILE_EXTENSION}");
|
||||
|
||||
await Task.Run(async () =>
|
||||
{
|
||||
@@ -194,7 +190,7 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
|
||||
//
|
||||
// A share sheet which did not respond may still appear later and ask for the archive.
|
||||
// We keep it for that case; the clean-up removes it once it expired:
|
||||
// We keep it for that case; AI Studio deletes it when it quits or starts again:
|
||||
//
|
||||
case ShareSheetOutcome.UNRESPONSIVE:
|
||||
return ShareSheetUnavailable(plugin, TA("The share dialog of your operating system did not respond."));
|
||||
@@ -202,7 +198,7 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
case ShareSheetOutcome.FAILED:
|
||||
case ShareSheetOutcome.UNKNOWN:
|
||||
default:
|
||||
this.TryDeleteArchive(archivePath);
|
||||
this.TryDeleteArchiveDirectory(archiveDirectory);
|
||||
return ShareSheetUnavailable(plugin, TB("The native share dialog could not be opened."));
|
||||
}
|
||||
|
||||
@@ -211,12 +207,12 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
this.TryDeleteArchive(archivePath);
|
||||
this.TryDeleteArchiveDirectory(archiveDirectory);
|
||||
throw;
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
this.TryDeleteArchive(archivePath);
|
||||
this.TryDeleteArchiveDirectory(archiveDirectory);
|
||||
logger.LogError(exception, "Failed to create a share archive for plugin '{PluginName}' ({PluginId}).", plugin.Name, plugin.Id);
|
||||
return ShareError(plugin, string.Format(TB("Unexpected error: {0}"), exception.Message));
|
||||
}
|
||||
@@ -259,23 +255,6 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
return true;
|
||||
}
|
||||
|
||||
private void CleanUpExpiredArchives(string archiveDirectory)
|
||||
{
|
||||
var expiry = DateTime.UtcNow.AddHours(-TEMPORARY_ARCHIVE_RETENTION_HOURS);
|
||||
foreach (var archivePath in Directory.EnumerateFiles(archiveDirectory, $"*{PluginArchive.PLUGIN_FILE_EXTENSION}", SearchOption.TopDirectoryOnly))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (File.GetLastWriteTimeUtc(archivePath) < expiry)
|
||||
File.Delete(archivePath);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "Failed to delete expired plugin archive '{ArchivePath}'.", archivePath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string CreateSafeFileNamePrefix(string pluginName)
|
||||
{
|
||||
var invalidCharacters = Path.GetInvalidFileNameChars().ToHashSet();
|
||||
@@ -300,6 +279,21 @@ public sealed class PluginShareService(NativeShareService nativeShareService, Ru
|
||||
return childPath.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private void TryDeleteArchiveDirectory(string? archiveDirectory)
|
||||
{
|
||||
if (archiveDirectory is null || !Directory.Exists(archiveDirectory))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
Directory.Delete(archiveDirectory, true);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "Failed to delete the temporary plugin archive in '{ArchiveDirectory}'. AI Studio deletes it when it starts again.", archiveDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
private void TryDeleteArchive(string archivePath)
|
||||
{
|
||||
if (!File.Exists(archivePath))
|
||||
|
||||
@@ -1,76 +0,0 @@
|
||||
using AIStudio.Settings;
|
||||
|
||||
namespace AIStudio.Tools.Services;
|
||||
|
||||
/// <summary>
|
||||
/// One-shot startup service that removes transcript staging left by crashes or forced shutdowns.
|
||||
/// </summary>
|
||||
public sealed class TranscriptStagingCleanupService(ILogger<TranscriptStagingCleanupService> logger) : BackgroundService
|
||||
{
|
||||
/// <summary>Waits for the data directory, performs one cleanup pass, and then exits.</summary>
|
||||
/// <param name="stoppingToken">Host shutdown token.</param>
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
while (string.IsNullOrWhiteSpace(SettingsManager.DataDirectory) && !stoppingToken.IsCancellationRequested)
|
||||
await Task.Delay(TimeSpan.FromSeconds(1), stoppingToken);
|
||||
|
||||
if (stoppingToken.IsCancellationRequested)
|
||||
return;
|
||||
|
||||
var stagingRoot = Path.Combine(SettingsManager.DataDirectory!, "media-staging");
|
||||
if (!Directory.Exists(stagingRoot))
|
||||
{
|
||||
logger.LogInformation("Media transcript staging does not exist; startup cleanup has nothing to remove.");
|
||||
return;
|
||||
}
|
||||
|
||||
var directories = Directory.EnumerateDirectories(stagingRoot).ToArray();
|
||||
var files = Directory.EnumerateFiles(stagingRoot).ToArray();
|
||||
logger.LogInformation("Media transcript startup cleanup found {DirectoryCount} directories and {FileCount} loose files.", directories.Length, files.Length);
|
||||
|
||||
if (directories.Length == 0 && files.Length == 0)
|
||||
{
|
||||
logger.LogInformation("Media transcript staging is empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
var deletedDirectories = 0;
|
||||
var deletedFiles = 0;
|
||||
var failures = 0;
|
||||
|
||||
foreach (var directory in directories)
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.Delete(directory, true);
|
||||
deletedDirectories++;
|
||||
logger.LogInformation("Removed orphaned media staging directory '{Directory}'.", directory);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failures++;
|
||||
logger.LogWarning(exception, "Could not remove orphaned media staging directory '{Directory}'.", directory);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var file in files)
|
||||
{
|
||||
try
|
||||
{
|
||||
File.Delete(file);
|
||||
deletedFiles++;
|
||||
logger.LogInformation("Removed orphaned media staging file '{File}'.", file);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
failures++;
|
||||
logger.LogWarning(exception, "Could not remove orphaned media staging file '{File}'.", file);
|
||||
}
|
||||
}
|
||||
|
||||
logger.LogInformation("Media transcript startup cleanup removed {DirectoryCount} directories and {FileCount} files with {FailureCount} failures.",
|
||||
deletedDirectories,
|
||||
deletedFiles,
|
||||
failures);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
namespace AIStudio.Tools;
|
||||
|
||||
/// <summary>
|
||||
/// The temporary folder of AI Studio below its data directory, for files which live only while AI Studio runs.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// AI Studio does not write into the temporary folder of the system. On many Linux systems, that folder lives in
|
||||
/// memory (tmpfs). In a Flatpak, it always does, limited to a tenth of the memory, and a recording or a document with
|
||||
/// videos takes hundreds of megabytes. Besides, all users of a Linux computer share /tmp, and each of them can read
|
||||
/// a file which .NET creates there, whereas the data directory lies in the home folder of the user.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// AI Studio empties the folder when it starts, before any service runs, and once more when it stops. A file therefore
|
||||
/// lives at most as long as AI Studio runs, and whatever a crash left behind is gone with the next start. Whoever
|
||||
/// creates a file or a folder here still deletes it once done, since AI Studio may run for weeks. A backup leaves the
|
||||
/// folder out, see DataBackupContents.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static class TemporaryFiles
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the folder in the data directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Keep in sync with TEMPORARY_DIRECTORY_NAME in runtime/src/share_sheet.rs: the runtime hands only plugin
|
||||
/// archives from this folder to the share sheet of the operating system.
|
||||
/// </remarks>
|
||||
public const string FOLDER_NAME = "tmp";
|
||||
|
||||
/// <summary>
|
||||
/// The folder below the data directory, see DataBackupContents.
|
||||
/// </summary>
|
||||
public const string DIRECTORY = $"{FOLDER_NAME}/";
|
||||
|
||||
/// <summary>
|
||||
/// The folders in which earlier versions of AI Studio kept their temporary files, as patterns of folders directly
|
||||
/// in the data directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// They are deleted on every start, which costs a look per pattern, so that no installation keeps them.
|
||||
/// </remarks>
|
||||
private static readonly string[] FOLDERS_OF_EARLIER_VERSIONS = ["mailAttachments", "pandoc-install-*", ".document-staging", ".plugin-staging", "media-staging"];
|
||||
|
||||
/// <summary>
|
||||
/// Finds the folders of earlier versions also when they are hidden: on Linux and macOS, .NET takes a name which
|
||||
/// begins with a dot for hidden.
|
||||
/// </summary>
|
||||
private static readonly EnumerationOptions ALL_FOLDERS = new() { AttributesToSkip = FileAttributes.None };
|
||||
|
||||
private static string? FOLDER_PATH;
|
||||
|
||||
/// <summary>
|
||||
/// Sets the folder below the given data directory and empties it, together with the folders of earlier versions.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// AI Studio calls this once, before any service runs, since emptying the folder deletes what a running operation
|
||||
/// wrote there. Only the first instance of AI Studio starts its server, so a second one never deletes the files of
|
||||
/// the first.
|
||||
/// </remarks>
|
||||
/// <param name="dataDirectory">The data directory of AI Studio, as the runtime reports it.</param>
|
||||
/// <param name="logger">Where to report a folder which cannot be deleted.</param>
|
||||
public static void Initialize(string dataDirectory, ILogger logger)
|
||||
{
|
||||
// Below a relative path, the folder would lie in the working directory, and emptying it would delete files there:
|
||||
if (!Path.IsPathFullyQualified(dataDirectory))
|
||||
{
|
||||
logger.LogError("The temporary folder of AI Studio is not available, because the data directory '{DataDirectory}' is not an absolute path.", dataDirectory);
|
||||
return;
|
||||
}
|
||||
|
||||
FOLDER_PATH = Path.Join(dataDirectory, FOLDER_NAME);
|
||||
Clear(logger);
|
||||
DeleteFoldersOfEarlierVersions(dataDirectory, logger);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes up the path of a new file in the folder.
|
||||
/// </summary>
|
||||
/// <param name="fileExtension">The extension of the file, including the leading dot.</param>
|
||||
/// <returns>The path, where no file exists yet.</returns>
|
||||
/// <exception cref="InvalidOperationException">AI Studio has not set the folder yet.</exception>
|
||||
public static string GetFilePath(string fileExtension) => Path.Join(GetDirectory(), $"{Guid.NewGuid():N}{fileExtension}");
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new, empty folder in the folder, e.g., for files which belong together.
|
||||
/// </summary>
|
||||
/// <returns>The path of the new folder.</returns>
|
||||
/// <exception cref="InvalidOperationException">AI Studio has not set the folder yet.</exception>
|
||||
public static string CreateDirectory()
|
||||
{
|
||||
var path = Path.Join(GetDirectory(), Guid.NewGuid().ToString("N"));
|
||||
Directory.CreateDirectory(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes everything in the folder. AI Studio does so when it starts and when it stops.
|
||||
/// </summary>
|
||||
/// <param name="logger">Where to report a folder which cannot be deleted.</param>
|
||||
public static void Clear(ILogger logger)
|
||||
{
|
||||
if (FOLDER_PATH is not null)
|
||||
Delete(FOLDER_PATH, logger);
|
||||
}
|
||||
|
||||
private static void DeleteFoldersOfEarlierVersions(string dataDirectory, ILogger logger)
|
||||
{
|
||||
if (!Directory.Exists(dataDirectory))
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
foreach (var pattern in FOLDERS_OF_EARLIER_VERSIONS)
|
||||
{
|
||||
foreach (var folder in Directory.EnumerateDirectories(dataDirectory, pattern, ALL_FOLDERS))
|
||||
Delete(folder, logger);
|
||||
}
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "The temporary folders of earlier versions of AI Studio in '{DataDirectory}' could not be looked through. The next start of AI Studio tries again.", dataDirectory);
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetDirectory()
|
||||
{
|
||||
var path = FOLDER_PATH ?? throw new InvalidOperationException("The temporary folder of AI Studio is not set yet.");
|
||||
Directory.CreateDirectory(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Deletes a folder with everything in it. A link is removed, but never followed: whatever it points to stays.
|
||||
/// </summary>
|
||||
/// <param name="path">The folder.</param>
|
||||
/// <param name="logger">Where to report a folder which cannot be deleted, e.g., since a file in it is open.</param>
|
||||
private static void Delete(string path, ILogger logger)
|
||||
{
|
||||
try
|
||||
{
|
||||
var folder = new DirectoryInfo(path);
|
||||
if (folder.LinkTarget is not null)
|
||||
folder.Delete();
|
||||
else if (folder.Exists)
|
||||
folder.Delete(recursive: true);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogWarning(exception, "The temporary folder '{Path}' could not be deleted. The next start of AI Studio tries again.", path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user