Improved reading and writing large Office files without copying them into memory (#1243)

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-11-28 23:03:30 +01:00
1 parent 918572c158
commit dbe609a9a7
37 files changed
+1161 -471

No files matched your search

@@ -1,13 +1,19 @@
using System.IO.Compression;
using AIStudio.Tests.Tools.OpenXml;
using AIStudio.Tools.PowerPoint;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Validation;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Tools.PowerPoint;
/// <summary>
/// Checks that a presentation file comes about without anything next to the file the user chose.
/// Checks that a presentation file comes about without anything next to the file the user chose, and without its
/// template or its pictures in memory.
/// </summary>
/// <remarks>
/// Inside the Flatpak, the save dialog grants access to exactly the chosen file. A temporary file next
@@ -27,6 +33,16 @@ public sealed class PresentationFileTests
private static readonly byte[] PREVIOUS_CONTENT = [1, 2, 3];
/// <summary>
/// A video of a template, large enough that the update mode of ZipArchive would show in the allocations.
/// </summary>
private const int VIDEO_SIZE = 32 * 1024 * 1024;
private static readonly SlotBounds PICTURE_BOUNDS = new(6_200_000, 1_825_625, 5_150_000, 3_500_000);
private static readonly byte[] TEMPLATE_PICTURE = [11, 12, 13];
private static readonly byte[] SAMPLE_PICTURE = [21, 22, 23];
private static readonly byte[] PHOTO = [31, 32, 33, 34];
private string templateFolder = string.Empty;
private string targetFolder = string.Empty;
@@ -47,7 +63,7 @@ public sealed class PresentationFileTests
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var temporaryFiles = TemporaryFiles();
var stagedFiles = StagingFolder.Files();
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, BasisOf(templatePath), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
@@ -57,7 +73,7 @@ public sealed class PresentationFileTests
Assert.That(result.IsWritten, Is.True);
Assert.That(Directory.GetFileSystemEntries(this.targetFolder), Is.EqualTo(new[] { targetPath }), "Nothing else came about next to the chosen file.");
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The chosen file holds the presentation instead of what it held before.");
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
}
}
@@ -67,7 +83,7 @@ public sealed class PresentationFileTests
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var temporaryFiles = TemporaryFiles();
var stagedFiles = StagingFolder.Files();
// Without a basis, nothing is known to fit, as after a change of the template:
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, new Dictionary<string, string>(), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
@@ -77,7 +93,7 @@ public sealed class PresentationFileTests
{
Assert.That(result.IsWritten, Is.False);
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT));
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
}
}
@@ -93,7 +109,91 @@ public sealed class PresentationFileTests
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was copied before it was written over.");
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was read completely before it was written over.");
}
}
[Test]
public async Task APictureWhichFailsLeavesNothingBehind()
{
var templatePath = await this.CreateTemplateAsync();
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
var deck = new SlideDeckSpec("Mars", [new SlideSpec("L2", false, "Why Mars", string.Empty, [], [], [1, 2], null)]);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var stagedFiles = StagingFolder.Files();
// The first picture is staged already when the second one fails:
await Assert.ThrowsAsync<IOException>(() => PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new FailingAtSecondPicture(), NullLogger.Instance, CancellationToken.None));
var targetContent = await File.ReadAllBytesAsync(targetPath);
using (Assert.EnterMultipleScope())
{
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT), "The chosen file stays as it was.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template and the staged picture are gone.");
}
}
[TestCase(false)]
[TestCase(true)]
public async Task TheMediaOfTheTemplateStreamThroughAsTheyAre(bool asTemplate)
{
// The deck keeps slide 1 with its picture and video, and leaves out slide 2, a sample with a picture and a video of its own:
var templatePath = Path.Join(this.templateFolder, asTemplate ? "template.potx" : "template.pptx");
var templateOptions = new TestTemplateOptions(AsTemplate: asTemplate, Slides:
[
new TestSlide(1, (TestPlaceholder.Title(), "Mars")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, TEMPLATE_PICTURE)] },
new TestSlide(1, (TestPlaceholder.Title(), "Sample")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, SAMPLE_PICTURE)] },
]);
using (var template = TestTemplate.Create(templateOptions,
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(new SlotBounds(1_524_000, 3_602_038, 9_144_000, 1_655_762))),
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS)),
new TestLayout("Picture", TestPlaceholder.Title(), TestPlaceholder.Picture(11, PICTURE_BOUNDS))))
await File.WriteAllBytesAsync(templatePath, template.ToArray());
var video = TestTemplate.VideoOf(VIDEO_SIZE);
TestTemplate.AddVideo(templatePath, 1, video);
TestTemplate.AddVideo(templatePath, 2, TestTemplate.VideoOf(1024 * 1024, 2), "/ppt/media/video2.mp4");
var deck = new SlideDeckSpec("Mars",
[
new SlideSpec(string.Empty, false, string.Empty, string.Empty, [], [], [], null, 1),
new SlideSpec("L3", false, "The rocket", string.Empty, [], [], [1], null),
]);
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
var stagedFiles = StagingFolder.Files();
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new OnePhoto(), NullLogger.Instance, CancellationToken.None);
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
List<string> templateErrors;
using (var template = PresentationDocument.Open(templatePath, false))
templateErrors = ValidationErrorsOf(template);
using var archive = ZipFile.OpenRead(targetPath);
var targetVideo = archive.GetEntry("ppt/media/video1.mp4");
var smallEntries = archive.Entries.Where(entry => entry.Length < 1024).Select(ContentOf).ToList();
using var document = PresentationDocument.Open(targetPath, false);
var slides = document.PresentationPart!.Presentation!.SlideIdList!.Elements<DocumentFormat.OpenXml.Presentation.SlideId>()
.Select(slideId => (SlidePart)document.PresentationPart.GetPartById(slideId.RelationshipId!.Value!))
.ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(result.IsWritten, Is.True);
Assert.That(targetVideo, Is.Not.Null, "The video of the kept slide comes along.");
Assert.That(targetVideo is null ? Array.Empty<byte>() : ContentOf(targetVideo), Is.EqualTo(video), "The video keeps its bytes.");
Assert.That(targetVideo?.CompressedLength, Is.EqualTo(targetVideo?.Length), "The video stays stored.");
Assert.That(archive.GetEntry("ppt/media/video2.mp4"), Is.Null, "The video of the sample slide stays out.");
Assert.That(smallEntries, Has.None.EqualTo(SAMPLE_PICTURE), "The picture of the sample slide stays out.");
Assert.That(slides.Select(slide => slide.ImageParts.Select(ContentOf).Single()), Is.EqualTo(new[] { TEMPLATE_PICTURE, PHOTO }), "The kept slide keeps its picture, and the new slide shows the photo.");
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 4), $"The template goes through streams, not through memory; {allocated / 1024 / 1024} MB were allocated.");
Assert.That(ValidationErrorsOf(document), Is.EquivalentTo(templateErrors), "The presentation is as valid as its template.");
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton, the photo, and the presentation leave nothing behind in the staging folder.");
}
}
@@ -108,19 +208,43 @@ public sealed class PresentationFileTests
return templatePath;
}
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath).DescribeBasisOf(DECK);
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(DECK);
/// <summary>
/// The files in the folder where the presentations come about; others may have left some there.
/// </summary>
private static string[] TemporaryFiles()
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
.Validate(document)
.Select(error => $"{error.Path?.XPath}: {error.Description}")
.ToList();
private static byte[] ContentOf(ZipArchiveEntry entry)
{
var folder = Path.Join(Path.GetTempPath(), "mindwork-ai-studio-presentations");
return Directory.Exists(folder) ? Directory.GetFiles(folder) : [];
using var stream = entry.Open();
using var content = new MemoryStream();
stream.CopyTo(content);
return content.ToArray();
}
private static byte[] ContentOf(ImagePart part)
{
using var stream = part.GetStream(FileMode.Open, FileAccess.Read);
using var content = new MemoryStream();
stream.CopyTo(content);
return content.ToArray();
}
private sealed class NoPictures : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult<SlidePicture?>(null);
}
private sealed class OnePhoto : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult(number == 1 ? new SlidePicture(PHOTO, "image/jpeg", 400, 300) : null);
}
private sealed class FailingAtSecondPicture : IPictureSource
{
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => number < 2
? Task.FromResult<SlidePicture?>(new SlidePicture([1, 2, 3], "image/png", 400, 100))
: throw new IOException("The picture cannot be read.");
}
}