From c217a6268829abf83d484506afe0cf44f0ecc6df Mon Sep 17 00:00:00 2001 From: mahach666 <79989386+mahach666@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:51:16 +0300 Subject: [PATCH] Keep existing HTML exports intact on failure --- CHANGELOG.md | 2 + src/IOViewer/Exporters/HtmlViewerExporter.cs | 53 +++++++- src/IOViewer/Exporters/ViewerPayloadWriter.cs | 83 ++++++++++-- src/IOViewer/Legacy/LegacySnapshot.cs | 10 +- .../IOViewer.Tests/HtmlViewerExporterTests.cs | 120 ++++++++++++++++-- tests/IOViewer.Tests/LegacyFixtureTests.cs | 31 ++++- 6 files changed, 269 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f0ba22..c028287 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ API between minor releases. - Preserve all 64 bits of element IDs in HTML properties, Copy Id, clash results and 4D tasks. - Report the required byte count and the limit when an HTML export exceeds its binary buffer capacity. +- Save HTML to a temporary sibling file and replace the destination after a complete write. Report invalid coordinates, + duplicate element IDs, missing textures and conflicting legacy mesh arrays before publishing the output. ## [0.3.1] - 2026-11-13 diff --git a/src/IOViewer/Exporters/HtmlViewerExporter.cs b/src/IOViewer/Exporters/HtmlViewerExporter.cs index 450334e..de3740f 100644 --- a/src/IOViewer/Exporters/HtmlViewerExporter.cs +++ b/src/IOViewer/Exporters/HtmlViewerExporter.cs @@ -1,3 +1,4 @@ +using System.Security.AccessControl; using System.Text; using System.Text.RegularExpressions; using IOScene; @@ -22,16 +23,62 @@ public static void Export(SceneDocument scene, Stream stream, HtmlViewerOptions? public static string ExportToString(SceneDocument scene, HtmlViewerOptions? options = null) => ExportToString(new ViewerDocument(scene), options); + /// Writes a complete viewer page to a temporary file next to the destination before replacing it. + /// The document contains invalid viewer data. public static void Save(ViewerDocument doc, string filePath, HtmlViewerOptions? options = null) { ArgumentNullException.ThrowIfNull(doc); ArgumentNullException.ThrowIfNull(doc.Scene); ArgumentNullException.ThrowIfNull(filePath); - // Validated before the file is opened, so invalid data never truncates an existing page. var payload = ViewerPayloadWriter.Create(doc, options ?? new HtmlViewerOptions()); - using var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); - Write(payload, fs); + var target = new FileInfo(filePath); + if (target.LinkTarget is not null && target.ResolveLinkTarget(returnFinalTarget: true) is { } linked) + target = new FileInfo(linked.FullName); + bool replace = target.Exists; + if (replace) + { + // Check write access and sharing before the rename, which can ignore write permissions on Unix. + using var existing = target.Open(FileMode.Open, FileAccess.Write, FileShare.None); + } + + var temporary = new FileInfo(Path.Combine(target.DirectoryName!, $".ioviewer-{Guid.NewGuid():N}.tmp")); + var stream = OpenTemporary(temporary, replace ? target : null); + bool moved = false; + try + { + using (stream) + { + Write(payload, stream); + if (replace && !OperatingSystem.IsWindows()) + File.SetUnixFileMode(stream.SafeFileHandle, File.GetUnixFileMode(target.FullName)); + } + File.Move(temporary.FullName, target.FullName, overwrite: replace); + moved = true; + } + finally + { + if (!moved) temporary.Delete(); + } + } + + private static FileStream OpenTemporary(FileInfo temporary, FileInfo? target) + { + if (target is null) return temporary.Open(FileMode.CreateNew, FileAccess.Write, FileShare.None); + if (OperatingSystem.IsWindows()) + { + var access = target.GetAccessControl(AccessControlSections.Access); + return temporary.Create(FileMode.CreateNew, FileSystemRights.Write, FileShare.None, 4096, FileOptions.None, access); + } + + // A replacement may be more private than its parent directory. + return temporary.Open(new FileStreamOptions + { + Mode = FileMode.CreateNew, + Access = FileAccess.Write, + Share = FileShare.None, + UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite, + }); } public static void Export(ViewerDocument doc, Stream stream, HtmlViewerOptions? options = null) diff --git a/src/IOViewer/Exporters/ViewerPayloadWriter.cs b/src/IOViewer/Exporters/ViewerPayloadWriter.cs index e9cacb0..d76d90d 100644 --- a/src/IOViewer/Exporters/ViewerPayloadWriter.cs +++ b/src/IOViewer/Exporters/ViewerPayloadWriter.cs @@ -66,6 +66,7 @@ public static ViewerPayloadWriter Create(ViewerDocument doc, HtmlViewerOptions o var writer = new ViewerPayloadWriter(doc, options); writer.Build(); writer.BuildSections(doc); + writer.ValidateMetadata(); return writer; } @@ -103,6 +104,48 @@ private void BuildSections(ViewerDocument doc) private static bool IsFinite(Vector3d v) => double.IsFinite(v.X) && double.IsFinite(v.Y) && double.IsFinite(v.Z); + private void ValidateMetadata() + { + if (_options.IncludeViewpoints) + { + foreach (var view in _scene.Viewpoints) + { + if (!IsFinite(view.Camera.Position - _rtcOffset) || !IsFinite(view.Camera.Target - _rtcOffset)) + throw new InvalidDataException($"Viewpoint '{view.Name}' has a non-finite camera position or target."); + } + } + if (_options.IncludeGrids) + { + foreach (var line in _scene.Grids.SelectMany(g => g.Lines)) + { + if (!IsFinite(line.Start - _rtcOffset) || !IsFinite(line.End - _rtcOffset)) + throw new InvalidDataException($"Grid line '{line.Name}' has a non-finite endpoint."); + } + } + if (_options.IncludeClashes) + { + foreach (var clash in _scene.ClashTests.SelectMany(test => test.Clashes)) + { + if (!IsFinite(clash.Point - _rtcOffset) || clash.Distance is double distance && !double.IsFinite(distance)) + throw new InvalidDataException($"Clash '{clash.Id}' has a non-finite point or distance."); + } + } + if (_options.IncludeTimeLiner) + { + foreach (var schedule in _scene.Schedules) + { + var pending = new Stack(schedule.Tasks); + var visited = new HashSet(ReferenceEqualityComparer.Instance); + while (pending.TryPop(out var task)) + { + if (!visited.Add(task)) throw new InvalidDataException($"Task '{task.Id}' occurs more than once in schedule '{schedule.Name}'."); + if (!double.IsFinite(task.Progress)) throw new InvalidDataException($"Task '{task.Id}' has non-finite progress."); + foreach (var child in task.Children) pending.Push(child); + } + } + } + } + /// Counts the instances the viewer does not draw because their geometry is not made of triangles. public static int UndrawnInstances(SceneDocument scene) { @@ -121,6 +164,9 @@ private void Build() throw new InvalidDataException($"Geometry id {geometry.Id} is used by more than one geometry."); } if (geometry.Topology == SceneTopology.Triangles) CheckIndices(geometry.Indices, geometry.Vertices.Count, $"Geometry {geometry.Id}"); + if (!geometry.Vertices.All(IsFinite) || geometry.Normals?.All(IsFinite) == false + || geometry.UVs?.All(uv => double.IsFinite(uv.X) && double.IsFinite(uv.Y)) == false) + throw new InvalidDataException($"Geometry {geometry.Id} has a non-finite vertex, normal or UV coordinate."); } // Instances per geometry, and the largest axis length of any of them: grid steps in local units grow by it. @@ -135,17 +181,36 @@ private void Build() } uses[instance.GeometryId] = uses.GetValueOrDefault(instance.GeometryId) + 1; if (instance.Transform is not { } t) continue; + if (!IsFinite(t.XAxis) || !IsFinite(t.YAxis) || !IsFinite(t.ZAxis) || !IsFinite(t.Translation)) + throw new InvalidDataException($"Instance of element {instance.ElementId} has a non-finite transform."); double scale = Math.Max(t.XAxis.Length, Math.Max(t.YAxis.Length, t.ZAxis.Length)); maxScale[instance.GeometryId] = Math.Max(maxScale.GetValueOrDefault(instance.GeometryId), scale); } - foreach (var material in _scene.Materials) _materialsById.TryAdd(material.Id, material); - for (int i = 0; i < _scene.Textures.Count; i++) _textureIndex.TryAdd(_scene.Textures[i].Id, i); + for (int i = 0; i < _scene.Textures.Count; i++) + { + var texture = _scene.Textures[i]; + if (!double.IsFinite(texture.ScaleX) || !double.IsFinite(texture.ScaleY)) + throw new InvalidDataException($"Texture {texture.Id} has a non-finite scale."); + _textureIndex.TryAdd(texture.Id, i); + } + foreach (var material in _scene.Materials) + { + if (material.TextureId is int textureId && !_textureIndex.ContainsKey(textureId)) + throw new InvalidDataException($"Material {material.Id} references missing texture {textureId}."); + _materialsById.TryAdd(material.Id, material); + } var elementIndex = new Dictionary(); - for (int i = 0; i < _scene.Elements.Count; i++) elementIndex.TryAdd(_scene.Elements[i].Id, i); + for (int i = 0; i < _scene.Elements.Count; i++) + { + long id = _scene.Elements[i].Id; + if (!elementIndex.TryAdd(id, i)) throw new InvalidDataException($"Element id {id} is used by more than one element."); + } _bounds = _scene.ComputeBounds(); _rtcOffset = _bounds.IsEmpty ? Vector3d.Zero : _bounds.Center; + if (!IsFinite(_rtcOffset) || !_bounds.IsEmpty && (!IsFinite(_bounds.Min - _rtcOffset) || !IsFinite(_bounds.Max - _rtcOffset))) + throw new InvalidDataException("The scene bounds are not finite in viewer coordinates."); var sharedOutput = new Dictionary(); long totalVertices = 0; @@ -463,24 +528,17 @@ public void WriteProps(Stream output) { var sets = new Dictionary(); foreach (var set in _scene.PropertySets) sets.TryAdd(set.Id, set); - // JSON.parse keeps only the last of equal member names, so no object here may repeat one. The page finds - // properties by element id, so elements that share an id (which Validate rejects) are one entry. - var setIds = new Dictionary>(); - foreach (var el in _scene.Elements) - { - setIds[el.Id] = setIds.TryGetValue(el.Id, out var ids) ? ids.Concat(el.PropertySetIds) : el.PropertySetIds; - } var referenced = new HashSet(); var names = new HashSet(); var nextSuffix = new Dictionary(); foreach (var el in _scene.Elements) { - if (!setIds.Remove(el.Id, out var ids) || !ids.Any()) continue; + if (el.PropertySetIds.Count == 0) continue; w.WriteStartObject(el.Id.ToString(CultureInfo.InvariantCulture)); // Sets with the same name are one group, in the order the element first references them; a property // name used before in the group gets the first free suffix " (2)", " (3)", ... referenced.Clear(); - var groups = ids.Where(referenced.Add).Select(id => sets.GetValueOrDefault(id)).OfType().GroupBy(s => Written(s.Name)); + var groups = el.PropertySetIds.Where(referenced.Add).Select(id => sets.GetValueOrDefault(id)).OfType().GroupBy(s => Written(s.Name)); foreach (var group in groups) { w.WriteStartObject(group.Key); @@ -833,6 +891,7 @@ private static void WriteView(Utf8JsonWriter w, string name, BlobView? view) private static void WriteVector(Utf8JsonWriter w, string name, Vector3d v) { + if (!IsFinite(v)) throw new InvalidDataException($"The '{name}' vector is not finite in viewer coordinates."); w.WriteStartArray(name); w.WriteNumberValue(v.X); w.WriteNumberValue(v.Y); diff --git a/src/IOViewer/Legacy/LegacySnapshot.cs b/src/IOViewer/Legacy/LegacySnapshot.cs index f868034..a0110b8 100644 --- a/src/IOViewer/Legacy/LegacySnapshot.cs +++ b/src/IOViewer/Legacy/LegacySnapshot.cs @@ -182,7 +182,13 @@ long ElementOf(ViewerMesh mesh) } scene.Textures.Add(new SceneTexture { Id = i + 1, MimeType = texture.MimeType ?? "image/png", Data = data, ScaleX = texture.ScaleX, ScaleY = texture.ScaleY }); } - int? TextureOf(int? index) => index is int i && (uint)i < (uint)old.Textures.Count ? i + 1 : null; + int? TextureOf(int? index) + { + if (index is not int i) return null; + if ((uint)i >= (uint)old.Textures.Count) + throw new InvalidDataException($"Texture index {i} is outside the {old.Textures.Count} textures in the snapshot."); + return i + 1; + } // 0.2.0 drew a mesh with the first material of its id; the material opacity becomes the colour alpha. var materials = new Dictionary(); @@ -234,6 +240,8 @@ int CopyWithTexture(SceneMaterial? material, int? texture) if (mesh.GeometryId is int shared) { if (mesh.Vertices.Count > 0) throw new InvalidDataException($"Mesh {mesh.Id} has both geometry {shared} and its own vertices."); + if (mesh.Indices.Count > 0 || mesh.Normals is { Count: > 0 } || mesh.UVs is { Count: > 0 }) + throw new InvalidDataException($"Mesh {mesh.Id} has both geometry {shared} and its own indices, normals or UVs."); geometryId = shared; } else diff --git a/tests/IOViewer.Tests/HtmlViewerExporterTests.cs b/tests/IOViewer.Tests/HtmlViewerExporterTests.cs index 365866e..ecb2699 100644 --- a/tests/IOViewer.Tests/HtmlViewerExporterTests.cs +++ b/tests/IOViewer.Tests/HtmlViewerExporterTests.cs @@ -1,5 +1,7 @@ using System.Diagnostics; using System.Globalization; +using System.Security.AccessControl; +using System.Security.Principal; using System.Text; using System.Text.Json; using IOScene; @@ -447,6 +449,101 @@ public void Save_InvalidData_LeavesExistingFileUntouched() } } + [Theory] + [InlineData("vertex", "Geometry 1")] + [InlineData("viewpoint", "Viewpoint")] + [InlineData("grid", "Grid line")] + [InlineData("clash", "Clash")] + [InlineData("progress", "Task")] + [InlineData("texture", "Texture 9")] + public void NonFiniteData_IsRejectedBeforeWriting(string field, string diagnostic) + { + var doc = GeoreferencedModel(); + switch (field) + { + case "vertex": + doc.Scene.Geometries[0].Vertices = [new(double.NaN, 0, 0), new(1, 0, 0), new(0, 1, 0), new(1, 1, 0)]; + break; + case "viewpoint": + doc.Scene.Viewpoints[0].Camera.Target = new(0, double.PositiveInfinity, 0); + break; + case "grid": + doc.Scene.Grids[0].Lines[0].End = new(0, 0, double.NaN); + break; + case "clash": + doc.Scene.ClashTests[0].Clashes[0].Distance = double.NegativeInfinity; + break; + case "progress": + doc.Scene.Schedules[0].Tasks[0].Progress = double.NaN; + break; + case "texture": + doc.Scene.Textures.Add(new SceneTexture { Id = 9, ScaleX = double.PositiveInfinity }); + break; + } + using var stream = new MemoryStream(); + var error = Assert.Throws(() => HtmlViewerExporter.Export(doc, stream)); + Assert.Contains(diagnostic, error.Message, StringComparison.Ordinal); + Assert.Empty(stream.ToArray()); + } + + [Fact] + public void Save_ReplacesACompletePage_AndKeepsFilePermissions() + { + var folder = Directory.CreateTempSubdirectory(); + var target = new FileInfo(Path.Combine(folder.FullName, "viewer.html")); + try + { + File.WriteAllText(target.FullName, "Previous page"); + const UnixFileMode mode = UnixFileMode.UserRead | UnixFileMode.UserWrite; + if (OperatingSystem.IsWindows()) + { + using var identity = WindowsIdentity.GetCurrent(); + var access = new FileSecurity(); + access.SetAccessRuleProtection(isProtected: true, preserveInheritance: false); + access.AddAccessRule(new FileSystemAccessRule(identity.User!, FileSystemRights.FullControl, AccessControlType.Allow)); + target.SetAccessControl(access); + } + else File.SetUnixFileMode(target.FullName, mode); + + HtmlViewerExporter.Save(GeoreferencedModel(), target.FullName); + + Assert.True(ViewerHtml.Parse(File.ReadAllText(target.FullName)).InstanceCount > 0); + Assert.Single(folder.EnumerateFileSystemInfos()); + if (OperatingSystem.IsWindows()) + { + using var identity = WindowsIdentity.GetCurrent(); + var access = target.GetAccessControl(AccessControlSections.Access); + Assert.True(access.AreAccessRulesProtected); + var rule = Assert.Single(access.GetAccessRules(true, true, typeof(SecurityIdentifier)).OfType()); + Assert.Equal(identity.User, rule.IdentityReference); + Assert.Equal(FileSystemRights.FullControl, rule.FileSystemRights); + Assert.Equal(AccessControlType.Allow, rule.AccessControlType); + } + else Assert.Equal(mode, File.GetUnixFileMode(target.FullName)); + } + finally + { + folder.Delete(recursive: true); + } + } + + [Fact] + public void Save_WhenPublishFails_RemovesTheTemporaryFile() + { + var folder = Directory.CreateTempSubdirectory(); + try + { + var target = folder.CreateSubdirectory("viewer.html"); + var error = Record.Exception(() => HtmlViewerExporter.Save(GeoreferencedModel(), target.FullName)); + Assert.True(error is IOException or UnauthorizedAccessException, error?.ToString()); + Assert.Equal(target.Name, Assert.Single(folder.EnumerateFileSystemInfos()).Name); + } + finally + { + folder.Delete(recursive: true); + } + } + [Fact] public void SharedGeometryIndexOutOfRange_Throws() { @@ -582,22 +679,23 @@ public void Props_NamesWrittenAlike_AreMerged() } [Fact] - public void Props_ElementsThatShareAnId_AreOneEntry() + public void DuplicateElementId_IsRejected() { - // A scene Validate rejects, but the page finds properties by element id. var scene = TestScenes.Empty(); scene.Mesh([new(0, 0, 0), new(1, 0, 0), new(0, 1, 0)], [0, 1, 2]); - scene.Elements.Add(new SceneElement { Id = 1, ModelId = 1, Name = "Twin", PropertySetIds = [2] }); - scene.PropertySets.Add(Set(1, "Dimensions", ("Height", "3000 mm"))); - scene.PropertySets.Add(Set(2, "Identity Data", ("Mark", "D1"))); - scene.Elements[0].PropertySetIds.Add(1); + scene.Elements.Add(new SceneElement { Id = 1, ModelId = 1, Name = "Twin" }); - var view = ViewerHtml.Export(new ViewerDocument(scene)); + var error = Assert.Throws(() => HtmlViewerExporter.ExportToString(scene)); + Assert.Contains("Element id 1", error.Message, StringComparison.Ordinal); + } - AssertNoDuplicateMembers(view.Props); - var element = view.Props.GetProperty("1"); - Assert.Equal([("Height", "3000 mm")], Members(element.GetProperty("Dimensions"))); - Assert.Equal([("Mark", "D1")], Members(element.GetProperty("Identity Data"))); + [Fact] + public void MissingMaterialTexture_IsRejected() + { + var scene = TestScenes.Empty(); + scene.Materials.Add(new SceneMaterial { Id = 6, TextureId = 9 }); + var error = Assert.Throws(() => HtmlViewerExporter.ExportToString(scene)); + Assert.Contains("Material 6 references missing texture 9", error.Message, StringComparison.Ordinal); } [Fact] diff --git a/tests/IOViewer.Tests/LegacyFixtureTests.cs b/tests/IOViewer.Tests/LegacyFixtureTests.cs index 090dfe6..9dc16dc 100644 --- a/tests/IOViewer.Tests/LegacyFixtureTests.cs +++ b/tests/IOViewer.Tests/LegacyFixtureTests.cs @@ -231,12 +231,24 @@ public void SharedGeometryAndOwnTransforms_AreKept() Assert.Equal("Element 1", Assert.Single(scene.Elements).Name); // the first mesh has no name } - [Fact] - public void MeshWithGeometryAndOwnVertices_IsRejected() + [Theory] + [InlineData("vertices")] + [InlineData("indices")] + [InlineData("normals")] + [InlineData("uvs")] + public void MeshWithGeometryAndOwnArrays_IsRejected(string field) { var old = new Legacy.ViewerDocument(); old.Geometries.Add(new Legacy.ViewerGeometry { Id = 1, Vertices = [new(0, 0, 0)] }); - old.Meshes.Add(new Legacy.ViewerMesh { Id = 2, GeometryId = 1, Vertices = [new(0, 0, 0)] }); + old.Meshes.Add(new Legacy.ViewerMesh + { + Id = 2, + GeometryId = 1, + Vertices = field == "vertices" ? [new(0, 0, 0)] : [], + Indices = field == "indices" ? [0] : [], + Normals = field == "normals" ? [new(0, 0, 1)] : [], + UVs = field == "uvs" ? [new(0, 0)] : [], + }); var ex = Assert.Throws(() => Map(old)); Assert.Contains("Mesh 2 has both geometry 1", ex.Message, StringComparison.Ordinal); @@ -266,4 +278,17 @@ public void BrokenTextureData_IsRejected() Assert.Throws(() => Map(old)); } + + [Theory] + [InlineData(-1, false)] + [InlineData(1, true)] + public void OutOfRangeTextureIndex_IsRejected(int index, bool onMaterial) + { + var old = new Legacy.ViewerDocument(); + old.Textures.Add(new Legacy.ViewerTexture()); + if (onMaterial) old.Materials.Add(new Legacy.ViewerMaterial { Id = 1, TextureIndex = index }); + else old.Meshes.Add(new Legacy.ViewerMesh { Id = 1, TextureIndex = index }); + var error = Assert.Throws(() => Map(old)); + Assert.Contains($"Texture index {index}", error.Message, StringComparison.Ordinal); + } }