From 875dae7fc02a087c23ee9ec245070915d8100835 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Thu, 26 Nov 2026 04:32:40 +0700 Subject: [PATCH 1/2] [SCRIPTS] run the tests by hand, by themselves only for master --- .github/workflows/tests.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index c9fa495..73cfede 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,11 +1,14 @@ name: Tests # The module built and tested on the core, by the workflow of the core. +# By itself only on the way into master; on any other branch by hand (Run workflow). on: + workflow_dispatch: push: - branches: [develop, master] + branches: [master] pull_request: + branches: [master] permissions: contents: read From a4e87c62512d83276b2a7b0e739b58d378bbdb54 Mon Sep 17 00:00:00 2001 From: MarcT1me Date: Thu, 26 Nov 2026 04:32:46 +0700 Subject: [PATCH 2/2] [SFS] [SDK] [TESTS] mount the folders of the engine, make writes safe from threads and cancellation --- global.json | 2 +- .../Stellar.FileSystem/Domains/DomainBase.cs | 110 +++++++---- .../Drivers/DirectoryDriver.cs | 185 +++++++++++++----- .../Drivers/MemoryDriver.cs | 93 ++++++--- .../Drivers/OverlayDriver.cs | 161 ++++++++++----- .../Stellar.FileSystem/EngineMounts.cs | 90 +++++++++ .../FileSystemEntryPoint.cs | 20 +- .../Stellar.FileSystem/FileSystemFiles.cs | 105 +++++++--- .../Stellar.FileSystem/SystemFolders.cs | 94 +++++++++ .../Stellar.FileSystem/VirtualFileSystem.cs | 17 +- .../EntryPointTests.cs | 29 ++- .../Stellar.FileSystem.Tests/FoldersTests.cs | 180 +++++++++++++++++ 12 files changed, 866 insertions(+), 220 deletions(-) create mode 100644 src/Managed/Stellar.FileSystem/EngineMounts.cs create mode 100644 src/Managed/Stellar.FileSystem/SystemFolders.cs create mode 100644 tests/Stellar.FileSystem.Tests/FoldersTests.cs diff --git a/global.json b/global.json index f4183af..6d9e576 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "msbuild-sdks": { - "Stellar.Sdk": "0.4.1" + "Stellar.Sdk": "0.4.2" } } diff --git a/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs b/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs index 31476f5..a8157a5 100644 --- a/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs +++ b/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs @@ -15,7 +15,7 @@ public abstract class DomainBase : Quant, IDomain { private static readonly IReadOnlyDictionary NoOptions = new Dictionary(); - private volatile bool _disposed; + private int _disposed; /// public string Name { get; } @@ -42,7 +42,7 @@ public abstract class DomainBase /// /// Gets whether the domain is disposed. /// - protected bool IsDisposed => _disposed; + protected bool IsDisposed => Volatile.Read(ref _disposed) != 0; /// /// Makes the domain. @@ -66,25 +66,34 @@ protected DomainBase(DomainMount mount, IFileSystem fileSystem, DomainCapabiliti /// /// Makes the exception for what the domain cannot do. /// - protected NotSupportedException Unsupported(string what) => - new($"The domain '{Name}' ({Scheme}) cannot {what}"); + protected NotSupportedException Unsupported(string what) + { + return new NotSupportedException($"The domain '{Name}' ({Scheme}) cannot {what}"); + } /// /// Makes the exception for a file that is not there. /// - protected FileNotFoundException NotFound(string path) => - new($"No file '{PathOf(path)}'", PathOf(path).ToString()); + protected FileNotFoundException NotFound(string path) + { + return new FileNotFoundException($"No file '{PathOf(path)}'", PathOf(path).ToString()); + } /// /// Makes the exception for a directory that is not there. /// - protected DirectoryNotFoundException DirectoryNotFound(string path) => - new($"No directory '{PathOf(path)}'"); + protected DirectoryNotFoundException DirectoryNotFound(string path) + { + return new DirectoryNotFoundException($"No directory '{PathOf(path)}'"); + } /// /// Throws if the domain is disposed. /// - protected void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); + protected void ThrowIfDisposed() + { + ObjectDisposedException.ThrowIf(IsDisposed, this); + } private void Require(DomainCapabilities capability, string what) { @@ -112,19 +121,28 @@ private void RequireFor(FileOpenOptions options) protected abstract bool TryGetEntryCore(string path, out FileEntry entry); /// The entries of a directory. - protected virtual IEnumerable EnumerateCore(string directory, string pattern, bool recursive) => + protected virtual IEnumerable EnumerateCore(string directory, string pattern, bool recursive) + { throw Unsupported("list files"); + } /// Opens a file; the options are checked against the capabilities. protected abstract Stream OpenCore(string path, FileOpenOptions options); /// Opens a file without blocking; by default, . - protected virtual ValueTask OpenAsyncCore(string path, FileOpenOptions options, - CancellationToken cancellationToken) => - new(OpenCore(path, options)); + protected virtual ValueTask OpenAsyncCore( + string path, FileOpenOptions options, + CancellationToken cancellationToken + ) + { + return new ValueTask(OpenCore(path, options)); + } /// Opens a file for reads at offsets. - protected virtual IRandomAccessFile OpenRandomAccessCore(string path) => throw Unsupported("read at offsets"); + protected virtual IRandomAccessFile OpenRandomAccessCore(string path) + { + throw Unsupported("read at offsets"); + } /// The bytes of a file in memory. protected virtual bool TryGetMemoryCore(string path, out ReadOnlyMemory data) @@ -134,17 +152,28 @@ protected virtual bool TryGetMemoryCore(string path, out ReadOnlyMemory da } /// Creates a directory. - protected virtual void CreateDirectoryCore(string path) => throw Unsupported("create directories"); + protected virtual void CreateDirectoryCore(string path) + { + throw Unsupported("create directories"); + } /// Deletes a file or a directory, never the root. - protected virtual bool DeleteCore(string path, bool recursive) => throw Unsupported("delete"); + protected virtual bool DeleteCore(string path, bool recursive) + { + throw Unsupported("delete"); + } /// Moves a file or a directory; neither is the root, and the destination is not inside the source. - protected virtual void MoveCore(string source, string destination, bool overwrite) => throw Unsupported("move"); + protected virtual void MoveCore(string source, string destination, bool overwrite) + { + throw Unsupported("move"); + } /// Watches a directory. - protected virtual IDisposable WatchCore(string directory, bool recursive, Action handler) => + protected virtual IDisposable WatchCore(string directory, bool recursive, Action handler) + { throw Unsupported("watch"); + } /// /// Releases what the domain holds: called once. @@ -163,9 +192,9 @@ protected virtual void DisposeCore() protected static bool GetFlag(IReadOnlyDictionary? options, string key, bool fallback) { if (options is null - || !options.TryGetValue(key, out var text)) + || !options.TryGetValue(key, out string? text)) return fallback; - return bool.TryParse(text, out var value) + return bool.TryParse(text, out bool value) ? value : throw new ArgumentException($"The setting '{key}' is '{text}': expected true or false"); } @@ -175,16 +204,21 @@ protected static bool GetFlag(IReadOnlyDictionary? options, stri /// /// The path inside the domain. /// The full path. - protected FilePath PathOf(string path) => FilePath.Create(Name, path); + protected FilePath PathOf(string path) + { + return FilePath.Create(Name, path); + } /// /// Makes the entry of a file, its content type from the file system. /// - protected FileEntry FileEntryOf(string path, long length, + protected FileEntry FileEntryOf( + string path, long length, DateTime? creationTimeUtc, DateTime? lastWriteTimeUtc, - long revision) + long revision + ) { - var full = PathOf(path); + FilePath full = PathOf(path); return new FileEntry(full, FileEntryKind.File, length, creationTimeUtc, lastWriteTimeUtc, FileSystem.ContentTypes.Resolve(full), revision); @@ -193,10 +227,12 @@ protected FileEntry FileEntryOf(string path, long length, /// /// Makes the entry of a directory. /// - protected FileEntry DirectoryEntryOf(string path, - DateTime? creationTimeUtc = null, DateTime? lastWriteTimeUtc = null) + protected FileEntry DirectoryEntryOf( + string path, + DateTime? creationTimeUtc = null, DateTime? lastWriteTimeUtc = null + ) { - var full = PathOf(path); + FilePath full = PathOf(path); return new FileEntry(full, FileEntryKind.Directory, 0, creationTimeUtc, lastWriteTimeUtc, default, 0); @@ -234,8 +270,10 @@ public Stream Open(string path, FileOpenOptions options) } /// - public ValueTask OpenAsync(string path, FileOpenOptions options, - CancellationToken cancellationToken = default) + public ValueTask OpenAsync( + string path, FileOpenOptions options, + CancellationToken cancellationToken = default + ) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); @@ -273,7 +311,7 @@ public bool Delete(string path, bool recursive = false) { ThrowIfDisposed(); Require(DomainCapabilities.Write, "delete"); - var normalized = FileSystemNames.NormalizePath(path); + string normalized = FileSystemNames.NormalizePath(path); if (normalized.Length == 0) throw new IOException($"The root of the domain '{Name}' cannot be deleted"); return DeleteCore(normalized, recursive); } @@ -283,8 +321,8 @@ public void Move(string source, string destination, bool overwrite = false) { ThrowIfDisposed(); Require(DomainCapabilities.Write, "move"); - var from = FileSystemNames.NormalizePath(source, nameof(source)); - var to = FileSystemNames.NormalizePath(destination, nameof(destination)); + string from = FileSystemNames.NormalizePath(source, nameof(source)); + string to = FileSystemNames.NormalizePath(destination, nameof(destination)); if (from.Length == 0 || to.Length == 0) throw new IOException($"The root of the domain '{Name}' cannot be moved"); if (from == to) return; @@ -305,12 +343,14 @@ public IDisposable Watch(string directory, bool recursive, Action ha /// public void Dispose() { - if (_disposed) return; - _disposed = true; + if (Interlocked.Exchange(ref _disposed, 1) != 0) return; DisposeCore(); GC.SuppressFinalize(this); } /// - public override string ToString() => $"{Name}:// ({Scheme} {Source})"; + public override string ToString() + { + return $"{Name}:// ({Scheme} {Source})"; + } } diff --git a/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs index 6d1498a..c6fc7f5 100644 --- a/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs +++ b/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs @@ -1,5 +1,7 @@ using System.IO.Enumeration; + using Microsoft.Win32.SafeHandles; + using Stellar.Core.Quantization; using Stellar.FileSystem.Domains; using Stellar.Kernel.FileSystem; @@ -14,11 +16,12 @@ namespace Stellar.FileSystem.Drivers; /// Options: /// /// readonly=true: no writes. A missing directory is then an error; otherwise it is created. +/// lazy=true: a missing directory is created by the first write, not by the mount. /// links=follow: follows links wherever they lead. By default a link (symbolic link, junction) that /// leads out of the directory is refused, and listings do not go into linked directories. /// /// Atomic writes go to a file beside the target, named *.stellar-tmp, which listings and watches -/// never show. +/// never show. A write that failed or was cancelled leaves the file as it was. /// public sealed class DirectoryDriver() : Quant(new MetaQuant()), IFileDriver @@ -27,7 +30,10 @@ public sealed class DirectoryDriver() public DomainScheme Scheme => DomainScheme.Directory; /// - public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new DirectoryDomain(mount, fileSystem); + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) + { + return new DirectoryDomain(mount, fileSystem); + } } /// @@ -41,6 +47,7 @@ internal sealed class AtomicFileStream private readonly string _temporary; private readonly bool _overwrite; private int _committed; + private volatile bool _failed; public AtomicFileStream(string target, bool overwrite, FileOptions options) : this(target, TemporaryOf(target), overwrite, options) @@ -57,15 +64,66 @@ private AtomicFileStream(string target, string temporary, bool overwrite, FileOp _overwrite = overwrite; } - private static string TemporaryOf(string target) => - Path.Combine(Path.GetDirectoryName(target)!, + private static string TemporaryOf(string target) + { + return Path.Combine(Path.GetDirectoryName(target)!, $".{Path.GetFileName(target)}.{Guid.NewGuid():N}{DirectoryDomain.TemporarySuffix}"); + } + + public override void Write(byte[] buffer, int offset, int count) + { + try + { + base.Write(buffer, offset, count); + } + catch + { + _failed = true; + throw; + } + } + + public override void Write(ReadOnlySpan buffer) + { + try + { + base.Write(buffer); + } + catch + { + _failed = true; + throw; + } + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return Remember(base.WriteAsync(buffer, offset, count, cancellationToken)); + } + + public override ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + return new ValueTask(Remember(base.WriteAsync(buffer, cancellationToken).AsTask())); + } + + private async Task Remember(Task write) + { + try + { + await write.ConfigureAwait(false); + } + catch + { + _failed = true; + throw; + } + } protected override void Dispose(bool disposing) { // The bytes reach the disk before the file takes their place - var commit = disposing && Volatile.Read(ref _committed) == 0 && CanWrite; - if (commit) Flush(flushToDisk: true); + bool commit = disposing && Volatile.Read(ref _committed) == 0 && CanWrite; + if (commit) Flush(true); base.Dispose(disposing); if (commit) Commit(); } @@ -79,7 +137,7 @@ public override async ValueTask DisposeAsync() } await FlushAsync().ConfigureAwait(false); - Flush(flushToDisk: true); + Flush(true); await base.DisposeAsync().ConfigureAwait(false); Commit(); } @@ -88,6 +146,12 @@ private void Commit() { if (Interlocked.Exchange(ref _committed, 1) != 0) return; + if (_failed) + { + File.Delete(_temporary); + return; + } + try { File.Move(_temporary, _target, _overwrite); @@ -116,11 +180,13 @@ internal sealed class DirectoryDomain // With a separator at the end, so "C:\Game2" is not inside "C:\Game" private readonly string _root; private readonly bool _followLinks; + private readonly bool _lazy; private static DomainCapabilities CapabilitiesOf(DomainMount mount) { - var capabilities = DomainCapabilities.Read | DomainCapabilities.Enumerate | DomainCapabilities.Watch | - DomainCapabilities.RandomAccess; + DomainCapabilities capabilities = DomainCapabilities.Read | DomainCapabilities.Enumerate | + DomainCapabilities.Watch | + DomainCapabilities.RandomAccess; return GetFlag(mount.Options, "readonly", false) ? capabilities : capabilities | DomainCapabilities.Write | DomainCapabilities.AtomicWrite; @@ -134,15 +200,17 @@ public DirectoryDomain(DomainMount mount, IFileSystem fileSystem) throw new ArgumentException($"The source of the dir domain '{mount.Name}' must be a full path, " + $"resolved by the runtime: '{mount.Source}'", nameof(mount)); - var full = Path.GetFullPath(mount.Source).TrimEnd(Separator, Path.AltDirectorySeparatorChar); + string full = Path.GetFullPath(mount.Source).TrimEnd(Separator, Path.AltDirectorySeparatorChar); _root = full + Separator; - _followLinks = Options.TryGetValue("links", out var links) && links == "follow"; + _followLinks = Options.TryGetValue("links", out string? links) && links == "follow"; + + _lazy = GetFlag(Options, "lazy", false); if (!Directory.Exists(full)) { if ((Capabilities & DomainCapabilities.Write) == 0) throw new DirectoryNotFoundException($"No directory '{full}' for the domain '{Name}'"); - Directory.CreateDirectory(full); + if (!_lazy) Directory.CreateDirectory(full); } } @@ -151,16 +219,16 @@ private string Resolve(string path) { if (path.Length == 0) return _root; - var full = _root + (Separator == '/' ? path : path.Replace('/', Separator)); + string full = _root + (Separator == '/' ? path : path.Replace('/', Separator)); if (_followLinks) return full; - for (var index = _root.Length;; index++) + for (int index = _root.Length;; index++) { index = full.IndexOf(Separator, index); - var current = index < 0 ? full : full.Substring(0, index); + string current = index < 0 ? full : full.Substring(0, index); var info = new FileInfo(current); - var attributes = (int)info.Attributes; + int attributes = (int)info.Attributes; if (attributes == -1) break; // Nothing there, nor below if ((info.Attributes & FileAttributes.ReparsePoint) != 0 && info.LinkTarget is not null && !IsInside( @@ -177,7 +245,7 @@ private string Resolve(string path) private FileEntry EntryOf(string path, FileInfo file) { // The time of the last write, and the length for file systems that keep the time coarse - var revision = unchecked((file.LastWriteTimeUtc.Ticks * 397) ^ file.Length); + long revision = unchecked((file.LastWriteTimeUtc.Ticks * 397) ^ file.Length); return FileEntryOf(path, file.Length, file.CreationTimeUtc, file.LastWriteTimeUtc, revision); } @@ -187,25 +255,27 @@ private FileEntry EntryOf(string path, FileInfo file) if (!(full + Separator).StartsWith(_root, PathComparison) || full.Length < _root.Length) return null; if (full.EndsWith(TemporarySuffix, StringComparison.Ordinal)) return null; - var relative = full.Substring(_root.Length); + string relative = full.Substring(_root.Length); if (Separator != '/') relative = relative.Replace(Separator, '/'); if (Separator == '/' && relative.Contains('\\')) return null; // A name the engine would not accept (possible on some file systems) is not a file of the domain - return FileSystemNames.TryNormalizePath(relative, out var normalized) && normalized == relative + return FileSystemNames.TryNormalizePath(relative, out string normalized) && normalized == relative ? relative : null; } - private bool IsInside(string? full) => - full is not null && (full + Separator).StartsWith(_root, PathComparison); + private bool IsInside(string? full) + { + return full is not null && (full + Separator).StartsWith(_root, PathComparison); + } private Stream OpenFile(string path, FileOpenOptions options, bool asynchronous) { - var full = Resolve(path); + string full = Resolve(path); if (Directory.Exists(full)) throw new UnauthorizedAccessException($"'{PathOf(path)}' is a directory"); - var fileOptions = asynchronous ? FileOptions.Asynchronous : FileOptions.None; + FileOptions fileOptions = asynchronous ? FileOptions.Asynchronous : FileOptions.None; if ((options.Flags & FileOpenFlags.Sequential) != 0) fileOptions |= FileOptions.SequentialScan; if ((options.Flags & FileOpenFlags.RandomAccess) != 0) fileOptions |= FileOptions.RandomAccess; @@ -241,20 +311,30 @@ private sealed class RandomAccessFile(FilePath path, SafeFileHandle handle) public long Length => RandomAccess.GetLength(handle); - public int Read(long offset, Span buffer) => RandomAccess.Read(handle, buffer, offset); + public int Read(long offset, Span buffer) + { + return RandomAccess.Read(handle, buffer, offset); + } - public ValueTask ReadAsync(long offset, Memory buffer, - CancellationToken cancellationToken = default) => - RandomAccess.ReadAsync(handle, buffer, offset, cancellationToken); + public ValueTask ReadAsync( + long offset, Memory buffer, + CancellationToken cancellationToken = default + ) + { + return RandomAccess.ReadAsync(handle, buffer, offset, cancellationToken); + } - public void Dispose() => handle.Dispose(); + public void Dispose() + { + handle.Dispose(); + } } protected override bool ExistsCore(string path) { try { - var full = Resolve(path); + string full = Resolve(path); return File.Exists(full) || Directory.Exists(full); } catch (UnauthorizedAccessException) @@ -292,8 +372,9 @@ protected override bool TryGetEntryCore(string path, out FileEntry entry) protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) { - var full = Resolve(directory); - if (!Directory.Exists(full)) throw DirectoryNotFound(directory); + string full = Resolve(directory); + if (!Directory.Exists(full)) + return _lazy && directory.Length == 0 ? [] : throw DirectoryNotFound(directory); var options = new EnumerationOptions { @@ -303,7 +384,7 @@ protected override IEnumerable EnumerateCore(string directory, string ReturnSpecialDirectories = false }; - var entries = new FileSystemEnumerable(full, + FileSystemEnumerable entries = new(full, (ref FileSystemEntry entry) => entry.ToFileSystemInfo(), options) { ShouldIncludePredicate = (ref FileSystemEntry entry) => @@ -318,7 +399,7 @@ protected override IEnumerable EnumerateCore(string directory, string IEnumerable Select(IEnumerable infos) { - foreach (var info in infos) + foreach (FileSystemInfo info in infos) { if (RelativeOf(info.FullName) is not { } path) continue; if (!_followLinks && info.LinkTarget is not null && @@ -331,29 +412,38 @@ IEnumerable Select(IEnumerable infos) } } - protected override Stream OpenCore(string path, FileOpenOptions options) => - OpenFile(path, options, asynchronous: false); + protected override Stream OpenCore(string path, FileOpenOptions options) + { + return OpenFile(path, options, false); + } - protected override ValueTask OpenAsyncCore(string path, FileOpenOptions options, - CancellationToken cancellationToken) => - new(OpenFile(path, options, asynchronous: true)); + protected override ValueTask OpenAsyncCore( + string path, FileOpenOptions options, + CancellationToken cancellationToken + ) + { + return new ValueTask(OpenFile(path, options, true)); + } protected override IRandomAccessFile OpenRandomAccessCore(string path) { - var full = Resolve(path); + string full = Resolve(path); if (!File.Exists(full)) throw NotFound(path); - var handle = File.OpenHandle(full, FileMode.Open, FileAccess.Read, + SafeFileHandle handle = File.OpenHandle(full, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, FileOptions.RandomAccess | FileOptions.Asynchronous); return new RandomAccessFile(PathOf(path), handle); } - protected override void CreateDirectoryCore(string path) => Directory.CreateDirectory(Resolve(path)); + protected override void CreateDirectoryCore(string path) + { + Directory.CreateDirectory(Resolve(path)); + } protected override bool DeleteCore(string path, bool recursive) { - var full = Resolve(path); + string full = Resolve(path); if (File.Exists(full)) { File.Delete(full); @@ -369,8 +459,8 @@ protected override bool DeleteCore(string path, bool recursive) protected override void MoveCore(string source, string destination, bool overwrite) { - var from = Resolve(source); - var to = Resolve(destination); + string from = Resolve(source); + string to = Resolve(destination); Directory.CreateDirectory(Path.GetDirectoryName(to)!); if (File.Exists(from)) File.Move(from, to, overwrite); @@ -380,7 +470,8 @@ protected override void MoveCore(string source, string destination, bool overwri protected override IDisposable WatchCore(string directory, bool recursive, Action handler) { - var full = Resolve(directory); + string full = Resolve(directory); + if (_lazy && directory.Length == 0) Directory.CreateDirectory(full); if (!Directory.Exists(full)) throw DirectoryNotFound(directory); var watcher = new FileSystemWatcher(full) @@ -400,7 +491,7 @@ protected override IDisposable WatchCore(string directory, bool recursive, Actio }; watcher.Renamed += (_, e) => { - var path = RelativeOf(e.FullPath); + string? path = RelativeOf(e.FullPath); if (path is null) return; // The end of an atomic write: the file got new content @@ -410,7 +501,7 @@ protected override IDisposable WatchCore(string directory, bool recursive, Actio return; } - var old = RelativeOf(e.OldFullPath); + string? old = RelativeOf(e.OldFullPath); handler(old is null ? new FileChange(FileChangeKind.Created, PathOf(path)) : new FileChange(FileChangeKind.Renamed, PathOf(path), PathOf(old))); diff --git a/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs index 04da96e..7399d00 100644 --- a/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs +++ b/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs @@ -14,7 +14,10 @@ public sealed class MemoryDriver() public DomainScheme Scheme => DomainScheme.Memory; /// - public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new MemoryDomain(mount, fileSystem); + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) + { + return new MemoryDomain(mount, fileSystem); + } } /// @@ -56,7 +59,7 @@ private bool AddDirectories(string path) if (path.Length == 0 || _directories.Contains(path)) return false; if (_files.ContainsKey(path)) throw new IOException($"'{PathOf(path)}' is a file"); - foreach (var ancestor in DomainPaths.AncestorsOf(path)) + foreach (string ancestor in DomainPaths.AncestorsOf(path)) { if (_files.ContainsKey(ancestor)) throw new IOException($"'{PathOf(ancestor)}' is a file"); if (!_directories.Add(ancestor)) break; @@ -69,13 +72,11 @@ private bool AddDirectories(string path) private void Notify(FileChange change) { // Out of the lock: a handler may call the domain - foreach (var watcher in _watchers) - { + foreach (Watcher watcher in _watchers) if (DomainPaths.IsIn(change.Path.Value, watcher.Directory, watcher.Recursive) || (!change.OldPath.IsEmpty && DomainPaths.IsIn(change.OldPath.Value, watcher.Directory, watcher.Recursive))) watcher.Handler(change); - } } private void Commit(string path, byte[] data) @@ -87,8 +88,8 @@ private void Commit(string path, byte[] data) if (_directories.Contains(path)) throw new UnauthorizedAccessException($"'{PathOf(path)}' became a directory"); - var now = DateTime.UtcNow; - var existed = _files.TryGetValue(path, out var old); + DateTime now = DateTime.UtcNow; + bool existed = _files.TryGetValue(path, out MemoryFile? old); AddDirectories(DomainPaths.ParentOf(path)); _files[path] = new MemoryFile(data, old?.CreationTimeUtc ?? now, now, ++_revision); kind = existed ? FileChangeKind.Changed : FileChangeKind.Created; @@ -102,7 +103,10 @@ private sealed class Unwatch(MemoryDomain domain, Watcher watcher) { public void Dispose() { - lock (domain._sync) domain._watchers = domain._watchers.Where(w => !ReferenceEquals(w, watcher)).ToArray(); + lock (domain._sync) + { + domain._watchers = domain._watchers.Where(w => !ReferenceEquals(w, watcher)).ToArray(); + } } } @@ -112,7 +116,8 @@ private sealed class CommitStream { private readonly MemoryDomain _domain; private readonly string _path; - private bool _committed; + private int _committed; + private volatile bool _failed; public CommitStream(MemoryDomain domain, string path, byte[] initial, bool append) { @@ -122,13 +127,24 @@ public CommitStream(MemoryDomain domain, string path, byte[] initial, bool appen Position = append ? Length : 0; } + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + if (cancellationToken.IsCancellationRequested) _failed = true; + return base.WriteAsync(buffer, offset, count, cancellationToken); + } + + public override ValueTask WriteAsync( + ReadOnlyMemory buffer, + CancellationToken cancellationToken = default + ) + { + if (cancellationToken.IsCancellationRequested) _failed = true; + return base.WriteAsync(buffer, cancellationToken); + } + protected override void Dispose(bool disposing) { - if (disposing && !_committed) - { - _committed = true; - _domain.Commit(_path, ToArray()); - } + if (disposing && Interlocked.Exchange(ref _committed, 1) == 0 && !_failed) _domain.Commit(_path, ToArray()); base.Dispose(disposing); } @@ -137,7 +153,10 @@ protected override void Dispose(bool disposing) /// protected override bool ExistsCore(string path) { - lock (_sync) return _files.ContainsKey(path) || _directories.Contains(path); + lock (_sync) + { + return _files.ContainsKey(path) || _directories.Contains(path); + } } /// @@ -145,7 +164,7 @@ protected override bool TryGetEntryCore(string path, out FileEntry entry) { lock (_sync) { - if (_files.TryGetValue(path, out var file)) + if (_files.TryGetValue(path, out MemoryFile? file)) { entry = FileEntryOf(path, file.Data.Length, file.CreationTimeUtc, file.LastWriteTimeUtc, file.Revision); return true; @@ -159,17 +178,17 @@ protected override bool TryGetEntryCore(string path, out FileEntry entry) /// protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) { - var entries = new List(); + List entries = new(); lock (_sync) { if (!_directories.Contains(directory)) throw DirectoryNotFound(directory); - foreach (var path in _directories) + foreach (string path in _directories) if (DomainPaths.IsIn(path, directory, recursive) && DomainPaths.Matches(pattern, DomainPaths.NameOf(path))) entries.Add(DirectoryEntryOf(path)); - foreach (var (path, file) in _files) + foreach ((string path, MemoryFile file) in _files) if (DomainPaths.IsIn(path, directory, recursive) && DomainPaths.Matches(pattern, DomainPaths.NameOf(path))) entries.Add(FileEntryOf(path, file.Data.Length, file.CreationTimeUtc, file.LastWriteTimeUtc, @@ -200,9 +219,9 @@ protected override Stream OpenCore(string path, FileOpenOptions options) } if (!options.Writes) - return new MemoryStream(file!.Data, 0, file.Data.Length, writable: false, publiclyVisible: true); + return new MemoryStream(file!.Data, 0, file.Data.Length, false, true); - var keep = file is not null && options.Mode is FileMode.Open or FileMode.OpenOrCreate or FileMode.Append; + bool keep = file is not null && options.Mode is FileMode.Open or FileMode.OpenOrCreate or FileMode.Append; return new CommitStream(this, path, keep ? file!.Data : [], options.Mode == FileMode.Append); } @@ -211,23 +230,29 @@ protected override bool TryGetMemoryCore(string path, out ReadOnlyMemory d { lock (_sync) { - var found = _files.TryGetValue(path, out var file); + bool found = _files.TryGetValue(path, out MemoryFile? file); data = found ? file!.Data : null; return found; } } /// - protected override IRandomAccessFile OpenRandomAccessCore(string path) => - TryGetMemoryCore(path, out var data) + protected override IRandomAccessFile OpenRandomAccessCore(string path) + { + return TryGetMemoryCore(path, out ReadOnlyMemory data) ? new MemoryRandomAccessFile(PathOf(path), data) : throw NotFound(path); + } /// protected override void CreateDirectoryCore(string path) { bool created; - lock (_sync) created = AddDirectories(path); + lock (_sync) + { + created = AddDirectories(path); + } + if (created) Notify(new FileChange(FileChangeKind.Created, PathOf(path))); } @@ -240,13 +265,13 @@ protected override bool DeleteCore(string path, bool recursive) { if (!_directories.Contains(path)) return false; - var inside = _files.Keys.Where(file => DomainPaths.IsIn(file, path, true)) + string[] inside = _files.Keys.Where(file => DomainPaths.IsIn(file, path, true)) .Concat(_directories.Where(directory => DomainPaths.IsIn(directory, path, true))) .ToArray(); if (inside.Length > 0 && !recursive) throw new IOException($"'{PathOf(path)}' is not empty"); - foreach (var item in inside) + foreach (string item in inside) if (!_files.Remove(item)) _directories.Remove(item); _directories.Remove(path); @@ -262,7 +287,7 @@ protected override void MoveCore(string source, string destination, bool overwri { lock (_sync) { - if (_files.TryGetValue(source, out var file)) + if (_files.TryGetValue(source, out MemoryFile? file)) { if (_directories.Contains(destination)) throw new IOException($"'{PathOf(destination)}' is a directory"); @@ -279,22 +304,26 @@ protected override void MoveCore(string source, string destination, bool overwri throw new IOException($"'{PathOf(destination)}' exists already"); AddDirectories(DomainPaths.ParentOf(destination)); - var prefix = source + "/"; - foreach (var directory in _directories + string prefix = source + "/"; + foreach (string directory in _directories .Where(d => d == source || d.StartsWith(prefix, StringComparison.Ordinal)).ToArray()) { _directories.Remove(directory); _directories.Add(destination + directory.Substring(source.Length)); } - foreach (var (path, moved) in _files.Where(f => f.Key.StartsWith(prefix, StringComparison.Ordinal)) + foreach ((string path, MemoryFile moved) in _files + .Where(f => f.Key.StartsWith(prefix, StringComparison.Ordinal)) .ToArray()) { _files.Remove(path); _files[destination + path.Substring(source.Length)] = moved with { Revision = ++_revision }; } } - else throw NotFound(source); + else + { + throw NotFound(source); + } } Notify(new FileChange(FileChangeKind.Renamed, PathOf(destination), PathOf(source))); diff --git a/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs index a6bfb39..3e945ed 100644 --- a/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs +++ b/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs @@ -23,7 +23,10 @@ public sealed class OverlayDriver() public DomainScheme Scheme => DomainScheme.Overlay; /// - public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new OverlayDomain(mount, fileSystem); + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) + { + return new OverlayDomain(mount, fileSystem); + } } internal sealed class OverlayDomain @@ -32,13 +35,15 @@ internal sealed class OverlayDomain private readonly string[] _layers; private readonly string? _writeLayer; + private readonly SemaphoreSlim _copying = new(1, 1); + private static DomainCapabilities CapabilitiesOf(DomainMount mount) { - var capabilities = DomainCapabilities.Read - | DomainCapabilities.Enumerate - | DomainCapabilities.Watch - | DomainCapabilities.RandomAccess - | DomainCapabilities.Memory; + DomainCapabilities capabilities = DomainCapabilities.Read + | DomainCapabilities.Enumerate + | DomainCapabilities.Watch + | DomainCapabilities.RandomAccess + | DomainCapabilities.Memory; return mount.Options?.ContainsKey("write") == true ? capabilities | DomainCapabilities.Write | DomainCapabilities.AtomicWrite : capabilities; @@ -59,7 +64,7 @@ public OverlayDomain(DomainMount mount, IFileSystem fileSystem) if (_layers.Contains(Name)) throw new ArgumentException($"The overlay '{Name}' cannot be a layer of itself", nameof(mount)); - if (!Options.TryGetValue("write", out var write)) return; + if (!Options.TryGetValue("write", out string? write)) return; _writeLayer = FileSystemNames.NormalizeName(write, nameof(mount)); if (!_layers.Contains(_writeLayer)) @@ -69,52 +74,82 @@ public OverlayDomain(DomainMount mount, IFileSystem fileSystem) private IEnumerable Layers() { - foreach (var name in _layers) - if (FileSystem.Domains.TryGet(name, out var layer)) + foreach (string name in _layers) + if (FileSystem.Domains.TryGet(name, out IDomain? layer)) yield return layer; } - private IDomain WriteLayer() => - _writeLayer is not null && FileSystem.Domains.TryGet(_writeLayer, out var layer) + private IDomain WriteLayer() + { + return _writeLayer is not null && FileSystem.Domains.TryGet(_writeLayer, out IDomain? layer) ? layer : throw new InvalidOperationException( $"The write layer '{_writeLayer}' of the overlay '{Name}' is not mounted"); + } // The write layer gets its own copy of a file of a lower layer before changing it private void CopyUp(string path, IDomain layer, bool optional = false) { - var lower = Layers().FirstOrDefault(l => !ReferenceEquals(l, layer) && l.Exists(path)); + IDomain? lower = Layers().FirstOrDefault(l => !ReferenceEquals(l, layer) && l.Exists(path)); if (lower is null) { if (optional) return; throw NotFound(path); } - if (lower.TryGetEntry(path, out var entry) && entry.IsDirectory) + if (lower.TryGetEntry(path, out FileEntry entry) && entry.IsDirectory) throw Unsupported("change a directory of a lower layer"); - using var source = lower.Open(path, FileOpenOptions.Read); - using var target = layer.Open(path, FileOpenOptions.Write); + bool atomic = (layer.Capabilities & DomainCapabilities.AtomicWrite) != 0; + using Stream source = lower.Open(path, FileOpenOptions.Read); + using Stream target = layer.Open(path, atomic ? FileOpenOptions.Replace : FileOpenOptions.Write); source.CopyTo(target); } private IDomain WriteLayerFor(string path, FileOpenOptions options) { - var layer = WriteLayer(); + IDomain layer = WriteLayer(); if (options.Mode is FileMode.Open or FileMode.OpenOrCreate or FileMode.Append && !layer.Exists(path)) - CopyUp(path, layer, optional: true); + CopyUpOnce(path, layer, true); return layer; } - private IDomain ReadLayerOf(string path) => - Layers().FirstOrDefault(layer => layer.Exists(path)) ?? throw NotFound(path); + private void CopyUpOnce(string path, IDomain layer, bool optional = false) + { + _copying.Wait(); + try + { + if (!layer.Exists(path)) CopyUp(path, layer, optional); + } + finally + { + _copying.Release(); + } + } + + private async ValueTask OpenForWriteAsync( + string path, FileOpenOptions options, + CancellationToken cancellationToken + ) + { + IDomain layer = WriteLayer(); + if (options.Mode is FileMode.Open or FileMode.OpenOrCreate or FileMode.Append && !layer.Exists(path)) + await Task.Run(() => CopyUpOnce(path, layer, true), cancellationToken).ConfigureAwait(false); + + return await layer.OpenAsync(path, options, cancellationToken).ConfigureAwait(false); + } + + private IDomain ReadLayerOf(string path) + { + return Layers().FirstOrDefault(layer => layer.Exists(path)) ?? throw NotFound(path); + } private sealed class Watches(List watches) : IDisposable { public void Dispose() { - foreach (var watch in watches) watch.Dispose(); + foreach (IDisposable watch in watches) watch.Dispose(); } } @@ -125,21 +160,33 @@ private sealed class Renamed(FilePath path, IRandomAccessFile file) public long Length => file.Length; - public int Read(long offset, Span buffer) => file.Read(offset, buffer); + public int Read(long offset, Span buffer) + { + return file.Read(offset, buffer); + } - public ValueTask ReadAsync(long offset, Memory buffer, - CancellationToken cancellationToken = default) => - file.ReadAsync(offset, buffer, cancellationToken); + public ValueTask ReadAsync( + long offset, Memory buffer, + CancellationToken cancellationToken = default + ) + { + return file.ReadAsync(offset, buffer, cancellationToken); + } - public void Dispose() => file.Dispose(); + public void Dispose() + { + file.Dispose(); + } } - protected override bool ExistsCore(string path) => - Layers().Any(layer => layer.Exists(path)); + protected override bool ExistsCore(string path) + { + return Layers().Any(layer => layer.Exists(path)); + } protected override bool TryGetEntryCore(string path, out FileEntry entry) { - foreach (var layer in Layers()) + foreach (IDomain layer in Layers()) { if (!layer.TryGetEntry(path, out entry)) continue; entry = entry with { Path = entry.Path.WithDomain(Name) }; @@ -152,8 +199,8 @@ protected override bool TryGetEntryCore(string path, out FileEntry entry) protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) { - var layers = Layers() - .Where(layer => layer.TryGetEntry(directory, out var entry) && entry.IsDirectory) + IDomain[] layers = Layers() + .Where(layer => layer.TryGetEntry(directory, out FileEntry entry) && entry.IsDirectory) .ToArray(); if (layers.Length == 0) throw DirectoryNotFound(directory); @@ -162,51 +209,67 @@ protected override IEnumerable EnumerateCore(string directory, string IEnumerable Merge() { - var seen = new HashSet(StringComparer.Ordinal); - foreach (var layer in layers) - foreach (var entry in layer.Enumerate(directory, pattern, recursive)) + HashSet seen = new(StringComparer.Ordinal); + foreach (IDomain layer in layers) + foreach (FileEntry entry in layer.Enumerate(directory, pattern, recursive)) if (seen.Add(entry.Path.Value)) yield return entry with { Path = entry.Path.WithDomain(Name) }; } } - protected override Stream OpenCore(string path, FileOpenOptions options) => - options.Writes ? WriteLayerFor(path, options).Open(path, options) : ReadLayerOf(path).Open(path, options); + protected override Stream OpenCore(string path, FileOpenOptions options) + { + return options.Writes + ? WriteLayerFor(path, options).Open(path, options) + : ReadLayerOf(path).Open(path, options); + } - protected override ValueTask OpenAsyncCore(string path, FileOpenOptions options, - CancellationToken cancellationToken) => - options.Writes - ? WriteLayerFor(path, options).OpenAsync(path, options, cancellationToken) + protected override ValueTask OpenAsyncCore( + string path, FileOpenOptions options, + CancellationToken cancellationToken + ) + { + return options.Writes + ? OpenForWriteAsync(path, options, cancellationToken) : ReadLayerOf(path).OpenAsync(path, options, cancellationToken); + } - protected override IRandomAccessFile OpenRandomAccessCore(string path) => - new Renamed(PathOf(path), ReadLayerOf(path).OpenRandomAccess(path)); + protected override IRandomAccessFile OpenRandomAccessCore(string path) + { + return new Renamed(PathOf(path), ReadLayerOf(path).OpenRandomAccess(path)); + } protected override bool TryGetMemoryCore(string path, out ReadOnlyMemory data) { data = default; - var layer = Layers().FirstOrDefault(l => l.Exists(path)); + IDomain? layer = Layers().FirstOrDefault(l => l.Exists(path)); return layer is not null && layer.TryGetMemory(path, out data); } - protected override void CreateDirectoryCore(string path) => WriteLayer().CreateDirectory(path); + protected override void CreateDirectoryCore(string path) + { + WriteLayer().CreateDirectory(path); + } - protected override bool DeleteCore(string path, bool recursive) => WriteLayer().Delete(path, recursive); + protected override bool DeleteCore(string path, bool recursive) + { + return WriteLayer().Delete(path, recursive); + } protected override void MoveCore(string source, string destination, bool overwrite) { - var layer = WriteLayer(); - if (!layer.Exists(source)) CopyUp(source, layer); + IDomain layer = WriteLayer(); + if (!layer.Exists(source)) CopyUpOnce(source, layer); layer.Move(source, destination, overwrite); } protected override IDisposable WatchCore(string directory, bool recursive, Action handler) { - var watches = new List(); - foreach (var layer in Layers()) + List watches = new(); + foreach (IDomain layer in Layers()) { if ((layer.Capabilities & DomainCapabilities.Watch) == 0) continue; - if (!layer.TryGetEntry(directory, out var entry) || !entry.IsDirectory) continue; + if (!layer.TryGetEntry(directory, out FileEntry entry) || !entry.IsDirectory) continue; watches.Add(layer.Watch(directory, recursive, change => handler(change with { diff --git a/src/Managed/Stellar.FileSystem/EngineMounts.cs b/src/Managed/Stellar.FileSystem/EngineMounts.cs new file mode 100644 index 0000000..dd5b5c4 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/EngineMounts.cs @@ -0,0 +1,90 @@ +using Stellar.Kernel.Configuration; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem; + +/// +/// Tells where the domains of lie for an application. +/// +/// +/// The settings AssetsFolder and ResourcesFolder (the Runtime section of the +/// .stellar.project, or --stellar:AssetsFolder=...) move the assets and the resources: relative to the +/// application, or a full path. +/// +public static class EngineMounts +{ + /// The setting of the folder of the assets, Assets by default. + public const string AssetsSetting = "AssetsFolder"; + + /// The setting of the folder of the resources, Resources by default. + public const string ResourcesSetting = "ResourcesFolder"; + + /// The folder of applications that name no company. + public const string DefaultCompany = "Starlet"; + + private static DomainMount ReadOnly(FilePath root, string directory) + { + return new DomainMount(root.Domain, DomainScheme.Directory, directory, + new Dictionary { ["readonly"] = "true" }); + } + + // A folder nobody asked for may be missing; one asked for by name must be there (Mount throws) + private static void AddContent( + List mounts, FilePath root, RuntimeConfiguration configuration, + string setting, string byDefault + ) + { + bool asked = configuration.Settings.TryGetValue(setting, out string? folder) + && !string.IsNullOrWhiteSpace(folder); + string full = Path.GetFullPath(asked ? folder! : byDefault, SystemFolders.App); + + if (asked || Directory.Exists(full)) mounts.Add(ReadOnly(root, full)); + } + + // One folder, never a path: "..", "a/b" and "C:" must not lead anywhere else + private static string FolderName(string? name) + { + if (string.IsNullOrWhiteSpace(name)) return string.Empty; + + char[] characters = name.ToCharArray(); + for (int i = 0; i < characters.Length; i++) + if (characters[i] < ' ' || "\\/:*?\"<>|".Contains(characters[i])) + characters[i] = '_'; + + return new string(characters).Trim(' ', '.'); + } + + private static DomainMount Lazy(FilePath root, string directory) + { + return new DomainMount(root.Domain, DomainScheme.Directory, directory, + new Dictionary { ["lazy"] = "true" }); + } + + /// + /// Gets the domains to mount for an application. + /// + /// The configuration of the application. + /// The domains, in the order they are mounted. + public static IReadOnlyList Of(RuntimeConfiguration configuration) + { + ArgumentNullException.ThrowIfNull(configuration); + + List mounts = [ReadOnly(Folders.App, SystemFolders.App)]; + AddContent(mounts, Folders.Assets, configuration, AssetsSetting, "Assets"); + AddContent(mounts, Folders.Resources, configuration, ResourcesSetting, "Resources"); + + // Without a name all applications would share one folder, or get the whole folder of the user + string project = FolderName(configuration.ProjectName); + if (project.Length == 0) return mounts; + + string company = FolderName(configuration.CompanyName); + if (company.Length == 0 || company == "Unknown") company = DefaultCompany; + string own = Path.Combine(company, project); + + mounts.Add(Lazy(Folders.AppData.Roaming, Path.Combine(SystemFolders.AppData.Roaming, own))); + mounts.Add(Lazy(Folders.AppData.Local, Path.Combine(SystemFolders.AppData.Local, own))); + mounts.Add(Lazy(Folders.AppData.LocalLow, Path.Combine(SystemFolders.AppData.LocalLow, own))); + mounts.Add(Lazy(Folders.Temp, Path.Combine(SystemFolders.Temp, own))); + return mounts; + } +} diff --git a/src/Managed/Stellar.FileSystem/FileSystemEntryPoint.cs b/src/Managed/Stellar.FileSystem/FileSystemEntryPoint.cs index 81c727a..8e26787 100644 --- a/src/Managed/Stellar.FileSystem/FileSystemEntryPoint.cs +++ b/src/Managed/Stellar.FileSystem/FileSystemEntryPoint.cs @@ -6,9 +6,7 @@ namespace Stellar.FileSystem; /// -/// Publishes the file system of the engine: -/// app:// is the folder of the application, read-only, -/// user:// the folder of the user. +/// Publishes the file system of the engine, with the domains of mounted. /// [StellarEntryPoint] public sealed class FileSystemEntryPoint(RuntimeConfiguration configuration) @@ -25,21 +23,7 @@ public override int Run(ref readonly TContext context) _services = services; _fileSystem = VirtualFileSystem.CreateDefault(); - _fileSystem.Mount(new DomainMount( - "app", DomainScheme.Directory, AppContext.BaseDirectory, - new Dictionary { ["readonly"] = "true" } - )); - - if (!string.IsNullOrWhiteSpace(RuntimeConfiguration.ProjectName)) - { - string company = RuntimeConfiguration.CompanyName; - if (string.IsNullOrWhiteSpace(company) || company == "Unknown") company = "Starlet"; - _fileSystem.Mount(new DomainMount( - "user", DomainScheme.Directory, Path.Combine(Environment.GetFolderPath( - Environment.SpecialFolder.ApplicationData), - company, RuntimeConfiguration.ProjectName) - )); - } + foreach (DomainMount mount in EngineMounts.Of(RuntimeConfiguration)) _fileSystem.Mount(mount); services.Set(_fileSystem); diff --git a/src/Managed/Stellar.FileSystem/FileSystemFiles.cs b/src/Managed/Stellar.FileSystem/FileSystemFiles.cs index 72ba20c..850e141 100644 --- a/src/Managed/Stellar.FileSystem/FileSystemFiles.cs +++ b/src/Managed/Stellar.FileSystem/FileSystemFiles.cs @@ -1,4 +1,5 @@ using System.Text; + using Stellar.Kernel.FileSystem; namespace Stellar.FileSystem; @@ -15,7 +16,7 @@ public static class FileSystemFiles { private static byte[] ReadToEnd(Stream stream) { - if (stream is MemoryStream memory && memory.TryGetBuffer(out var segment)) + if (stream is MemoryStream memory && memory.TryGetBuffer(out ArraySegment segment)) return segment.AsSpan((int)memory.Position).ToArray(); var buffer = new MemoryStream(stream.CanSeek ? (int)Math.Min(stream.Length, int.MaxValue) : 0); @@ -25,8 +26,8 @@ private static byte[] ReadToEnd(Stream stream) private static Encoding EncodingOf(IFileSystem fileSystem, FilePath path) { - var charset = fileSystem.ContentTypes.Resolve(path).Charset; - if (charset is null or "utf-8" or "utf8") return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + string? charset = fileSystem.ContentTypes.Resolve(path).Charset; + if (charset is null or "utf-8" or "utf8") return new UTF8Encoding(false); try { @@ -34,7 +35,7 @@ private static Encoding EncodingOf(IFileSystem fileSystem, FilePath path) } catch (ArgumentException) { - return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + return new UTF8Encoding(false); } } @@ -55,10 +56,10 @@ private static string Decode(ReadOnlySpan data, Encoding encoding) /// A copy of its bytes. public static byte[] ReadAllBytes(this IFileSystem fileSystem, FilePath path) { - var domain = fileSystem.GetDomain(path); - if (domain.TryGetMemory(path.Value, out var memory)) return memory.ToArray(); + IDomain domain = fileSystem.GetDomain(path); + if (domain.TryGetMemory(path.Value, out ReadOnlyMemory memory)) return memory.ToArray(); - using var stream = domain.Open(path.Value, + using Stream stream = domain.Open(path.Value, FileOpenOptions.Read with { Flags = FileOpenFlags.Sequential }); return ReadToEnd(stream); } @@ -70,13 +71,15 @@ public static byte[] ReadAllBytes(this IFileSystem fileSystem, FilePath path) /// The file. /// Stops the read. /// A copy of its bytes. - public static async ValueTask ReadAllBytesAsync(this IFileSystem fileSystem, FilePath path, - CancellationToken cancellationToken = default) + public static async ValueTask ReadAllBytesAsync( + this IFileSystem fileSystem, FilePath path, + CancellationToken cancellationToken = default + ) { - var domain = fileSystem.GetDomain(path); - if (domain.TryGetMemory(path.Value, out var memory)) return memory.ToArray(); + IDomain domain = fileSystem.GetDomain(path); + if (domain.TryGetMemory(path.Value, out ReadOnlyMemory memory)) return memory.ToArray(); - await using var stream = await domain.OpenAsync(path.Value, + await using Stream stream = await domain.OpenAsync(path.Value, FileOpenOptions.Read with { Flags = FileOpenFlags.Sequential }, cancellationToken) .ConfigureAwait(false); var buffer = new MemoryStream(stream.CanSeek ? (int)Math.Min(stream.Length, int.MaxValue) : 0); @@ -92,16 +95,70 @@ public static async ValueTask ReadAllBytesAsync(this IFileSystem fileSys /// Its text. public static string ReadAllText(this IFileSystem fileSystem, FilePath path) { - var encoding = EncodingOf(fileSystem, path); - var domain = fileSystem.GetDomain(path); - if (domain.TryGetMemory(path.Value, out var memory)) return Decode(memory.Span, encoding); + Encoding encoding = EncodingOf(fileSystem, path); + IDomain domain = fileSystem.GetDomain(path); + if (domain.TryGetMemory(path.Value, out ReadOnlyMemory memory)) return Decode(memory.Span, encoding); - using var stream = domain.Open(path.Value, + using Stream stream = domain.Open(path.Value, FileOpenOptions.Read with { Flags = FileOpenFlags.Sequential }); - using var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); + using var reader = new StreamReader(stream, encoding, true); return reader.ReadToEnd(); } + /// + /// Reads a file as text without blocking on a slow source. + /// + /// The file system. + /// The file. + /// Stops the read. + /// Its text. + public static async ValueTask ReadAllTextAsync( + this IFileSystem fileSystem, FilePath path, + CancellationToken cancellationToken = default + ) + { + byte[] data = await fileSystem.ReadAllBytesAsync(path, cancellationToken).ConfigureAwait(false); + return Decode(data, EncodingOf(fileSystem, path)); + } + + /// + /// Writes the bytes of a file, replacing it, without blocking on a slow source. + /// + /// The file system. + /// The file. + /// The bytes; they must not change until the write ends. + /// Whether the file is the old one or the new one, never a part of it, a cancelled write included; needs . + /// Stops the write. + /// Ends when the file is written. + public static async ValueTask WriteAllBytesAsync( + this IFileSystem fileSystem, FilePath path, + ReadOnlyMemory data, bool atomic = false, CancellationToken cancellationToken = default + ) + { + FileOpenOptions options = atomic ? FileOpenOptions.Replace : FileOpenOptions.Write; + await using Stream stream = await fileSystem.OpenAsync(path, options, cancellationToken).ConfigureAwait(false); + await stream.WriteAsync(data, cancellationToken).ConfigureAwait(false); + } + + /// + /// Writes a file as text, replacing it, without blocking on a slow source; the charset as in . + /// + /// The file system. + /// The file. + /// The text. + /// Whether the file is the old one or the new one, never a part of it, a cancelled write included; needs . + /// Stops the write. + /// Ends when the file is written. + public static ValueTask WriteAllTextAsync( + this IFileSystem fileSystem, FilePath path, + string text, bool atomic = false, CancellationToken cancellationToken = default + ) + { + ArgumentNullException.ThrowIfNull(text); + return fileSystem.WriteAllBytesAsync(path, EncodingOf(fileSystem, path).GetBytes(text), atomic, + cancellationToken); + } + /// /// Writes the bytes of a file, replacing it. /// @@ -109,10 +166,12 @@ public static string ReadAllText(this IFileSystem fileSystem, FilePath path) /// The file. /// The bytes. /// Whether the file is the old one or the new one, never a part of it; needs . - public static void WriteAllBytes(this IFileSystem fileSystem, FilePath path, - ReadOnlySpan data, bool atomic = false) + public static void WriteAllBytes( + this IFileSystem fileSystem, FilePath path, + ReadOnlySpan data, bool atomic = false + ) { - using var stream = fileSystem.Open(path, atomic ? FileOpenOptions.Replace : FileOpenOptions.Write); + using Stream stream = fileSystem.Open(path, atomic ? FileOpenOptions.Replace : FileOpenOptions.Write); stream.Write(data); } @@ -123,8 +182,10 @@ public static void WriteAllBytes(this IFileSystem fileSystem, FilePath path, /// The file. /// The text. /// Whether the file is the old one or the new one, never a part of it; needs . - public static void WriteAllText(this IFileSystem fileSystem, FilePath path, - string text, bool atomic = false) + public static void WriteAllText( + this IFileSystem fileSystem, FilePath path, + string text, bool atomic = false + ) { ArgumentNullException.ThrowIfNull(text); fileSystem.WriteAllBytes(path, EncodingOf(fileSystem, path).GetBytes(text), atomic); diff --git a/src/Managed/Stellar.FileSystem/SystemFolders.cs b/src/Managed/Stellar.FileSystem/SystemFolders.cs new file mode 100644 index 0000000..e779d18 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/SystemFolders.cs @@ -0,0 +1,94 @@ +using System.Runtime.InteropServices; + +namespace Stellar.FileSystem; + +/// +/// The folders of the machine and its user, as full paths: sources of domains. A game names +/// instead. +/// +/// +/// Facts of the machine, not of an engine instance, so they are static; nothing is kept, safe from any thread. A +/// folder is told even if it is not there yet. +/// +public static class SystemFolders +{ + private static readonly Guid DownloadsId = new("374DE290-123F-4565-9164-39C4925E467B"); + private static readonly Guid SavedGamesId = new("4C5C32FF-BB9D-43B0-B5B4-2D72E54EAAA4"); + private static readonly Guid LocalLowId = new("A520A1A4-1780-4FF6-BD18-167343C5AF16"); + + /// Gets the folder of the application. + public static string App => AppContext.BaseDirectory; + + /// Gets the folder for temporary files. + public static string Temp => Path.GetTempPath(); + + /// Gets the folder of the user. + public static string Home => Get(Environment.SpecialFolder.UserProfile); + + /// Gets the desktop of the user. + public static string Desktop => Get(Environment.SpecialFolder.DesktopDirectory); + + /// Gets the documents of the user. + public static string Documents => Get(Environment.SpecialFolder.MyDocuments); + + /// Gets the downloads of the user. + public static string Downloads => GetKnown(DownloadsId, Path.Combine(Home, "Downloads")); + + /// Gets the pictures of the user. + public static string Pictures => Get(Environment.SpecialFolder.MyPictures); + + /// Gets the music of the user. + public static string Music => Get(Environment.SpecialFolder.MyMusic); + + /// Gets the videos of the user. + public static string Videos => Get(Environment.SpecialFolder.MyVideos); + + /// Gets the saved games of the user; on other systems than Windows, the local data. + public static string SavedGames => GetKnown(SavedGamesId, AppData.Local); + + /// Gets the data all users of the machine share. + public static string Shared => Get(Environment.SpecialFolder.CommonApplicationData); + + /// + /// The data of applications, for this user. + /// + public static class AppData + { + /// Gets the data that follows the user from machine to machine. + public static string Roaming => Get(Environment.SpecialFolder.ApplicationData); + + /// Gets the data of this machine. + public static string Local => Get(Environment.SpecialFolder.LocalApplicationData); + + /// + /// Gets the data of this machine a process with few rights may write; on other systems than Windows, the + /// same as . + /// + public static string LocalLow => GetKnown(LocalLowId, Local); + } + + private static string Get(Environment.SpecialFolder folder) + { + return Environment.GetFolderPath(folder, Environment.SpecialFolderOption.DoNotVerify); + } + + [DllImport("shell32.dll", ExactSpelling = true)] + private static extern int SHGetKnownFolderPath(in Guid id, uint flags, IntPtr token, out IntPtr path); + + // The folders .NET has no name for. The user may have moved them, so Windows is asked + private static string GetKnown(Guid id, string fallback) + { + if (!OperatingSystem.IsWindows()) return fallback; + + const uint doNotVerify = 0x4000; + int result = SHGetKnownFolderPath(in id, doNotVerify, IntPtr.Zero, out IntPtr text); + try + { + return result == 0 ? Marshal.PtrToStringUni(text) ?? fallback : fallback; + } + finally + { + Marshal.FreeCoTaskMem(text); + } + } +} diff --git a/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs b/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs index 87f65fb..1ba4b96 100644 --- a/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs +++ b/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs @@ -55,7 +55,7 @@ protected override Exception NotFound(string key) private readonly DriverCatalog _drivers = new(); private readonly DomainCatalog _domains = new(); private readonly Lock _mounting = new(); - private volatile bool _disposed; + private bool _disposed; /// public IContentTypeCatalog ContentTypes { get; } @@ -100,15 +100,15 @@ public static VirtualFileSystem CreateDefault() /// public IDomain Mount(DomainMount mount) { - ObjectDisposedException.ThrowIf(_disposed, this); - var name = FileSystemNames.NormalizeName(mount.Name, nameof(mount)); - if (!_drivers.TryGet(mount.Scheme, out var driver)) + string name = FileSystemNames.NormalizeName(mount.Name, nameof(mount)); + if (!_drivers.TryGet(mount.Scheme, out IFileDriver? driver)) throw new InvalidOperationException($"No driver of the scheme '{mount.Scheme}' is there, " + $"for the domain '{name}'"); IDomain domain; lock (_mounting) { + ObjectDisposedException.ThrowIf(_disposed, this); if (_domains.Contains(name)) throw new InvalidOperationException($"A domain '{name}' is mounted already"); @@ -156,9 +156,12 @@ public bool Unmount(string name) /// public void Dispose() { - if (_disposed) return; - _disposed = true; + lock (_mounting) + { + if (_disposed) return; + _disposed = true; + } - foreach (var name in _domains.Keys) Unmount(name); + foreach (string name in _domains.Keys) Unmount(name); } } diff --git a/tests/Stellar.FileSystem.Tests/EntryPointTests.cs b/tests/Stellar.FileSystem.Tests/EntryPointTests.cs index 14ba044..c2419fc 100644 --- a/tests/Stellar.FileSystem.Tests/EntryPointTests.cs +++ b/tests/Stellar.FileSystem.Tests/EntryPointTests.cs @@ -13,6 +13,11 @@ public sealed class EntryPointTests private static readonly string AppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + private static readonly string[] Roots = + [ + SystemFolders.AppData.Roaming, SystemFolders.AppData.Local, SystemFolders.AppData.LocalLow, SystemFolders.Temp + ]; + // Names nobody else has: what the tests leave in the real folder of the user is deleted whole private readonly string _company = "StellarTests-" + Guid.NewGuid().ToString("N"); private readonly string _project = "Project-" + Guid.NewGuid().ToString("N"); @@ -20,14 +25,18 @@ public sealed class EntryPointTests public void Dispose() { - Delete(Path.Combine(AppData, _company)); - Delete(Path.Combine(AppData, _project)); - Delete(Path.Combine(AppData, "Starlet", _project)); - Delete(Path.Combine(AppData, "Unknown", _project)); + foreach (string root in Roots) + { + Delete(Path.Combine(root, _company)); + Delete(Path.Combine(root, _project)); + Delete(Path.Combine(root, "Starlet", _project)); + Delete(Path.Combine(root, "Unknown", _project)); - // Only if it is ours: a folder of somebody else is not empty - string shared = Path.Combine(AppData, "Starlet"); - if (Directory.Exists(shared) && !Directory.EnumerateFileSystemEntries(shared).Any()) Directory.Delete(shared); + // Only if it is ours: a folder of somebody else is not empty + string shared = Path.Combine(root, "Starlet"); + if (Directory.Exists(shared) && !Directory.EnumerateFileSystemEntries(shared).Any()) + Directory.Delete(shared); + } } private static void Delete(string path) @@ -66,7 +75,7 @@ public void Run_PublishesTheFileSystem_AndStopTakesItBack() var files = _services.Find()!; files.Should().BeOfType(); - files.Domains.Keys.Should().BeEquivalentTo("app", "user"); + files.Domains.Keys.Should().BeEquivalentTo("app", "user", "local", "locallow", "temp"); Stop(entryPoint); _services.Find().Should().BeNull(); @@ -94,6 +103,7 @@ public void User_OfNoCompany_IsInStarlet(string? company) { FileSystemEntryPoint entryPoint = Make(company!, _project); Run(entryPoint, _services); + _services.Find()!.WriteAllText(FilePath.Parse("user://a.txt"), "text"); Stop(entryPoint); Directory.Exists(Path.Combine(AppData, "Starlet", _project)).Should().BeTrue(); @@ -170,7 +180,8 @@ public void TwoEngines_HaveTheirOwnFileSystems() Run(second, otherServices); Stop(first); - otherServices.Find()!.Domains.Keys.Should().BeEquivalentTo("app", "user"); + otherServices.Find()!.Domains.Keys.Should() + .BeEquivalentTo("app", "user", "local", "locallow", "temp"); Stop(second); } diff --git a/tests/Stellar.FileSystem.Tests/FoldersTests.cs b/tests/Stellar.FileSystem.Tests/FoldersTests.cs new file mode 100644 index 0000000..854b272 --- /dev/null +++ b/tests/Stellar.FileSystem.Tests/FoldersTests.cs @@ -0,0 +1,180 @@ +using Stellar.Kernel.Configuration; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Tests; + +public sealed class FoldersTests + : IDisposable +{ + private readonly string _root = + Path.Combine(Path.GetTempPath(), "Stellar.FileSystem.Tests", Guid.NewGuid().ToString("N")); + + private readonly VirtualFileSystem _files = VirtualFileSystem.CreateDefault(); + + public void Dispose() + { + _files.Dispose(); + if (Directory.Exists(_root)) Directory.Delete(_root, true); + } + + private static string SourceOf(RuntimeConfiguration configuration, FilePath root) + { + return EngineMounts.Of(configuration).Single(mount => mount.Name == root.Domain).Source; + } + + private void MountLazy(string directory) + { + _files.Mount(new DomainMount("disk", DomainScheme.Directory, directory, + new Dictionary { ["lazy"] = "true" })); + } + + [Fact] + public void SystemFolders_AreFullPaths() + { + string[] folders = + [ + SystemFolders.App, SystemFolders.Temp, SystemFolders.Home, SystemFolders.Desktop, SystemFolders.Documents, + SystemFolders.Downloads, SystemFolders.Pictures, SystemFolders.Music, SystemFolders.Videos, + SystemFolders.SavedGames, SystemFolders.Shared, SystemFolders.AppData.Roaming, SystemFolders.AppData.Local, + SystemFolders.AppData.LocalLow + ]; + + folders.Should().OnlyContain(folder => Path.IsPathFullyQualified(folder)); + if (OperatingSystem.IsWindows()) SystemFolders.AppData.LocalLow.Should().EndWith("LocalLow"); + } + + [Fact] + public void Folders_ArePathsOfDomains() + { + Folders.AppData.Roaming.Combine("saves/a.json").Should().Be(FilePath.Parse("user://saves/a.json")); + Folders.Assets.Combine("hero.png").Should().Be(FilePath.Parse("assets://hero.png")); + } + + [Theory] + [InlineData("..", "..")] + [InlineData("a/../..", "b\\..")] + [InlineData("C:", "/etc")] + public void Names_NeverLeadOutOfTheFolderOfTheUser(string company, string project) + { + var configuration = new RuntimeConfiguration { CompanyName = company, ProjectName = project }; + + foreach (DomainMount mount in EngineMounts.Of(configuration).Where(mount => mount.Name == "user")) + Path.GetFullPath(mount.Source) + .Should().StartWith(SystemFolders.AppData.Roaming + Path.DirectorySeparatorChar); + } + + [Fact] + public void Assets_FollowTheSetting() + { + var configuration = new RuntimeConfiguration(); + EngineMounts.Of(configuration).Select(mount => mount.Name).Should().Equal("app"); + + configuration.Settings[EngineMounts.AssetsSetting] = "Content"; + SourceOf(configuration, Folders.Assets).Should().Be(Path.Combine(SystemFolders.App, "Content")); + + configuration.Settings[EngineMounts.AssetsSetting] = _root; + SourceOf(configuration, Folders.Assets).Should().Be(_root); + } + + [Fact] + public void ALazyDirectory_IsCreatedByTheFirstWrite() + { + MountLazy(_root); + FilePath file = FilePath.Parse("disk://a/b.txt"); + + _files.Exists(file).Should().BeFalse(); + _files.Enumerate(FilePath.Root("disk")).Should().BeEmpty(); + Directory.Exists(_root).Should().BeFalse(); + + _files.WriteAllText(file, "text", true); + _files.ReadAllText(file).Should().Be("text"); + } + + [Fact] + public async Task Text_IsWrittenAndReadAsync() + { + MountLazy(_root); + FilePath file = FilePath.Parse("disk://a.txt"); + + await _files.WriteAllTextAsync(file, "привет", true); + (await _files.ReadAllTextAsync(file)).Should().Be("привет"); + } + + [Theory] + [InlineData("dir")] + [InlineData("mem")] + public async Task ACancelledAtomicWrite_LeavesTheFile(string scheme) + { + _files.Mount(new DomainMount("disk", new DomainScheme(scheme), _root)); + FilePath file = FilePath.Parse("disk://a.txt"); + await _files.WriteAllTextAsync(file, "old"); + + using var cancellation = new CancellationTokenSource(); + Func write = async () => + { + // ReSharper disable once MethodSupportsCancellation + await using Stream stream = await _files.OpenAsync(file, FileOpenOptions.Replace); + // ReSharper disable once MethodSupportsCancellation + await stream.WriteAsync(new byte[10]); + // ReSharper disable once AccessToDisposedClosure + await cancellation.CancelAsync(); + // ReSharper disable once AccessToDisposedClosure + await stream.WriteAsync(new byte[10], cancellation.Token); + }; + + await write.Should().ThrowAsync(); + // ReSharper disable once MethodSupportsCancellation + (await _files.ReadAllTextAsync(file)).Should().Be("old"); + if (scheme == "dir") Directory.GetFiles(_root).Should().HaveCount(1); + } + + [Fact] + public async Task AnOverlay_CopiesAFileUpOnce_FromManyThreads() + { + _files.Mount(new DomainMount("base", DomainScheme.Memory, "")); + _files.Mount(new DomainMount("mods", DomainScheme.Memory, "")); + await _files.WriteAllTextAsync(FilePath.Parse("base://a.txt"), "base"); + int copies = 0; + using IDisposable watch = _files.Watch(FilePath.Root("mods"), true, _ => Interlocked.Increment(ref copies)); + _files.Mount(new DomainMount("all", DomainScheme.Overlay, "mods,base", + new Dictionary { ["write"] = "mods" })); + + + Stream[] streams = await Task.WhenAll(Enumerable.Range(0, 16).Select(_ => Task.Run(async () => + await _files.OpenAsync(FilePath.Parse("all://a.txt"), + new FileOpenOptions(FileMode.Open, FileAccess.ReadWrite))))); + + + // Opened, not closed yet: the only change is the copy + copies.Should().Be(1); + foreach (Stream stream in streams) await stream.DisposeAsync(); + } + + [Fact] + public void MountAndDispose_FromManyThreads_LeaveNoDomain() + { + for (int round = 0; round < 50; round++) + { + var files = VirtualFileSystem.CreateDefault(); + Parallel.For(0, 16, i => + { + if (i == 8) + { + files.Dispose(); + return; + } + + try + { + files.Mount(new DomainMount($"d{i}", DomainScheme.Memory, "")); + } + catch (ObjectDisposedException) + { + // Too late to mount + } + }); + + files.Domains.Keys.Should().BeEmpty(); + } + } +}