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

@@ -63,7 +63,7 @@ public sealed class HtmlSegmentFormatTests
[Test]
public async Task TheWordsGoToTheModelAndTheMarkupBecomesTags()
{
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
using (Assert.EnterMultipleScope())
{
@@ -192,7 +192,7 @@ public sealed class HtmlSegmentFormatTests
var page =$"<p>Intro text.</p>{Nested("div", 300, "Deep block")}<p>Before {Nested("span", 300, "deep words")} after.</p><p>Outro text.</p>";
File.WriteAllText(this.source, page, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
var written = await File.ReadAllTextAsync(this.target);
@@ -209,7 +209,7 @@ public sealed class HtmlSegmentFormatTests
// Thousands of elements without their end tags, as a broken generator may write them:
File.WriteAllText(this.source, "<p>" + string.Concat(Enumerable.Repeat("<span>", 20_000)) + "Words</p>", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
Assert.That(async () => await this.format.ReadAsync(this.source, CancellationToken.None), Throws.Exception);
Assert.That(async () => await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None), Throws.Exception);
}
[Test]
@@ -218,7 +218,7 @@ public sealed class HtmlSegmentFormatTests
// A card, as many pages show them: a link around a heading and a paragraph:
File.WriteAllText(this.source, "<a href=\"/mars\"><div><h3>Mars</h3><p>The red planet.</p></div></a>", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
Assert.That(keys, Is.EqualTo(new[] { "Mars", "The red planet." }));
}
@@ -248,7 +248,7 @@ public sealed class HtmlSegmentFormatTests
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
{
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
return new SegmentResults(segments
.Where(segment => segment.HasWords)
.DistinctBy(segment => segment.Key)
@@ -362,11 +362,11 @@ public sealed class LatexSegmentFormatTests
private void WriteSource(string text) => File.WriteAllText(this.source, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
{
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
return new SegmentResults(segments
.Where(segment => segment.HasWords)
.DistinctBy(segment => segment.Key)
@@ -199,7 +199,7 @@ public sealed class MarkdownSegmentFormatTests
{
var source = await this.WriteSourceAsync("Fish &amp; Chips cost 5 \\* 3 \\| 2 &copy; us.\n");
var keys = (await this.format.ReadAsync(source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
Assert.That(keys, Is.EqualTo(new[] { "Fish & Chips cost 5 * 3 | 2 © us." }));
}
@@ -277,7 +277,7 @@ public sealed class MarkdownSegmentFormatTests
{
var source = await this.WriteSourceAsync("Press &lt;1&gt; to continue.\n\nPress <1 /> as well.\n\nOther words.\n");
var keys = (await this.format.ReadAsync(source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
Assert.That(keys, Is.EqualTo(new[] { "Other words." }), "A model could not tell such words apart from tags, even when they come from two entities and the words between them.");
}
@@ -291,7 +291,7 @@ public sealed class MarkdownSegmentFormatTests
private async Task<SegmentResults> ResultsAsync(string path, Func<string, string> transform)
{
var segments = await this.format.ReadAsync(path, CancellationToken.None);
var segments = await this.format.ReadAsync(path, NullLogger.Instance, CancellationToken.None);
return new SegmentResults(segments
.Where(segment => segment.HasWords)
.DistinctBy(segment => segment.Key)
@@ -1,10 +1,9 @@
using System.IO.Compression;
using System.IO.Packaging;
using AIStudio.Tests.Tools.OpenXml;
using AIStudio.Tests.Tools.PowerPoint;
using AIStudio.Tools.DocumentSegments;
using AIStudio.Tools.DocumentSegments.PowerPoint;
using AIStudio.Tools.OpenXml;
using AIStudio.Tools.PowerPoint;
using DocumentFormat.OpenXml;
@@ -90,7 +89,7 @@ public sealed class PowerPointSegmentFormatTests
[Test]
public async Task TheTextsOfSlidesAndNotesBecomeSegmentsWithTags()
{
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
using (Assert.EnterMultipleScope())
{
@@ -248,7 +247,7 @@ public sealed class PowerPointSegmentFormatTests
this.AddVideo();
var results = await this.ResultsAsync(key => key.ToUpperInvariant());
var stagedBefore = StagedFiles();
var stagedBefore = StagingFolder.Files();
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
var result = await this.format.WriteAsync(this.source, this.target, results, "de-DE", NullLogger.Instance, CancellationToken.None);
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
@@ -267,7 +266,7 @@ public sealed class PowerPointSegmentFormatTests
Assert.That(targetVideo.CompressedLength, Is.EqualTo(targetVideo.Length), "The video stays uncompressed.");
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 2), "The video goes through the stream, not through memory.");
Assert.That(SlideOf(document).Descendants<A.Paragraph>().Select(paragraph => paragraph.InnerText), Has.Member("MISSION TO MARS"), "The new words reach the new document.");
Assert.That(StagedFiles().Except(stagedBefore), Is.Empty, "The new document leaves nothing behind in the staging folder.");
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The new document leaves nothing behind in the staging folder.");
}
}
@@ -283,6 +282,21 @@ public sealed class PowerPointSegmentFormatTests
Assert.That(this.format.TextSizeOf(this.source), Is.EqualTo(xmlSize).And.LessThan(VIDEO_SIZE), "Only the XML comes into memory, unpacked, never the pictures and videos.");
}
[Test]
public async Task ReadingThroughTheSkeletonLeavesNothingBehind()
{
this.AddVideo();
var stagedBefore = StagingFolder.Files();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
using (Assert.EnterMultipleScope())
{
Assert.That(keys, Does.Contain("Mission to Mars"), "The skeleton holds every text of the presentation.");
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The skeleton is gone once the presentation is read.");
}
}
[Test]
public async Task AChangedSourceWritesNothing()
{
@@ -297,7 +311,7 @@ public sealed class PowerPointSegmentFormatTests
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
{
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
return new SegmentResults(segments
.Where(segment => segment.HasWords)
.DistinctBy(segment => segment.Key)
@@ -309,19 +323,7 @@ public sealed class PowerPointSegmentFormatTests
/// <summary>
/// Adds a video as PowerPoint stores it: uncompressed, behind the slides, which the update mode of ZipArchive would load into memory.
/// </summary>
private void AddVideo()
{
var video = new byte[VIDEO_SIZE];
new Random(1179).NextBytes(video);
using var package = Package.Open(this.source, FileMode.Open, FileAccess.ReadWrite);
var slidePart = package.GetParts().Single(part => part.Uri.OriginalString.StartsWith("/ppt/slides/slide", StringComparison.Ordinal));
var videoPart = package.CreatePart(new Uri("/ppt/media/video1.mp4", UriKind.Relative), "video/mp4", CompressionOption.NotCompressed);
using (var stream = videoPart.GetStream())
stream.Write(video);
slidePart.CreateRelationship(videoPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
}
private void AddVideo() => TestTemplate.AddVideo(this.source, 1, TestTemplate.VideoOf(VIDEO_SIZE));
private static byte[] ContentOf(ZipArchiveEntry entry)
{
@@ -331,12 +333,6 @@ public sealed class PowerPointSegmentFormatTests
return content.ToArray();
}
private static HashSet<string> StagedFiles()
{
var directory = Path.Join(Path.GetTempPath(), StagedDocument.DIRECTORY);
return Directory.Exists(directory) ? Directory.EnumerateFiles(directory).ToHashSet() : [];
}
private static IEnumerable<OpenXmlElement> RootsOf(PresentationDocument document)
{
var slidePart = document.PresentationPart!.SlideParts.Single();
@@ -4,6 +4,8 @@ using AIStudio.Tools.DocumentSegments;
using AIStudio.Tools.DocumentSegments.Html;
using AIStudio.Tools.DocumentSegments.Latex;
using Microsoft.Extensions.Logging.Abstractions;
namespace AIStudio.Tests.Tools.DocumentSegments;
/// <summary>
@@ -69,7 +71,7 @@ public sealed class TextDocumentFileTests
{
var source = await this.WriteAsync("page.html", Encoding.ASCII.GetBytes("<html><head><meta charset=\"iso-8859-1\"></head><body><p>M&uuml;ller</p></body></html>"));
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None));
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
Assert.That(exception!.DeclaredEncoding, Is.EqualTo("iso-8859-1"), "An ASCII page which says Latin-1 would show new words in UTF-8 garbled.");
}
@@ -80,7 +82,7 @@ public sealed class TextDocumentFileTests
var page = "<html><head><meta charset=\"iso-8859-1\"></head><body><p>Grüße</p></body></html>";
var source = await this.WriteAsync("page.html", new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(page)).ToArray());
var segments = await new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None);
var segments = await new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None);
Assert.That(segments.Select(segment => segment.Key), Does.Contain("Grüße"), "Browsers follow the byte order mark, too.");
}
@@ -90,7 +92,7 @@ public sealed class TextDocumentFileTests
{
var source = await this.WriteAsync("paper.tex", Encoding.ASCII.GetBytes("\\documentclass{article}\n\\usepackage[latin1]{inputenc}\n\\begin{document}\nHello.\n\\end{document}"));
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new LatexSegmentFormat().ReadAsync(source, CancellationToken.None));
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new LatexSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
Assert.That(exception!.DeclaredEncoding, Is.EqualTo("latin1"));
}
@@ -146,7 +148,7 @@ public sealed class TextDocumentFileTests
await using (var stream = new FileStream(source, FileMode.CreateNew))
stream.SetLength(new HtmlSegmentFormat().MaxTextSize + 1);
await Assert.ThrowsAsync<DocumentTooLargeException>(() => new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None));
await Assert.ThrowsAsync<DocumentTooLargeException>(() => new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
}
private async Task<string> WriteAsync(string name, byte[] bytes)
@@ -383,7 +383,7 @@ public sealed class WordInlineFormattingTests
private void CreateSentence() => Create(this.source, Paragraph(Run("This is "), Bold("very"), Run(" "), Italic("important"), Run(" and "), Link("linked"), Run(" text.")));
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
private Task<SegmentWriteResult> WriteAsync(string key, string newText)
{
@@ -44,7 +44,7 @@ public sealed class WordSegmentFormatTests
[Test]
public async Task TheParagraphsBecomeSegmentsWithTags()
{
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
using (Assert.EnterMultipleScope())
{
@@ -201,7 +201,7 @@ public sealed class WordSegmentFormatTests
using (var sourceToExtend = WordprocessingDocument.Open(this.source, true))
BodyOf(sourceToExtend).AppendChild(bound);
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
@@ -224,7 +224,7 @@ public sealed class WordSegmentFormatTests
new W.DeletedRun(new W.Run(new W.DeletedText("gone"))) { Id = "1", Author = "Tester" },
new W.InsertedRun(Run("new")) { Id = "2", Author = "Tester" }));
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
@@ -250,7 +250,7 @@ public sealed class WordSegmentFormatTests
Run("Introduction")),
Paragraph(Run("Methods"), new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End })));
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
@@ -324,7 +324,7 @@ public sealed class WordSegmentFormatTests
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
{
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
return new SegmentResults(segments
.Where(segment => segment.HasWords)
.DistinctBy(segment => segment.Key)