diff --git a/docs/public-api.md b/docs/public-api.md index ffb7699..61edd8b 100644 --- a/docs/public-api.md +++ b/docs/public-api.md @@ -45,6 +45,12 @@ use asynchronous reads and writes for file and stream overloads and pass the can to the underlying I/O. Parsing, serialization and compression perform synchronous CPU work between I/O operations. Stream overloads leave the supplied stream open. +`NwcAssembly.LoadFromDirectoryAsync` and `NwcAssembly.OpenNwfAsync` read model files asynchronously +and pass cancellation through to each read. They load models sequentially in the same order as their +synchronous counterparts. Directory discovery and reference resolution use synchronous filesystem metadata. +The `load-models` phase reports each folder model, or the primary NWF and each of its reference entries, +including missing, duplicate and unsupported references. + ## Coordination & Clash Detection (`NwcIO.Model.Clash`) | Type | Description | diff --git a/src/NwcIO/Model/NwcAssembly.cs b/src/NwcIO/Model/NwcAssembly.cs index 18c42b7..46b1521 100644 --- a/src/NwcIO/Model/NwcAssembly.cs +++ b/src/NwcIO/Model/NwcAssembly.cs @@ -1,3 +1,4 @@ +using NwcIO.Internal; using NwcIO.Internal.Json; namespace NwcIO.Model; @@ -230,7 +231,20 @@ public static NwcAssembly LoadFromDirectory( NwcReaderOptions? options, IProgress? progress, CancellationToken cancellationToken) + => LoadFromDirectoryCore(directoryPath, searchPatterns, recursive, options, progress, asynchronous: false, cancellationToken) + .GetSynchronousResult(); + + private static async ValueTask LoadFromDirectoryCore( + string directoryPath, + IReadOnlyList searchPatterns, + bool recursive, + NwcReaderOptions? options, + IProgress? progress, + bool asynchronous, + CancellationToken cancellationToken) { + if (asynchronous) cancellationToken.ThrowIfCancellationRequested(); + ArgumentNullException.ThrowIfNull(searchPatterns); if (!Directory.Exists(directoryPath)) { @@ -259,12 +273,15 @@ public static NwcAssembly LoadFromDirectory( for (int i = 0; i < files.Length; i++) { cancellationToken.ThrowIfCancellationRequested(); - docs.Add(NwcDocument.Open(files[i], options, null, cancellationToken)); + docs.Add(await OpenModel(files[i], options, asynchronous, cancellationToken).ConfigureAwait(false)); progress?.Report(new NwcProgress("load-models", i + 1, files.Length)); } string assemblyName = Path.GetFileName(directoryPath.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)); - return Create(assemblyName, docs); + cancellationToken.ThrowIfCancellationRequested(); + var assembly = Create(assemblyName, docs); + cancellationToken.ThrowIfCancellationRequested(); + return assembly; } /// @@ -282,14 +299,24 @@ public static NwcAssembly OpenNwf( NwcReaderOptions? options, IProgress? progress, CancellationToken cancellationToken) + => OpenNwfCore(nwfPath, options, progress, asynchronous: false, cancellationToken).GetSynchronousResult(); + + private static async ValueTask OpenNwfCore( + string nwfPath, + NwcReaderOptions? options, + IProgress? progress, + bool asynchronous, + CancellationToken cancellationToken) { + if (asynchronous) cancellationToken.ThrowIfCancellationRequested(); + if (!File.Exists(nwfPath)) { throw new FileNotFoundException($"NWF file not found: {nwfPath}", nwfPath); } cancellationToken.ThrowIfCancellationRequested(); - var primaryDoc = NwcDocument.Open(nwfPath, options, null, cancellationToken); + var primaryDoc = await OpenModel(nwfPath, options, asynchronous, cancellationToken).ConfigureAwait(false); var baseDir = Path.GetDirectoryName(Path.GetFullPath(nwfPath)) ?? "."; var loadedDocs = new List { primaryDoc }; @@ -307,35 +334,31 @@ public static NwcAssembly OpenNwf( foreach (var xref in primaryDoc.XRefs.References) { cancellationToken.ThrowIfCancellationRequested(); - // Every reference counts, loaded or not, so Completed reaches Total. - processed++; if (!xref.TryResolve(baseDir, out string resolved)) { unresolved.Add(xref); - progress?.Report(new NwcProgress("load-models", processed, total)); - continue; } - - // Load every resolved file once, whatever the stored path spelled like. - if (!loadedPaths.Add(Path.GetFullPath(resolved))) + else if (loadedPaths.Add(Path.GetFullPath(resolved))) { - progress?.Report(new NwcProgress("load-models", processed, total)); - continue; + // Load every resolved file once, whatever the stored path spelled like. + if (resolved.EndsWith(".nwc", StringComparison.OrdinalIgnoreCase) || + resolved.EndsWith(".nwd", StringComparison.OrdinalIgnoreCase)) + { + loadedDocs.Add(await OpenModel(resolved, options, asynchronous, cancellationToken).ConfigureAwait(false)); + } + else + { + skipped.Add(xref); + } } - if (!resolved.EndsWith(".nwc", StringComparison.OrdinalIgnoreCase) && - !resolved.EndsWith(".nwd", StringComparison.OrdinalIgnoreCase)) - { - skipped.Add(xref); - progress?.Report(new NwcProgress("load-models", processed, total)); - continue; - } - - loadedDocs.Add(NwcDocument.Open(resolved, options, null, cancellationToken)); + // Every reference counts, including entries that did not load a model. + processed++; progress?.Report(new NwcProgress("load-models", processed, total)); } } + cancellationToken.ThrowIfCancellationRequested(); string assemblyName = Path.GetFileNameWithoutExtension(nwfPath); var assembly = Create(assemblyName, loadedDocs); assembly.UnresolvedXRefs = unresolved; @@ -353,25 +376,34 @@ public static NwcAssembly OpenNwf( $"Skipped unsupported NWF reference: '{x.EffectivePath}'."))); assembly.Diagnostics = diagnostics; } + + cancellationToken.ThrowIfCancellationRequested(); return assembly; } - /// Loads a folder asynchronously. The current implementation wraps the synchronous loader. + private static ValueTask OpenModel( + string path, NwcReaderOptions? options, bool asynchronous, CancellationToken cancellationToken) => + asynchronous + ? new ValueTask(NwcDocument.OpenAsync(path, options, cancellationToken: cancellationToken)) + : ValueTask.FromResult(NwcDocument.Open(path, options, progress: null, cancellationToken)); + + /// Loads documents in a folder using asynchronous file reads. public static Task LoadFromDirectoryAsync( string directoryPath, string searchPattern = "*.nwc", NwcReaderOptions? options = null, IProgress? progress = null, CancellationToken cancellationToken = default) - => Task.Run(() => LoadFromDirectory(directoryPath, searchPattern, options, progress, cancellationToken), cancellationToken); + => LoadFromDirectoryCore(directoryPath, [searchPattern], recursive: false, options, progress, + asynchronous: true, cancellationToken).AsTask(); - /// Opens a .nwf asynchronously. The current implementation wraps the synchronous loader. + /// Opens a .nwf and its referenced models using asynchronous file reads. public static Task OpenNwfAsync( string nwfPath, NwcReaderOptions? options = null, IProgress? progress = null, CancellationToken cancellationToken = default) - => Task.Run(() => OpenNwf(nwfPath, options, progress, cancellationToken), cancellationToken); + => OpenNwfCore(nwfPath, options, progress, asynchronous: true, cancellationToken).AsTask(); /// /// Builds a single document that carries the assembly scene tree, meshes with their transforms, diff --git a/tests/NwcIO.Tests/AssemblyTests.cs b/tests/NwcIO.Tests/AssemblyTests.cs index 5e3e7a4..e73a11a 100644 --- a/tests/NwcIO.Tests/AssemblyTests.cs +++ b/tests/NwcIO.Tests/AssemblyTests.cs @@ -398,8 +398,10 @@ private static void WriteNwfWithXRefs(string nwfPath, params string[] effectiveP NwcIO.Internal.Container.NwcContainerWriter.Write(fs, [xrefStream]); } - [Fact] - public void OpenNwf_ResolvesSubfoldersDeduplicatesAndReportsMissing() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task OpenNwf_ResolvesSubfoldersDeduplicatesAndReportsMissing(bool asynchronous) { string tempDir = Path.Combine(Path.GetTempPath(), "nwcio-nwf-" + Guid.NewGuid().ToString("N")); string archDir = Path.Combine(tempDir, "Arch"); @@ -423,7 +425,7 @@ public void OpenNwf_ResolvesSubfoldersDeduplicatesAndReportsMissing() nowhere + "/Mech/D.nwc", // nowhere to be found: unresolved "Textures/tex.png"); // resolves but unsupported: skipped - var assembly = NwcAssembly.OpenNwf(nwfPath); + var assembly = asynchronous ? await NwcAssembly.OpenNwfAsync(nwfPath) : NwcAssembly.OpenNwf(nwfPath); // nwf doc + A, B, C — B must appear once despite two references. Assert.Equal(4, assembly.Models.Count); diff --git a/tests/NwcIO.Tests/ReaderCancellationTests.cs b/tests/NwcIO.Tests/ReaderCancellationTests.cs index 65c0c1e..8a010c5 100644 --- a/tests/NwcIO.Tests/ReaderCancellationTests.cs +++ b/tests/NwcIO.Tests/ReaderCancellationTests.cs @@ -82,23 +82,25 @@ public void Open_CanceledAfterReadContainer_StopsBeforeGeometry() Assert.Equal(["read-container"], progress.Reports.Select(p => p.Phase)); } - [Fact] - public void LoadFromDirectory_CanceledBetweenModels_StopsAfterFirstModel() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task LoadFromDirectory_CanceledBetweenModels_StopsAfterFirstModel(bool asynchronous) { string directory = TempDirectory(); try { - foreach (var name in new[] { "a.nwc", "b.nwc", "c.nwc" }) - { - NwcDocument.Create().Save(Path.Combine(directory, name)); - } + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + File.WriteAllText(Path.Combine(directory, "b.nwc"), "Invalid model"); using var cancellation = new CancellationTokenSource(); var progress = new CollectingProgress { OnReport = p => { if (p.Phase == "load-models") cancellation.Cancel(); } }; - Assert.Throws(() => - NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, progress, cancellation.Token)); + var error = await Assert.ThrowsAnyAsync(() => asynchronous + ? NwcAssembly.LoadFromDirectoryAsync(directory, progress: progress, cancellationToken: cancellation.Token) + : Task.FromResult(NwcAssembly.LoadFromDirectory(directory, "*.nwc", null, progress, cancellation.Token))); - Assert.Single(progress.Reports, p => p.Phase == "load-models"); + Assert.Equal(cancellation.Token, error.CancellationToken); + Assert.Equal(new NwcProgress("load-models", 1, 2), Assert.Single(progress.Reports)); } finally { @@ -106,23 +108,34 @@ public void LoadFromDirectory_CanceledBetweenModels_StopsAfterFirstModel() } } - [Fact] - public void OpenNwf_CanceledBetweenReferences_StopsBeforeNextReference() + [Theory] + [InlineData(false, 1)] + [InlineData(false, 2)] + [InlineData(true, 1)] + [InlineData(true, 2)] + public async Task OpenNwf_CanceledBetweenModels_StopsBeforeNextReference(bool asynchronous, int cancelAfter) { string directory = TempDirectory(); try { string nwf = Path.Combine(directory, "fed.nwf"); - WriteNwf(nwf, "missing.nwc", "a.nwc"); + WriteNwf(nwf, "a.nwc", "b.nwc"); NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + File.WriteAllText(Path.Combine(directory, "b.nwc"), "Invalid model"); using var cancellation = new CancellationTokenSource(); - var progress = new CollectingProgress { OnReport = _ => cancellation.Cancel() }; + var progress = new CollectingProgress + { + OnReport = report => { if (report.Completed == cancelAfter) cancellation.Cancel(); }, + }; - Assert.Throws(() => - NwcAssembly.OpenNwf(nwf, null, progress, cancellation.Token)); + var error = await Assert.ThrowsAnyAsync(() => asynchronous + ? NwcAssembly.OpenNwfAsync(nwf, progress: progress, cancellationToken: cancellation.Token) + : Task.FromResult(NwcAssembly.OpenNwf(nwf, null, progress, cancellation.Token))); - // Only the primary document was reported: the unresolved reference was never visited. - Assert.Single(progress.Reports); + Assert.Equal(cancellation.Token, error.CancellationToken); + Assert.Equal( + Enumerable.Range(1, cancelAfter).Select(completed => new NwcProgress("load-models", completed, 3)), + progress.Reports); } finally { @@ -130,8 +143,10 @@ public void OpenNwf_CanceledBetweenReferences_StopsBeforeNextReference() } } - [Fact] - public void OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded(bool asynchronous) { string directory = TempDirectory(); try @@ -142,9 +157,11 @@ public void OpenNwf_ProgressReachesTotalWhenReferencesAreNotLoaded() File.WriteAllText(Path.Combine(directory, "tex.png"), "x"); var progress = new CollectingProgress(); - var assembly = NwcAssembly.OpenNwf(nwf, null, progress, CancellationToken.None); + var assembly = asynchronous + ? await NwcAssembly.OpenNwfAsync(nwf, progress: progress) + : NwcAssembly.OpenNwf(nwf, null, progress, CancellationToken.None); - Assert.Equal(2, assembly.Models.Count); + Assert.Equal([nwf, Path.Combine(directory, "a.nwc")], assembly.Models.Select(model => model.GetLoadedPath())); Assert.Single(assembly.UnresolvedXRefs); Assert.Single(assembly.SkippedXRefs); Assert.Equal( @@ -190,17 +207,77 @@ public async Task OpenAsyncAndSaveAsync_Roundtrip() } } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task LoadAssemblyAsync_PreCancelled_ReturnsCancelledTask(bool nwf) + { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + var progress = new CollectingProgress(); + + var task = nwf + ? NwcAssembly.OpenNwfAsync("", progress: progress, cancellationToken: cancellation.Token) + : NwcAssembly.LoadFromDirectoryAsync("", progress: progress, cancellationToken: cancellation.Token); + + var error = await Assert.ThrowsAnyAsync(() => task); + Assert.Equal(cancellation.Token, error.CancellationToken); + Assert.True(task.IsCanceled); + Assert.Empty(progress.Reports); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task LoadAssemblyAsync_CancelledAtLastModel_ReturnsCancelledTask(bool nwf) + { + string directory = TempDirectory(); + try + { + string path = Path.Combine(directory, "fed.nwf"); + if (nwf) + { + WriteNwf(path); + } + else + { + NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + } + + using var cancellation = new CancellationTokenSource(); + var progress = new CollectingProgress { OnReport = _ => cancellation.Cancel() }; + var task = nwf + ? NwcAssembly.OpenNwfAsync(path, progress: progress, cancellationToken: cancellation.Token) + : NwcAssembly.LoadFromDirectoryAsync(directory, progress: progress, cancellationToken: cancellation.Token); + + await Assert.ThrowsAnyAsync(() => task); + Assert.True(task.IsCanceled); + Assert.Equal(new NwcProgress("load-models", 1, 1), Assert.Single(progress.Reports)); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + [Fact] - public async Task LoadFromDirectoryAsync_LoadsModels() + public async Task LoadFromDirectoryAsync_LoadsModelsInPathOrder() { string directory = TempDirectory(); try { - NwcDocument.Create().Save(Path.Combine(directory, "a.nwc")); + var b = Path.Combine(directory, "b.nwc"); + var a = Path.Combine(directory, "a.nwc"); + NwcDocument.Create().Save(b); + NwcDocument.Create().Save(a); + var progress = new CollectingProgress(); - var assembly = await NwcAssembly.LoadFromDirectoryAsync(directory); + var assembly = await NwcAssembly.LoadFromDirectoryAsync(directory, + options: new NwcReaderOptions { KeepStreamCatalog = false }, progress: progress); - Assert.Single(assembly.Models); + Assert.Equal([a, b], assembly.Models.Select(model => model.GetLoadedPath())); + Assert.All(assembly.Models, model => Assert.Empty(model.Container.Streams)); + Assert.Equal([new NwcProgress("load-models", 1, 2), new NwcProgress("load-models", 2, 2)], progress.Reports); } finally {