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,3 +1,4 @@
using System.Collections.ObjectModel;
using System.IO.Compression;
using AIStudio.Tools.OpenXml;
@@ -13,10 +14,12 @@ namespace AIStudio.Tools.DocumentSegments;
/// </summary>
/// <remarks>
/// The source is read again, for reading only, and nothing is written when the results miss one of its paragraphs.
/// The writer changes the DOM of the paragraphs, and PackageRewrite writes a new document with the parts whose
/// paragraphs got new words, streaming every other entry through: the pictures and videos of a document never come
/// into memory. The new document comes about in a StagedDocument and goes into the file the user chose once it is
/// complete, see TargetFile. A paragraph whose text stays as it was keeps everything, its runs included.
/// Reading and writing both go through a PackageSkeleton, which holds only the XML of the source: the writer changes the
/// DOM of the paragraphs in the skeleton, and the skeleton writes a new document with the parts whose paragraphs got new
/// words, streaming the pictures and videos through from the source. They never come into memory, nor into the
/// temporary folder, where the SDK copies whatever it opens for reading. The new document comes about in a
/// StagedDocument and goes into the file the user chose once it is complete, see TargetFile. A paragraph whose text
/// stays as it was keeps everything, its runs included.
/// </remarks>
/// <typeparam name="TDocument">The kind of Office document, e.g., WordprocessingDocument.</typeparam>
/// <typeparam name="TParagraph">A paragraph as the reader of the format returns it, with all its writer needs.</typeparam>
@@ -45,23 +48,23 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
/// <inheritdoc />
/// <remarks>
/// The entries of XML and of relationships count with their unpacked size, which the directory of the archive
/// holds, so nothing is unpacked; pictures, videos, and other binary entries never come into memory.
/// The entries of XML and of relationships, which a PackageSkeleton keeps, count with their unpacked size, which the
/// directory of the archive holds, so nothing is unpacked; pictures, videos, and other binary entries never come into
/// memory.
/// </remarks>
public long TextSizeOf(string path)
{
using var file = TemplateFile.OpenRead(path);
using var archive = new ZipArchive(file, ZipArchiveMode.Read);
return archive.Entries
.Where(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))
.Sum(entry => entry.Length);
return archive.Entries.Where(PackageSkeleton.HoldsXml).Sum(entry => entry.Length);
}
/// <inheritdoc />
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
{
this.RefuseTooLargeText(path);
using var file = TemplateFile.OpenRead(path);
using var skeleton = PackageSkeleton.Create(path, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
return this.ReadParagraphs(document).Select(this.SegmentOf).ToList();
}, token);
@@ -70,7 +73,7 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
public async Task<SegmentWriteResult> WriteAsync(string sourcePath, string targetPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
using var stagedDocument = StagedDocument.Create(this.FileExtension, logger);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, token), token);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, logger, token), token);
if (result.Outcome is SegmentWriteOutcome.WRITTEN)
await stagedDocument.WriteIntoAsync(targetPath, token);
@@ -80,7 +83,7 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
#endregion
/// <summary>
/// The extension of the documents, with its dot, e.g., ".docx", for the new document in the StagedDocument.
/// The extension of the documents, with its dot, e.g., ".docx", for the skeleton and the new document in the staging folder.
/// </summary>
protected abstract string FileExtension { get; }
@@ -122,13 +125,14 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
/// Writes the new words into the DOM of the source read again, and the new document into the given file.
/// </summary>
/// <remarks>
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which
/// PackageRewrite does instead.
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which the
/// skeleton does instead.
/// </remarks>
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, CancellationToken token)
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
this.RefuseTooLargeText(sourcePath);
using var file = TemplateFile.OpenRead(sourcePath);
using var skeleton = PackageSkeleton.Create(sourcePath, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
var paragraphs = this.ReadParagraphs(document);
if (paragraphs.Any(paragraph => !results.Covers(this.SegmentOf(paragraph))))
@@ -151,8 +155,10 @@ internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentS
simplifiedCount++;
}
PackageRewrite.Write(sourcePath, changedParts, documentPath, token);
return new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount);
// False when the source changed since its skeleton was written, e.g., because Word saved it meanwhile:
return skeleton.TryWriteDocument(changedParts, ReadOnlyDictionary<string, string>.Empty, documentPath, token)
? new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount)
: SegmentWriteResult.SOURCE_CHANGED;
}
/// <summary>