diff --git a/CHANGELOG.md b/CHANGELOG.md index 56d310e..c49541a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -20,7 +20,14 @@ against an empty feed. ## [Unreleased] -Nothing yet. +### Added + +- **One call reports the whole picture.** `IPdfDiagnoser.DiagnoseAsync` returns a `PdfDiagnosticsReport` — + the document, its fonts, its signatures, an optional PDF/A pre-flight and the merged, de-duplicated + warnings — assembled from the use cases the library already exposes, so it cannot disagree with them. + The report is read-only and never returns stream contents; a document that stays closed is reported + with `IsReadable`/`RequiresPassword` instead of throwing. `tools/SharpCorePDF.Diagnostics` prints it as + text or JSON, with `--profile` for the archival pre-flight and `--json` for the whole report. ## [1.7.0] - 2026-11-14 diff --git a/README.md b/README.md index ddbaeaf..a453aad 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,12 @@ await merger.MergeToFileAsync(plan, @"C:\reports\combined.pdf"); select it. A standard font that relies on the one the reader already has is reported as carrying no program rather than as a defect, and a resource that does not resolve is a `FontUnreadable` warning beside the fonts that were read. Chapter 26 has the whole answer. +* **One call can describe the whole file.** `IPdfDiagnoser.DiagnoseAsync` returns a + `PdfDiagnosticsReport` — the document, its fonts, its signatures, an optional PDF/A pre-flight and the + merged, de-duplicated warnings — assembled from the same use cases the rest of the library uses, so it + cannot disagree with them. The report is read-only and never returns stream contents; a document that + stays closed is reported with `IsReadable`/`RequiresPassword` instead of throwing. The + `tools/SharpCorePDF.Diagnostics` console prints it as text or JSON. * **A cover page can be written from nothing and merged in front.** `PdfDocumentBuilder` adds pages of a chosen size, draws lines of text with one of the twelve standard fonts or a TrueType program you supply, and places PNG, JPEG, BMP and GIF images at fixed positions — a top-left origin, `y` @@ -345,8 +351,8 @@ nuget.org. | Package | Contents | | --- | --- | | [`SharpCorePDF`](https://www.nuget.org/packages/SharpCorePDF) | The one to install. Carries no assembly of its own: its only content is a dependency on the four below, so `dotnet add package SharpCorePDF` is the whole install. | -| [`SharpCorePDF.Domain`](https://www.nuget.org/packages/SharpCorePDF.Domain) | The `MergePlan` aggregate, the `PdfSource` entity, value objects (`PageSelection`, `PageRange`, `PdfMetadata`, `PdfVersion`, `PdfPageSize`, `PageRotation`, `PdfColor`, `StandardFont`, the policies), the read models (document and page info, `PdfReadResult`, image, mask, annotation, destination, form field, widget, bookmark, embedded file, text block, word, glyph, page detail and XMP) and the ports (`IPdfMerger`, `IPdfInspector`, `IPdfContentReader`, `IPdfContentSource`). No I/O, no third-party code. | -| [`SharpCorePDF.Application`](https://www.nuget.org/packages/SharpCorePDF.Application) | The use cases: `PdfMergerService` (validate, open, inspect, resolve selections, hand over to the engine, release every stream), `PdfInspectorService` and `PdfContentReaderService` (resolve the source, open it once, call the engine's page-content port), plus the extension methods callers use (`PdfMergerExtensions`, `PdfContentReaderExtensions`). | +| [`SharpCorePDF.Domain`](https://www.nuget.org/packages/SharpCorePDF.Domain) | The `MergePlan` aggregate, the `PdfSource` entity, value objects (`PageSelection`, `PageRange`, `PdfMetadata`, `PdfVersion`, `PdfPageSize`, `PageRotation`, `PdfColor`, `StandardFont`, the policies), the read models (document and page info, `PdfReadResult`, image, mask, annotation, destination, form field, widget, bookmark, embedded file, text block, word, glyph, page detail and XMP) and the ports (`IPdfMerger`, `IPdfInspector`, `IPdfContentReader`, `IPdfDiagnoser`, `IPdfContentSource`). No I/O, no third-party code. | +| [`SharpCorePDF.Application`](https://www.nuget.org/packages/SharpCorePDF.Application) | The use cases: `PdfMergerService` (validate, open, inspect, resolve selections, hand over to the engine, release every stream), `PdfInspectorService`, `PdfContentReaderService` and `PdfDiagnoserService` (resolve the source, open it once, call the engine's page-content port), plus the extension methods callers use (`PdfMergerExtensions`, `PdfContentReaderExtensions`). | | [`SharpCorePDF.Infrastructure`](https://www.nuget.org/packages/SharpCorePDF.Infrastructure) | The engine: the object model, the lexer, the object parser, the filter decoders, cross-reference tables, cross-reference streams, object streams, the page tree walk, the object copier, `PdfMergeEngine`, `PdfDocumentReader`, `PdfPageContentReader` (one partial file per capability, with `PdfTextCollector` for the glyphs), the content scanner, the writer, the content sources, and the authoring path (`PdfDocumentBuilder`, `PdfPageCanvas`, `PdfTypeface`, with the TrueType subset writer and the PNG reader). | | [`SharpCorePDF.DependencyInjection`](https://www.nuget.org/packages/SharpCorePDF.DependencyInjection) | `AddSharpCorePDF()` registration. | diff --git a/SharpCorePDF.slnx b/SharpCorePDF.slnx index 06663e5..1ca9a39 100644 --- a/SharpCorePDF.slnx +++ b/SharpCorePDF.slnx @@ -31,6 +31,7 @@ + diff --git a/docs/README.md b/docs/README.md index 766b989..269f096 100644 --- a/docs/README.md +++ b/docs/README.md @@ -6,7 +6,7 @@ long-form reference for the API. ## The manual -- **[Read or download the manual as a PDF](SharpCorePDF-Manual-1.7.0.pdf)** — 124 pages, A4, with a +- **[Read or download the manual as a PDF](SharpCorePDF-Manual-1.7.0.pdf)** — 125 pages, A4, with a linked contents page and PDF bookmarks. - **Read the chapters as Markdown** in [`manual/src`](manual/src). Each file is one chapter, and the file-name order is the chapter order. This edition describes `1.7.0`. Chapters 16 to 19 were written @@ -31,7 +31,7 @@ long-form reference for the API. | [5. Page Selection](manual/src/05-page-selection.md) | The one-based selection notation, building selections in code, and preflighting a range. | | [6. Output Options](manual/src/06-output-options.md) | Target version, primary source, metadata policies and overrides, outlines, page labels and reproducible output. | | [7. Encryption and Permissions](manual/src/07-encryption-permissions.md) | Algorithms, passwords, permission bits, encrypted sources, and what encryption does to reproducibility. | -| [8. Inspection](manual/src/08-inspection.md) | The document model, what inspection reports, the content reader (images, text, annotations, form, bookmarks, attachments, XMP and the inline budget), encrypted and damaged documents, and preflight. | +| [8. Inspection](manual/src/08-inspection.md) | The document model, what inspection reports, the content reader (images, text, annotations, form, bookmarks, attachments, XMP and the inline budget), encrypted and damaged documents, preflight and the one-call diagnostics report. | | [9. Errors, Exceptions and Warnings](manual/src/09-error-handling.md) | The exception family, what throws when, writing files safely, and warnings versus errors. | | [10. Dependency Injection](manual/src/10-dependency-injection.md) | `AddSharpCorePDF`, engine options, configuration binding, logging and testing with the container. | | [11. Architecture](manual/src/11-architecture.md) | The layers, the life of a merge, immutability, the memory model, extension points and concurrency. | diff --git a/docs/SharpCorePDF-Manual-1.7.0.pdf b/docs/SharpCorePDF-Manual-1.7.0.pdf index db69011..48d0553 100644 Binary files a/docs/SharpCorePDF-Manual-1.7.0.pdf and b/docs/SharpCorePDF-Manual-1.7.0.pdf differ diff --git a/docs/manual/src/08-inspection.md b/docs/manual/src/08-inspection.md index d273d4f..be46306 100644 --- a/docs/manual/src/08-inspection.md +++ b/docs/manual/src/08-inspection.md @@ -408,3 +408,45 @@ gives you a place to interject a message, a prompt or a policy decision. It does safer in the sense of catching every error: a file can change between inspection and merge, and the merger validates again. The gain is a better conversation with the user, not a substitute for handling `PdfException` (Chapter 9). + +## One-call diagnostics + +When the question is not one fact but the whole picture — what is this file, which fonts does it need, +is it signed, would it archive — `IPdfDiagnoser` answers it in one call instead of four: + +```csharp +var report = await diagnoser.DiagnoseAsync( + new PdfFileSource("statement.pdf"), + password: null, + archivalProfile: PdfAProfile.PdfA2B); + +Console.WriteLine(report.Document.PageCount); +Console.WriteLine(report.Fonts.Count); +Console.WriteLine(report.Signatures.Count); +Console.WriteLine(report.Archival?.IsWritten); + +foreach (var warning in report.Warnings) +{ + logger.LogWarning("{Kind}: {Message}", warning.Kind, warning.Message); +} +``` + +The report is assembled from the same use cases the rest of this chapter describes — inspection, the +font inspector (Chapter 26), the signature validator (Chapter 23) and the archival writer's pre-flight +(Chapter 24) — so it cannot disagree with them. It is read-only and redaction-explicit: it names sources +and describes structure, and it never returns stream contents, which is what makes it safe to log or +attach to a support ticket. + +`Archival` is `null` unless a profile is named; when it is present, `IsWritten` says whether the writer +would write the document and `UnsatisfiedRequirements` names every reason it would not. A document that +is encrypted and stays closed is reported, not thrown: `Document.IsReadable` and +`Document.RequiresPassword` answer what stands in the way, and the other reads are skipped. `Warnings` +is the merged list, de-duplicated by kind and message, and `HasFindings` is the one-line answer. + +The `tools/SharpCorePDF.Diagnostics` console prints the same report as text or JSON, which is what makes +it useful in a support conversation: + +```powershell +dotnet run --project .\tools\SharpCorePDF.Diagnostics -- statement.pdf --profile 2b +dotnet run --project .\tools\SharpCorePDF.Diagnostics -- statement.pdf --json +``` diff --git a/docs/mutation-testing.md b/docs/mutation-testing.md index f6d9613..f08ec99 100644 --- a/docs/mutation-testing.md +++ b/docs/mutation-testing.md @@ -751,4 +751,33 @@ What survived, read one by one: promise an engine that the stream is at its start. A comment beside the branch now says exactly that, so the survivor is explained in the code rather than only in this record. +## 1.7.0 — the diagnostics service (2026-11-14) + +Scoped run over `Services/PdfDiagnoserService.cs` after the one-call report was added: + +| File | Score | Killed | Survived | No coverage | Compile errors | Mutants | +| --- | --- | --- | --- | --- | --- | --- | +| `Services/PdfDiagnoserService.cs` | 42.86% | 6 | 8 | 0 | 10 | 24 | + +The first run scored 21.43% and named two real gaps, both now closed: no test passed an undefined +`PdfAProfile`, and no test asserted a warning the font read makes but inspection does not +(`FontDescriptorMissing`). `Refuses_an_undefined_profile` and +`Reports_a_font_warning_the_inspection_did_not_make` close them, and `Reads_a_closed_document_once` +counts the source's opens so the early return for a document that stays closed is a behaviour rather +than an optimisation. + +What survived, read one by one: + +- **The four `ConfigureAwait(false)` arguments** (mutated to `true`): equivalent, for the same reason the + merge and font records state. +- **The `ArgumentOutOfRangeException` message string**: no test asserts a refusal's wording, which is not + a contract. +- **`ArgumentNullException.ThrowIfNull(source)`**: redundant with the guard in each of the four use cases + the diagnoser calls; removing it changes which layer throws, not the exception the caller sees. +- **The two warning-merge statements** (`Add(document.Warnings)` and the archival block): the damaged + fixture reports `CrossReferenceRebuilt` through the font read as well, and the authored archival page + produces no warning of its own, so the current fixtures cannot tell the merge from the omission. A + document with an inspection-only warning and an archival removal is the fixture that would close them, + and it is the next thing to add if this service's suite is extended. + diff --git a/specs/005-roadmap-intake/plan.md b/specs/005-roadmap-intake/plan.md index c1de623..d26301a 100644 --- a/specs/005-roadmap-intake/plan.md +++ b/specs/005-roadmap-intake/plan.md @@ -15,8 +15,10 @@ mutation record. P3 measured the 100 MB read path (`--large` in `tools/SharpCore `docs/measurements.md` §10), wrote [`docs/adr/0004-buffer-model.md`](../../docs/adr/0004-buffer-model.md) — which **rejects `System.IO.Pipelines` and the `ReadOnlySequence` seam for 1.x** — and implemented the option it recommended: a merge and an edit now read each source once, measured at **2.04× → 1.04×** input on -a 100 MB document with identical output. `P4` (one-call diagnostics) is still waiting for the remainder of the -roadmap text, and `P5` (PDF/A beyond the current claim) for a decision. +a 100 MB document with identical output. `P4` (one-call diagnostics) is implemented in `[Unreleased]` +(2026-11-14): `IPdfDiagnoser`, `PdfDiagnoserService` and the `tools/SharpCorePDF.Diagnostics` console; the +remainder of the roadmap text would only add fields to the report. `P5` (PDF/A beyond the current claim) is +still waiting for a decision. **Baseline**: this was written against the **working tree**, not the last commit. That tree carries the pending `[Unreleased]` change (configuration binding without reflection, the AOT smoke app) and three new diff --git a/src/SharpCorePDF.Application/PublicAPI.Unshipped.txt b/src/SharpCorePDF.Application/PublicAPI.Unshipped.txt index 7dc5c58..e7d9add 100644 --- a/src/SharpCorePDF.Application/PublicAPI.Unshipped.txt +++ b/src/SharpCorePDF.Application/PublicAPI.Unshipped.txt @@ -1 +1,4 @@ #nullable enable +SharpCorePDF.Application.Services.PdfDiagnoserService +SharpCorePDF.Application.Services.PdfDiagnoserService.DiagnoseAsync(SharpCorePDF.Domain.Ports.IPdfContentSource! source, string? password = null, SharpCorePDF.Domain.ValueObjects.PdfAProfile? archivalProfile = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +SharpCorePDF.Application.Services.PdfDiagnoserService.PdfDiagnoserService(SharpCorePDF.Domain.Ports.IPdfInspector! inspector, SharpCorePDF.Domain.Ports.IPdfFontInspector! fonts, SharpCorePDF.Domain.Ports.IPdfSignatureValidator! signatures, SharpCorePDF.Domain.Ports.IPdfAWriter! archival) -> void diff --git a/src/SharpCorePDF.Application/Services/PdfDiagnoserService.cs b/src/SharpCorePDF.Application/Services/PdfDiagnoserService.cs new file mode 100644 index 0000000..5ba361a --- /dev/null +++ b/src/SharpCorePDF.Application/Services/PdfDiagnoserService.cs @@ -0,0 +1,124 @@ +using SharpCorePDF.Domain.Ports; +using SharpCorePDF.Domain.ReadModels; +using SharpCorePDF.Domain.ValueObjects; + +namespace SharpCorePDF.Application.Services; + +/// +/// The use case behind : it asks each existing use case in turn, merges their +/// warnings and returns one report. +/// +/// +/// +/// The report is composed rather than computed: inspection answers the structure, the font inspector the +/// fonts, the signature validator the signatures, and the archival writer — when a profile is named — the +/// requirements the writer would refuse. Because each of those is the one the rest of the library uses, +/// the report cannot drift from the behaviour it describes. +/// +/// +/// A document that stays closed is reported with and +/// instead of an exception; the other reads are skipped, +/// because they would fail on the same document. The class is stateless and thread safe. +/// +/// +public sealed class PdfDiagnoserService : IPdfDiagnoser +{ + private readonly IPdfInspector inspector; + private readonly IPdfFontInspector fonts; + private readonly IPdfSignatureValidator signatures; + private readonly IPdfAWriter archival; + + /// Initializes a new instance of the class. + /// The use case that describes the document. + /// The use case that reads the fonts. + /// The use case that checks the signatures. + /// The use case whose pre-flight answers the archival question. + /// An argument is . + public PdfDiagnoserService( + IPdfInspector inspector, + IPdfFontInspector fonts, + IPdfSignatureValidator signatures, + IPdfAWriter archival) + { + this.inspector = inspector ?? throw new ArgumentNullException(nameof(inspector)); + this.fonts = fonts ?? throw new ArgumentNullException(nameof(fonts)); + this.signatures = signatures ?? throw new ArgumentNullException(nameof(signatures)); + this.archival = archival ?? throw new ArgumentNullException(nameof(archival)); + } + + /// + public async Task DiagnoseAsync( + IPdfContentSource source, + string? password = null, + PdfAProfile? archivalProfile = null, + CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(source); + + if (archivalProfile is { } profile && !Enum.IsDefined(profile)) + { + throw new ArgumentOutOfRangeException( + nameof(archivalProfile), + archivalProfile, + "The PDF/A profile is not one the engine writes."); + } + + var document = await inspector + .InspectAsync(source, password, cancellationToken) + .ConfigureAwait(false); + + // The other reads would throw on a document that stays closed. The inspector has already said + // what stands in the way, so the answer is returned instead of an exception. + if (!document.IsReadable) + { + return new PdfDiagnosticsReport + { + Document = document, + Warnings = [.. document.Warnings], + }; + } + + var fontResult = await fonts + .ReadFontsAsync(source, password, cancellationToken) + .ConfigureAwait(false); + + var signatureResult = await signatures + .ValidateAsync(source, trust: null, password, cancellationToken) + .ConfigureAwait(false); + + PdfAConversionResult? archivalResult = null; + + if (archivalProfile is { } archivalProfileValue) + { + // The writer's own pre-flight, with a destination that discards: a report is read-only, and + // the result says what would be refused without a document being kept. + archivalResult = await archival + .ConvertAsync(source, Stream.Null, archivalProfileValue, options: null, password, cancellationToken) + .ConfigureAwait(false); + } + + var warnings = new List(); + Add(warnings, document.Warnings); + Add(warnings, fontResult.Warnings); + + if (archivalResult is { } archivalWarnings) + { + Add(warnings, archivalWarnings.Warnings); + } + + return new PdfDiagnosticsReport + { + Document = document, + Fonts = fontResult.Items, + Signatures = signatureResult, + Archival = archivalResult, + Warnings = warnings, + }; + } + + /// Adds the warnings that are not already in the report, in the order they arrive. + /// The merged list. + /// The warnings of one sub-read. + private static void Add(List destination, IEnumerable warnings) => + destination.AddRange(warnings.Where(warning => !destination.Contains(warning))); +} diff --git a/src/SharpCorePDF.DependencyInjection/SharpCorePDFServiceCollectionExtensions.cs b/src/SharpCorePDF.DependencyInjection/SharpCorePDFServiceCollectionExtensions.cs index 27689be..1007003 100644 --- a/src/SharpCorePDF.DependencyInjection/SharpCorePDFServiceCollectionExtensions.cs +++ b/src/SharpCorePDF.DependencyInjection/SharpCorePDFServiceCollectionExtensions.cs @@ -123,6 +123,7 @@ private static IServiceCollection AddSharpCorePDFCore(this IServiceCollection se services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); return services; } diff --git a/src/SharpCorePDF.Domain/Ports/IPdfDiagnoser.cs b/src/SharpCorePDF.Domain/Ports/IPdfDiagnoser.cs new file mode 100644 index 0000000..bae0072 --- /dev/null +++ b/src/SharpCorePDF.Domain/Ports/IPdfDiagnoser.cs @@ -0,0 +1,42 @@ +using SharpCorePDF.Domain.ReadModels; +using SharpCorePDF.Domain.ValueObjects; + +namespace SharpCorePDF.Domain.Ports; + +/// +/// Inspects a document once and returns the report a support engineer needs: what the document is, the +/// fonts it uses, the signatures it carries, an optional archival pre-flight, and every warning the +/// sub-reads made. +/// +/// +/// +/// The report is assembled from the existing use cases rather than from a second walk of the file, so it +/// cannot disagree with them. It is read-only and redaction-explicit: it names sources and describes +/// structure, and it never returns stream contents. +/// +/// +/// A document that is encrypted and stays closed is reported, not thrown: +/// and answer what stands in the way, exactly as the other +/// reads do. Only content that is not a PDF at all raises +/// . +/// +/// +public interface IPdfDiagnoser +{ + /// Reads one report about a document. + /// The content to diagnose. + /// The user or owner password, when the document is encrypted. + /// + /// The PDF/A profile to pre-flight, or to skip the archival check. The check is + /// the writer's own, so the report names exactly the requirements the writer would refuse. + /// + /// A token to cancel the operation. + /// The report: the document, its fonts, its signatures, the archival result and the warnings. + /// is . + /// The content is not a readable PDF document. + Task DiagnoseAsync( + IPdfContentSource source, + string? password = null, + PdfAProfile? archivalProfile = null, + CancellationToken cancellationToken = default); +} diff --git a/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt b/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt index 7dc5c58..0002408 100644 --- a/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt +++ b/src/SharpCorePDF.Domain/PublicAPI.Unshipped.txt @@ -1 +1,23 @@ #nullable enable +override SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Equals(object? obj) -> bool +override SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.GetHashCode() -> int +override SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.ToString() -> string! +SharpCorePDF.Domain.Ports.IPdfDiagnoser +SharpCorePDF.Domain.Ports.IPdfDiagnoser.DiagnoseAsync(SharpCorePDF.Domain.Ports.IPdfContentSource! source, string? password = null, SharpCorePDF.Domain.ValueObjects.PdfAProfile? archivalProfile = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) -> System.Threading.Tasks.Task! +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.$() -> SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport! +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Archival.get -> SharpCorePDF.Domain.ReadModels.PdfAConversionResult? +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Archival.init -> void +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Document.get -> SharpCorePDF.Domain.ReadModels.PdfDocumentInfo! +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Document.init -> void +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Equals(SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport? other) -> bool +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Fonts.get -> System.Collections.Generic.IReadOnlyList! +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Fonts.init -> void +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.HasFindings.get -> bool +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.PdfDiagnosticsReport() -> void +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Signatures.get -> System.Collections.Generic.IReadOnlyList! +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Signatures.init -> void +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Warnings.get -> System.Collections.Generic.IReadOnlyList! +SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.Warnings.init -> void +static SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.operator !=(SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport? left, SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport? right) -> bool +static SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport.operator ==(SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport? left, SharpCorePDF.Domain.ReadModels.PdfDiagnosticsReport? right) -> bool diff --git a/src/SharpCorePDF.Domain/ReadModels/PdfDiagnosticsReport.cs b/src/SharpCorePDF.Domain/ReadModels/PdfDiagnosticsReport.cs new file mode 100644 index 0000000..9132ab7 --- /dev/null +++ b/src/SharpCorePDF.Domain/ReadModels/PdfDiagnosticsReport.cs @@ -0,0 +1,52 @@ +using SharpCorePDF.Domain.ValueObjects; + +namespace SharpCorePDF.Domain.ReadModels; + +/// +/// One read-only report about a document: its structure, the fonts it uses, the signatures it carries, +/// an optional archival pre-flight, and the warnings the sub-reads made. +/// +/// +/// +/// The report is assembled from the existing use cases — inspection, the font inspector, the signature +/// validator and the archival writer — so it stays in step with them. It names sources and describes +/// structure; it never returns stream contents, which is what makes it safe to log or attach to a support +/// ticket. +/// +/// +/// is the merged list of the sub-reads, de-duplicated by the remark's kind and +/// message. An empty list is a clean document; a document that had to be repaired still produces a +/// report, with the repair named here. +/// +/// +public sealed record PdfDiagnosticsReport +{ + /// Gets the description of the document. + public required PdfDocumentInfo Document { get; init; } + + /// Gets the fonts the document uses, in the order the pages first select them. + public IReadOnlyList Fonts { get; init; } = []; + + /// Gets one validation per signature, in revision order; empty when the document is unsigned. + public IReadOnlyList Signatures { get; init; } = []; + + /// + /// Gets the archival pre-flight, or when no profile was asked for or the + /// document could not be read. When it is present, says + /// whether the writer would write the document and + /// names every reason it would not. + /// + public PdfAConversionResult? Archival { get; init; } + + /// Gets the merged, de-duplicated warnings of every sub-read. + public IReadOnlyList Warnings { get; init; } = []; + + /// Gets a value indicating whether any sub-read reported a warning. + public bool HasFindings => Warnings.Count > 0; + + /// Formats the report for diagnostics. + /// The page count, the fonts, the signatures and the finding count, on one line. + public override string ToString() => string.Create( + System.Globalization.CultureInfo.InvariantCulture, + $"{Document.PageCount} page(s), {Fonts.Count} font(s), {Signatures.Count} signature(s), {Warnings.Count} finding(s)"); +} diff --git a/tests/SharpCorePDF.Tests/PdfDiagnoserTests.cs b/tests/SharpCorePDF.Tests/PdfDiagnoserTests.cs new file mode 100644 index 0000000..fed3015 --- /dev/null +++ b/tests/SharpCorePDF.Tests/PdfDiagnoserTests.cs @@ -0,0 +1,213 @@ +using System.Globalization; +using System.Text; +using Microsoft.Extensions.DependencyInjection; +using SharpCorePDF.Application.Services; +using SharpCorePDF.DependencyInjection; +using SharpCorePDF.Domain.Ports; +using SharpCorePDF.Domain.ReadModels; +using SharpCorePDF.Domain.ValueObjects; +using SharpCorePDF.Infrastructure; +using SharpCorePDF.Infrastructure.Authoring; +using SharpCorePDF.Infrastructure.Reading; +using SharpCorePDF.Infrastructure.Sources; + +namespace SharpCorePDF.Tests; + +/// +/// Tests of the one-call report: the document, its fonts, its signatures, the archival pre-flight and the +/// merged warnings, assembled from the use cases the rest of the library already exposes. +/// +public sealed class PdfDiagnoserTests +{ + private static CancellationToken Token => TestContext.Current.CancellationToken; + + private static PdfDiagnoserService Diagnoser() => new( + new PdfInspectorService(new PdfDocumentReader()), + new PdfFontInspectorService(new PdfFontInspector()), + new PdfSignatureValidatorService(new PdfDocumentSignatureValidator()), + new PdfAWriterService(new PdfAWriter())); + + private static async Task DiagnoseAsync( + byte[] bytes, + string? password = null, + PdfAProfile? archivalProfile = null) => + await Diagnoser().DiagnoseAsync( + new PdfByteArraySource(bytes, "diagnosed.pdf"), + password, + archivalProfile, + Token); + + /// A document the repository authored and never had to repair yields no finding. + [Fact] + public async Task Reports_a_clean_document_without_findings() + { + var face = PdfTypeface.FromTrueType(File.ReadAllBytes(TestAssets.EmbeddedFont)); + + var bytes = PdfDocumentBuilder.Create() + .AddPage(PdfPageSize.A4, page => page.DrawText("diagnostics", 72, 700, face, 12)) + .ToArray(); + + var report = await DiagnoseAsync(bytes); + + Assert.True(report.Document.IsReadable); + Assert.Equal(1, report.Document.PageCount); + Assert.NotEmpty(report.Fonts); + Assert.Empty(report.Signatures); + Assert.Null(report.Archival); + Assert.Empty(report.Warnings); + Assert.False(report.HasFindings); + Assert.Contains("1 page(s)", report.ToString(), StringComparison.Ordinal); + } + + /// A table the reader had to rebuild is a finding, not a failure. + [Fact] + public async Task Surfaces_a_rebuilt_cross_reference_as_a_finding() + { + var report = await DiagnoseAsync(DamageTheTableKeyword(File.ReadAllBytes(TestAssets.Outlined))); + + Assert.Equal(3, report.Document.PageCount); + Assert.Contains(report.Warnings, warning => warning.Kind == PdfWarningKind.CrossReferenceRebuilt); + Assert.True(report.HasFindings); + + // Two sub-reads can repair the same table; the report folds their remarks together. + Assert.Equal(report.Warnings.Count, report.Warnings.Distinct().Count()); + } + + /// A document that stays closed is reported, with what stands in the way, and does not throw. + [Fact] + public async Task Reports_an_encrypted_document_without_throwing() + { + var report = await DiagnoseAsync(await File.ReadAllBytesAsync(TestAssets.Encrypted, Token)); + + Assert.False(report.Document.IsReadable); + Assert.True(report.Document.RequiresPassword); + Assert.Empty(report.Fonts); + Assert.Empty(report.Signatures); + Assert.Null(report.Archival); + Assert.NotEmpty(report.Warnings); + } + + /// A profile turns the report into the writer's pre-flight, without writing a file. + [Fact] + public async Task Surfaces_the_archival_requirements_when_a_profile_is_named() + { + var face = PdfTypeface.FromTrueType(File.ReadAllBytes(TestAssets.EmbeddedFont)); + + var bytes = PdfDocumentBuilder.Create() + .AddPage(PdfPageSize.A4, page => page.DrawText("archive me", 72, 700, face, 12)) + .ToArray(); + + var report = await DiagnoseAsync(bytes, archivalProfile: PdfAProfile.PdfA2B); + + Assert.NotNull(report.Archival); + Assert.Equal(PdfAProfile.PdfA2B, report.Archival.Profile); + Assert.True(report.Archival.IsWritten); + } + + /// A null source is refused before anything is opened. + [Fact] + public async Task Refuses_a_null_source() + { + await Assert.ThrowsAsync(() => Diagnoser().DiagnoseAsync(null!)); + } + + /// The container resolves the diagnoser, so an application does not have to wire it by hand. + [Fact] + public void Is_registered_in_the_container() + { + using var provider = new ServiceCollection() + .AddSharpCorePDF() + .BuildServiceProvider(); + + Assert.NotNull(provider.GetService()); + } + + /// An undefined profile is refused before the source is read. + [Fact] + public async Task Refuses_an_undefined_profile() + { + await Assert.ThrowsAsync(() => + Diagnoser().DiagnoseAsync( + new PdfByteArraySource([], "empty.pdf"), + archivalProfile: (PdfAProfile)99)); + } + + /// A warning only the font read makes is part of the report, not lost in the merge. + [Fact] + public async Task Reports_a_font_warning_the_inspection_did_not_make() + { + var report = await DiagnoseAsync(PdfContentFixtures.Fonts()); + + Assert.Contains(report.Warnings, warning => warning.Kind == PdfWarningKind.FontDescriptorMissing); + } + + /// A document that stays closed is read once: the other use cases are not asked. + [Fact] + public async Task Reads_a_closed_document_once() + { + var source = new CountingSource(await File.ReadAllBytesAsync(TestAssets.Encrypted, Token), "encrypted.pdf"); + + var report = await Diagnoser().DiagnoseAsync(source); + + Assert.False(report.Document.IsReadable); + Assert.Equal(1, source.Opens); + } + + /// Reads the offset a document announces behind its startxref keyword. + /// The bytes of the document. + /// The offset. + private static int ReadStartxrefOffset(byte[] bytes) + { + var text = Encoding.Latin1.GetString(bytes); + var start = text.LastIndexOf("startxref", StringComparison.Ordinal) + "startxref".Length; + + while (start < text.Length && char.IsWhiteSpace(text[start])) + { + start++; + } + + var end = start; + + while (end < text.Length && char.IsAsciiDigit(text[end])) + { + end++; + } + + return int.Parse(text[start..end], CultureInfo.InvariantCulture); + } + + /// Rewrites the xref keyword of a document that carries a classic table. + /// The bytes of the document. + /// The damaged bytes. + private static byte[] DamageTheTableKeyword(byte[] bytes) + { + var offset = ReadStartxrefOffset(bytes); + + Assert.Equal("xref", Encoding.Latin1.GetString(bytes, offset, 4)); + + "Xref"u8.CopyTo(bytes.AsSpan(offset)); + return bytes; + } + + /// A content source that counts how often it is opened. + /// The bytes the source serves. + /// The display name of the source. + private sealed class CountingSource(byte[] bytes, string name) : IPdfContentSource + { + /// Gets the number of times the source has been opened. + public int Opens { get; private set; } + + /// + public string DisplayName => name; + + /// + public long? Length => bytes.Length; + + /// + public ValueTask OpenReadAsync(CancellationToken cancellationToken = default) + { + Opens++; + return ValueTask.FromResult(new MemoryStream(bytes, writable: false)); + } + } +} diff --git a/tools/SharpCorePDF.Diagnostics/Program.cs b/tools/SharpCorePDF.Diagnostics/Program.cs new file mode 100644 index 0000000..59ea5d4 --- /dev/null +++ b/tools/SharpCorePDF.Diagnostics/Program.cs @@ -0,0 +1,180 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using SharpCorePDF.Application.Services; +using SharpCorePDF.Domain.Ports; +using SharpCorePDF.Domain.ReadModels; +using SharpCorePDF.Domain.ValueObjects; +using SharpCorePDF.Infrastructure; +using SharpCorePDF.Infrastructure.Authoring; +using SharpCorePDF.Infrastructure.Reading; +using SharpCorePDF.Infrastructure.Sources; + +namespace SharpCorePDF.Diagnostics; + +/// +/// Prints the one-call diagnostics report for a PDF: the document, its fonts, its signatures, an +/// optional archival pre-flight and the warnings the sub-reads made. +/// +/// +/// dotnet run --project tools/SharpCorePDF.Diagnostics -- <file.pdf> [--password <p>] [--profile 1b|2b|3b|2u|3u] [--json] +/// +internal static class Program +{ + private static async Task Main(string[] args) + { + if (args.Length == 0 || args.Contains("--help") || args.Contains("-h")) + { + PrintUsage(); + return args.Length == 0 ? 1 : 0; + } + + string? path = null; + string? password = null; + PdfAProfile? profile = null; + var json = false; + + for (var index = 0; index < args.Length; index++) + { + switch (args[index]) + { + case "--password": + index++; + if (index >= args.Length) + { + Console.Error.WriteLine("--password needs a value."); + return 1; + } + + password = args[index]; + break; + case "--profile": + index++; + if (index >= args.Length || !TryProfile(args[index], out var parsed)) + { + Console.Error.WriteLine("--profile needs one of 1b, 2b, 3b, 2u or 3u."); + return 1; + } + + profile = parsed; + break; + case "--json": + json = true; + break; + default: + if (args[index].StartsWith('-')) + { + Console.Error.WriteLine("unknown argument: " + args[index]); + return 1; + } + + path ??= args[index]; + break; + } + } + + if (path is null || !File.Exists(path)) + { + Console.Error.WriteLine(path is null ? "no PDF was named." : $"{path} does not exist."); + return 1; + } + + try + { + var diagnoser = new PdfDiagnoserService( + new PdfInspectorService(new PdfDocumentReader()), + new PdfFontInspectorService(new PdfFontInspector()), + new PdfSignatureValidatorService(new PdfDocumentSignatureValidator()), + new PdfAWriterService(new PdfAWriter())); + + var report = await diagnoser + .DiagnoseAsync(new PdfFileSource(path), password, profile, CancellationToken.None) + .ConfigureAwait(false); + + if (json) + { + var options = new JsonSerializerOptions + { + WriteIndented = true, + Converters = { new JsonStringEnumConverter() }, + }; + + Console.WriteLine(JsonSerializer.Serialize(report, options)); + } + else + { + Print(report); + } + + return 0; + } + catch (Exception exception) when (exception is not OperationCanceledException) + { + Console.Error.WriteLine("error: " + exception.Message); + return 1; + } + } + + /// Prints the report as the lines a support engineer reads first. + /// The report to print. + private static void Print(PdfDiagnosticsReport report) + { + var document = report.Document; + + Console.WriteLine($"document : {document.SourceName}"); + Console.WriteLine($"version : {document.Version}, {document.PageCount} page(s), readable {document.IsReadable}"); + Console.WriteLine($"fonts : {report.Fonts.Count}"); + + foreach (var font in report.Fonts) + { + Console.WriteLine($" {font.ResourceName,-6} {font.BaseFont,-24} {font.Kind,-10} {font.Program}"); + } + + Console.WriteLine($"signatures : {report.Signatures.Count}"); + + foreach (var signature in report.Signatures) + { + Console.WriteLine($" {signature}"); + } + + Console.WriteLine(report.Archival is { } archival + ? $"archival : {archival}" + : "archival : not checked"); + + Console.WriteLine($"findings : {report.Warnings.Count}"); + + foreach (var warning in report.Warnings) + { + Console.WriteLine($" [{warning.Kind}] {warning.Message}"); + } + } + + /// Maps the short profile names the command line accepts. + /// The value after --profile. + /// The profile, when the value names one. + /// when the value names a profile. + private static bool TryProfile(string text, out PdfAProfile profile) + { + profile = text.ToLowerInvariant() switch + { + "1b" => PdfAProfile.PdfA1B, + "2b" => PdfAProfile.PdfA2B, + "3b" => PdfAProfile.PdfA3B, + "2u" => PdfAProfile.PdfA2U, + "3u" => PdfAProfile.PdfA3U, + _ => (PdfAProfile)(-1), + }; + + return Enum.IsDefined(profile); + } + + private static void PrintUsage() + { + Console.WriteLine("SharpCorePDF diagnostics"); + Console.WriteLine(); + Console.WriteLine(" SharpCorePDF.Diagnostics [--password

] [--profile 1b|2b|3b|2u|3u] [--json]"); + Console.WriteLine(); + Console.WriteLine(" --password the user or owner password, when the document is encrypted"); + Console.WriteLine(" --profile also run the PDF/A pre-flight for that profile"); + Console.WriteLine(" --json print the whole report as JSON instead of the text summary"); + } +} diff --git a/tools/SharpCorePDF.Diagnostics/SharpCorePDF.Diagnostics.csproj b/tools/SharpCorePDF.Diagnostics/SharpCorePDF.Diagnostics.csproj new file mode 100644 index 0000000..ac87868 --- /dev/null +++ b/tools/SharpCorePDF.Diagnostics/SharpCorePDF.Diagnostics.csproj @@ -0,0 +1,28 @@ + + + + + Exe + net11.0 + preview + enable + enable + true + latest-recommended + false + false + true + + + + + + + + +