diff --git a/Docs/index.md b/Docs/index.md index 5ca46d7..bca9296 100644 --- a/Docs/index.md +++ b/Docs/index.md @@ -2,7 +2,7 @@ File system of the engine -A `CoreModule` module of [StellarEngine](https://quantumdevteam.github.io/StellarEngine-Core/). Its site is https://quantumdevteam.github.io/Stellar.FileSystem/, built from the Markdown +A `CoreModule` module of [StellarEngine](https://quantumdevteam.github.io/StellarEngine-Mono/). Its site is https://quantumdevteam.github.io/Stellar.FileSystem/, built from the Markdown files of `Docs/` with DocFX; the whole engine, with every module, is on the site of the orchestra. ## Using it @@ -13,6 +13,29 @@ Add `Stellar.FileSystem` to `Dependencies` of your module or project descriptor, stellar modules sync ``` +```csharp +using var files = VirtualFileSystem.CreateDefault(); +files.Mount(new DomainMount("assets", DomainScheme.Directory, assetsDirectory)); +files.Mount(new DomainMount("mods", DomainScheme.Directory, modsDirectory)); +files.Mount(new DomainMount("game", DomainScheme.Overlay, "mods,assets")); + +var level = files.ReadAllText(FilePath.Parse("game://levels/1.json")); +``` + +The code names domains, never places of the machine: those are given once, when the runtime mounts the domains. + +## Drivers + +| Scheme | Source | What it can do | +|---|---|---| +| `dir` | A full path of a directory | Everything; `readonly=true` reads only. Links out of the directory are refused (`links=follow` allows them); atomic writes go beside the file as `*.stellar-tmp` | +| `asm` | The name of an assembly | Reads embedded resources at their logical names, without a copy; `prefix=` takes a part of them | +| `mem` | Not used | Everything, in memory: a write becomes the file when its stream closes | +| `overlay` | Domains, first wins: `mods,dlc,base` | Reads the first layer that has a file; `write=` sends writes there, copying a file of a lower layer up first | + +A driver of another scheme (an archive, a network, a world of a game) implements `IFileDriver` and is registered +with `AddDriver` (the catalog `Drivers`); the contracts are in `Stellar.Kernel.FileSystem`. + ## Working on it ```powershell diff --git a/Docs/toc.yml b/Docs/toc.yml index 77331f9..89c53bd 100644 --- a/Docs/toc.yml +++ b/Docs/toc.yml @@ -4,4 +4,4 @@ - name: README href: ../README.md - name: StellarEngine - href: https://quantumdevteam.github.io/StellarEngine-Core/ + href: https://quantumdevteam.github.io/StellarEngine-Mono/ diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..d8dbac9 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,133 @@ +# PolyForm Noncommercial License 1.0.0 + + + +Required Notice: Copyright (c) 2026 QuantumDevTeam (see NOTICE) + +## Acceptance + +In order to get any license under these terms, you must agree +to them as both strict obligations and conditions to all +your licenses. + +## Copyright License + +The licensor grants you a copyright license for the +software to do everything you might do with the software +that would otherwise infringe the licensor's copyright +in it for any permitted purpose. However, you may +only distribute the software according to [Distribution +License](#distribution-license) and make changes or new works +based on the software according to [Changes and New Works +License](#changes-and-new-works-license). + +## Distribution License + +The licensor grants you an additional copyright license +to distribute copies of the software. Your license +to distribute covers distributing the software with +changes and new works permitted by [Changes and New Works +License](#changes-and-new-works-license). + +## Notices + +You must ensure that anyone who gets a copy of any part of +the software from you also gets a copy of these terms or the +URL for them above, as well as copies of any plain-text lines +beginning with `Required Notice:` that the licensor provided +with the software. For example: + +> Required Notice: Copyright Yoyodyne, Inc. (http://example.com) + +## Changes and New Works License + +The licensor grants you an additional copyright license to +make changes and new works based on the software for any +permitted purpose. + +## Patent License + +The licensor grants you a patent license for the software that +covers patent claims the licensor can license, or becomes able +to license, that you would infringe by using the software. + +## Noncommercial Purposes + +Any noncommercial purpose is a permitted purpose. + +## Personal Uses + +Personal use for research, experiment, and testing for +the benefit of public knowledge, personal study, private +entertainment, hobby projects, amateur pursuits, or religious +observance, without any anticipated commercial application, +is use for a permitted purpose. + +## Noncommercial Organizations + +Use by any charitable organization, educational institution, +public research organization, public safety or health +organization, environmental protection organization, +or government institution is use for a permitted purpose +regardless of the source of funding or obligations resulting +from the funding. + +## Fair Use + +You may have "fair use" rights for the software under the +law. These terms do not limit them. + +## No Other Rights + +These terms do not allow you to sublicense or transfer any of +your licenses to anyone else, or prevent the licensor from +granting licenses to anyone else. These terms do not imply +any other licenses. + +## Patent Defense + +If you make any written claim that the software infringes or +contributes to infringement of any patent, your patent license +for the software granted under these terms ends immediately. If +your company makes such a claim, your patent license ends +immediately for work on behalf of your company. + +## Violations + +The first time you are notified in writing that you have +violated any of these terms, or done anything with the software +not covered by your licenses, your licenses can nonetheless +continue if you come into full compliance with these terms, +and take practical steps to correct past violations, within +32 days of receiving notice. Otherwise, all your licenses +end immediately. + +## No Liability + +***As far as the law allows, the software comes as is, without +any warranty or condition, and the licensor will not be liable +to you for any damages arising out of these terms or the use +or nature of the software, under any kind of legal claim.*** + +## Definitions + +The **licensor** is the individual or entity offering these +terms, and the **software** is the software the licensor makes +available under these terms. + +**You** refers to the individual or entity agreeing to these +terms. + +**Your company** is any legal entity, sole proprietorship, +or other kind of organization that you work for, plus all +organizations that have control over, are under the control of, +or are under common control with that organization. **Control** +means ownership of substantially all the assets of an entity, +or the power to direct its management and policies by vote, +contract, or otherwise. Control can be direct or indirect. + +**Your licenses** are all the licenses granted to you for the +software under these terms. + +**Use** means anything you do with the software requiring one +of your licenses. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000..644897c --- /dev/null +++ b/NOTICE @@ -0,0 +1,12 @@ +StellarEngine +Copyright (c) 2026 QuantumDevTeam + +QuantumDevTeam is the name under which Timur Shestakov acts personally. It is a brand and a +trade name, not a legal entity: the copyright in StellarEngine, and in every module and tool +published under this name, belongs to Timur Shestakov, who is the licensor of the license +below and the "Project Owner" of CLA.md. If a legal entity is established later, the rights +may be assigned to it as CLA.md describes, and this notice will name it. + +Licensed under the PolyForm Noncommercial License 1.0.0 +https://polyformproject.org/licenses/noncommercial/1.0.0 +See LICENSE.md and CLA.md. diff --git a/Stellar.FileSystem.stellar.module b/Stellar.FileSystem.stellar.module index 094af11..98e579d 100644 --- a/Stellar.FileSystem.stellar.module +++ b/Stellar.FileSystem.stellar.module @@ -1,7 +1,7 @@ { "$schema": "https://quantumdevteam.github.io/StellarEngine-Core/schemas/stellar.module.schema.json", "Id": "Stellar.FileSystem", - "Version": "0.8.0", + "Version": "0.9.0", "Level": "CoreModule", "Description": "File system of the engine", "Dependencies": [] diff --git a/src/Managed/Stellar.FileSystem/ContentTypeCatalog.cs b/src/Managed/Stellar.FileSystem/ContentTypeCatalog.cs new file mode 100644 index 0000000..56a56b4 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/ContentTypeCatalog.cs @@ -0,0 +1,92 @@ +using Stellar.Core.Data.Catalog; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem; + +/// +/// The content types of a file system, by extension; the extensions compare in any case. +/// +public sealed class ContentTypeCatalog() + : Catalog(StringComparer.OrdinalIgnoreCase), IContentTypeCatalog +{ + /// + /// Makes a catalog with the formats every engine reads: text, data, images, sounds, models, fonts, shaders. + /// + /// The catalog. + public static ContentTypeCatalog CreateDefault() + { + var catalog = new ContentTypeCatalog(); + + // text + foreach (var (extension, mediaType) in new[] + { + // application/* + (".json", "application/json"), (".xml", "application/xml"), (".yaml", "application/yaml"), + (".yml", "application/yaml"), (".toml", "application/toml"), + // plain text + (".txt", "text/plain"), (".ini", "text/plain"), (".cfg", "text/plain"), + (".md", "text/markdown"), (".csv", "text/csv"), + // models + (".gltf", "model/gltf+json"), (".obj", "model/obj"), + // shaders + (".shader", "text/x-shader"), + (".hlsl", "text/x-hlsl"), (".wgsl", "text/wgsl"), (".glsl", "text/x-glsl"), + // languages + (".lua", "text/x-lua"), (".cs", "text/x-csharp"), (".js", "text/javascript"), + (".html", "text/html"), (".css", "text/css"), + // images + (".svg", "image/svg+xml") + }) + catalog.Set(extension, new ContentType(mediaType, ContentKind.Text, "utf-8")); + + // binary + foreach (var (extension, mediaType) in new[] + { + // images + (".png", "image/png"), (".jpg", "image/jpeg"), (".jpeg", "image/jpeg"), (".bmp", "image/bmp"), + (".tga", "image/x-tga"), (".dds", "image/vnd-ms.dds"), (".ktx2", "image/ktx2"), + (".hdr", "image/vnd.radiance"), (".exr", "image/x-exr"), (".webp", "image/webp"), + // audio + (".wav", "audio/wav"), (".ogg", "audio/ogg"), (".mp3", "audio/mpeg"), (".flac", "audio/flac"), + // models + (".glb", "model/gltf-binary"), (".fbx", "model/x-fbx"), + // fonts + (".ttf", "font/ttf"), (".otf", "font/otf"), + // shaders + (".spv", "application/x-spirv"), + // other + (".bin", "application/octet-stream"), + (".zip", "application/zip"), + (".dll", "application/x-msdownload"), + }) + catalog.Set(extension, new ContentType(mediaType, ContentKind.Binary)); + + return catalog; + } + + /// + public ContentType Resolve(FilePath path) + { + var extension = path.Extension; + return extension.Length > 0 && TryGet(extension, out var contentType) + ? contentType + : ContentType.OctetStream; + } + + /// + protected override string NormalizeKey(string key) + { + ArgumentNullException.ThrowIfNull(key); + if (key.Length < 2 || key[0] != '.' || key.IndexOfAny(['/', '\\', ' ']) >= 0) + throw new ArgumentException($"'{key}' is not an extension: " + + $"expected a dot and a name, such as .png", nameof(key)); + return key; + } + + /// + protected override void Validate(string key, ContentType value) + { + if (value.IsUnknown) + throw new ArgumentException($"The unknown content type cannot be set for '{key}'", nameof(value)); + } +} diff --git a/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs b/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs new file mode 100644 index 0000000..31476f5 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Domains/DomainBase.cs @@ -0,0 +1,316 @@ +using Stellar.Core.Quantization; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Domains; + +/// +/// The base of the domains: the checks every domain makes, before the work of the driver. +/// +/// +/// Each public member checks that the domain is not disposed, that it has the capability, and brings the +/// path to its one form (free for a path that is in it already), then calls its Core method. A driver +/// overrides the Core methods of what it can do and declares it in the capabilities. +/// +public abstract class DomainBase + : Quant, IDomain +{ + private static readonly IReadOnlyDictionary NoOptions = new Dictionary(); + private volatile bool _disposed; + + /// + public string Name { get; } + + /// + public DomainScheme Scheme { get; } + + /// + public string Source { get; } + + /// + public DomainCapabilities Capabilities { get; } + + /// + /// Gets the settings of the driver this domain was mounted with. + /// + protected IReadOnlyDictionary Options { get; } + + /// + /// Gets the file system the domain is mounted in. + /// + protected IFileSystem FileSystem { get; } + + /// + /// Gets whether the domain is disposed. + /// + protected bool IsDisposed => _disposed; + + /// + /// Makes the domain. + /// + /// What was mounted. + /// The file system it is mounted in. + /// What the domain can do. + protected DomainBase(DomainMount mount, IFileSystem fileSystem, DomainCapabilities capabilities) + : base(new MetaQuant()) + { + ArgumentNullException.ThrowIfNull(fileSystem); + + Name = FileSystemNames.NormalizeName(mount.Name, nameof(mount)); + Scheme = mount.Scheme; + Source = mount.Source ?? string.Empty; + Options = mount.Options ?? NoOptions; + FileSystem = fileSystem; + Capabilities = capabilities; + } + + /// + /// Makes the exception for what the domain cannot do. + /// + protected NotSupportedException Unsupported(string what) => + new($"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()); + + /// + /// Makes the exception for a directory that is not there. + /// + protected DirectoryNotFoundException DirectoryNotFound(string path) => + new($"No directory '{PathOf(path)}'"); + + /// + /// Throws if the domain is disposed. + /// + protected void ThrowIfDisposed() => ObjectDisposedException.ThrowIf(_disposed, this); + + private void Require(DomainCapabilities capability, string what) + { + if ((Capabilities & capability) != capability) throw Unsupported(what); + } + + private void RequireFor(FileOpenOptions options) + { + if (options.Writes) Require(DomainCapabilities.Write, "write"); + else Require(DomainCapabilities.Read, "read"); + + if ((options.Flags & FileOpenFlags.Atomic) == 0) return; + + Require(DomainCapabilities.AtomicWrite, "replace files atomically"); + if (options.Mode is not (FileMode.Create or FileMode.CreateNew) || options.Access != FileAccess.Write) + throw new ArgumentException( + "An atomic write creates the file anew: FileMode.Create or CreateNew, FileAccess.Write", + nameof(options)); + } + + /// Whether a file or a directory exists. + protected abstract bool ExistsCore(string path); + + /// What is known of a file or a directory. + protected abstract bool TryGetEntryCore(string path, out FileEntry entry); + + /// The entries of a directory. + 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)); + + /// Opens a file for reads 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) + { + data = default; + return false; + } + + /// Creates a directory. + 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"); + + /// 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"); + + /// Watches a directory. + protected virtual IDisposable WatchCore(string directory, bool recursive, Action handler) => + throw Unsupported("watch"); + + /// + /// Releases what the domain holds: called once. + /// + protected virtual void DisposeCore() + { + } + + /// + /// Reads a yes-or-no setting of the mount. + /// + /// The settings. + /// The name of the setting. + /// The value when the setting is absent. + /// The value. + protected static bool GetFlag(IReadOnlyDictionary? options, string key, bool fallback) + { + if (options is null + || !options.TryGetValue(key, out var text)) + return fallback; + return bool.TryParse(text, out var value) + ? value + : throw new ArgumentException($"The setting '{key}' is '{text}': expected true or false"); + } + + /// + /// Gets the full path of a path of this domain. + /// + /// The path inside the domain. + /// The full path. + protected FilePath PathOf(string path) => FilePath.Create(Name, path); + + /// + /// Makes the entry of a file, its content type from the file system. + /// + protected FileEntry FileEntryOf(string path, long length, + DateTime? creationTimeUtc, DateTime? lastWriteTimeUtc, + long revision) + { + var full = PathOf(path); + return new FileEntry(full, FileEntryKind.File, length, + creationTimeUtc, lastWriteTimeUtc, + FileSystem.ContentTypes.Resolve(full), revision); + } + + /// + /// Makes the entry of a directory. + /// + protected FileEntry DirectoryEntryOf(string path, + DateTime? creationTimeUtc = null, DateTime? lastWriteTimeUtc = null) + { + var full = PathOf(path); + return new FileEntry(full, FileEntryKind.Directory, 0, + creationTimeUtc, lastWriteTimeUtc, + default, 0); + } + + /// + public bool Exists(string path) + { + ThrowIfDisposed(); + return ExistsCore(FileSystemNames.NormalizePath(path)); + } + + /// + public bool TryGetEntry(string path, out FileEntry entry) + { + ThrowIfDisposed(); + return TryGetEntryCore(FileSystemNames.NormalizePath(path), out entry); + } + + /// + public IEnumerable Enumerate(string directory, string pattern = "*", bool recursive = false) + { + ThrowIfDisposed(); + Require(DomainCapabilities.Enumerate, "list files"); + ArgumentNullException.ThrowIfNull(pattern); + return EnumerateCore(FileSystemNames.NormalizePath(directory, nameof(directory)), pattern, recursive); + } + + /// + public Stream Open(string path, FileOpenOptions options) + { + ThrowIfDisposed(); + RequireFor(options); + return OpenCore(FileSystemNames.NormalizePath(path), options); + } + + /// + public ValueTask OpenAsync(string path, FileOpenOptions options, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + ThrowIfDisposed(); + RequireFor(options); + return OpenAsyncCore(FileSystemNames.NormalizePath(path), options, cancellationToken); + } + + /// + public IRandomAccessFile OpenRandomAccess(string path) + { + ThrowIfDisposed(); + Require(DomainCapabilities.RandomAccess, "read at offsets"); + return OpenRandomAccessCore(FileSystemNames.NormalizePath(path)); + } + + /// + public bool TryGetMemory(string path, out ReadOnlyMemory data) + { + ThrowIfDisposed(); + data = default; + return (Capabilities & DomainCapabilities.Memory) != 0 + && TryGetMemoryCore(FileSystemNames.NormalizePath(path), out data); + } + + /// + public void CreateDirectory(string path) + { + ThrowIfDisposed(); + Require(DomainCapabilities.Write, "create directories"); + CreateDirectoryCore(FileSystemNames.NormalizePath(path)); + } + + /// + public bool Delete(string path, bool recursive = false) + { + ThrowIfDisposed(); + Require(DomainCapabilities.Write, "delete"); + var normalized = FileSystemNames.NormalizePath(path); + if (normalized.Length == 0) throw new IOException($"The root of the domain '{Name}' cannot be deleted"); + return DeleteCore(normalized, recursive); + } + + /// + 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)); + if (from.Length == 0 || to.Length == 0) + throw new IOException($"The root of the domain '{Name}' cannot be moved"); + if (from == to) return; + if (to.StartsWith(from + "/", StringComparison.Ordinal)) + throw new IOException($"'{PathOf(from)}' cannot move into itself"); + MoveCore(from, to, overwrite); + } + + /// + public IDisposable Watch(string directory, bool recursive, Action handler) + { + ThrowIfDisposed(); + Require(DomainCapabilities.Watch, "watch"); + ArgumentNullException.ThrowIfNull(handler); + return WatchCore(FileSystemNames.NormalizePath(directory, nameof(directory)), recursive, handler); + } + + /// + public void Dispose() + { + if (_disposed) return; + _disposed = true; + DisposeCore(); + GC.SuppressFinalize(this); + } + + /// + public override string ToString() => $"{Name}:// ({Scheme} {Source})"; +} diff --git a/src/Managed/Stellar.FileSystem/Domains/DomainPaths.cs b/src/Managed/Stellar.FileSystem/Domains/DomainPaths.cs new file mode 100644 index 0000000..be7c599 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Domains/DomainPaths.cs @@ -0,0 +1,59 @@ +using System.IO.Enumeration; + +namespace Stellar.FileSystem.Domains; + +/// +/// Operations on paths inside a domain, in the one form of . +/// +public static class DomainPaths +{ + /// + /// Joins a directory and a name. + /// + public static string Join(string directory, string name) => directory.Length == 0 ? name : directory + "/" + name; + + /// + /// Gets the last segment of a path. + /// + public static string NameOf(string path) => path.Substring(path.LastIndexOf('/') + 1); + + /// + /// Gets the directory of a path; an empty string for the root and what lies in it. + /// + public static string ParentOf(string path) + { + var slash = path.LastIndexOf('/'); + return slash < 0 ? string.Empty : path.Substring(0, slash); + } + + /// + /// Gets the directories above a path, nearest first, without the root. + /// + public static IEnumerable AncestorsOf(string path) + { + for (var slash = path.LastIndexOf('/'); slash > 0; slash = path.LastIndexOf('/', slash - 1)) + yield return path.Substring(0, slash); + } + + /// + /// Gets whether a path lies in a directory: right in it, or at any depth when recursive. + /// + public static bool IsIn(string path, string directory, bool recursive) + { + if (path.Length == 0 || path == directory) return false; + + int start; + if (directory.Length == 0) start = 0; + else if (path.Length > directory.Length && path[directory.Length] == '/' && path.StartsWith(directory, StringComparison.Ordinal)) + start = directory.Length + 1; + else return false; + + return recursive || path.IndexOf('/', start) < 0; + } + + /// + /// Gets whether a name matches a pattern of * and ?. + /// + public static bool Matches(string pattern, string name, bool ignoreCase = false) => + pattern == "*" || FileSystemName.MatchesSimpleExpression(pattern, name, ignoreCase); +} diff --git a/src/Managed/Stellar.FileSystem/Domains/MemoryRandomAccessFile.cs b/src/Managed/Stellar.FileSystem/Domains/MemoryRandomAccessFile.cs new file mode 100644 index 0000000..cb81740 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Domains/MemoryRandomAccessFile.cs @@ -0,0 +1,41 @@ +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Domains; + +/// +/// Reads at offsets of bytes held in memory. +/// +/// The path of the file. +/// Its bytes. +public sealed class MemoryRandomAccessFile(FilePath path, ReadOnlyMemory data) + : IRandomAccessFile +{ + /// + public FilePath Path { get; } = path; + + /// + public long Length => data.Length; + + /// + public int Read(long offset, Span buffer) + { + ArgumentOutOfRangeException.ThrowIfNegative(offset); + if (offset >= data.Length) return 0; + + var count = (int)Math.Min(buffer.Length, data.Length - offset); + data.Span.Slice((int)offset, count).CopyTo(buffer); + return count; + } + + /// + public ValueTask ReadAsync(long offset, Memory buffer, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + return new ValueTask(Read(offset, buffer.Span)); + } + + /// + public void Dispose() + { + } +} diff --git a/src/Managed/Stellar.FileSystem/Drivers/AssemblyDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/AssemblyDriver.cs new file mode 100644 index 0000000..a848042 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Drivers/AssemblyDriver.cs @@ -0,0 +1,185 @@ +using System.Buffers; +using System.Collections.Concurrent; +using System.Reflection; +using Stellar.Core.Quantization; +using Stellar.FileSystem.Domains; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Drivers; + +/// +/// Mounts the resources embedded in an assembly (asm), read-only. The source is the name of the assembly. +/// +/// +/// A resource is a file at its logical name. A name with '/' or '\' is a path, so a project embeds a tree with +/// <EmbeddedResource Include="Content\**" LogicalName="%(RecursiveDir)%(Filename)%(Extension)"/>; any +/// other name is a file at the root, dots and all. +/// The option prefix takes only the resources whose names start with it, and cuts it off. +/// The bytes are read where the assembly lies in memory: gives them with no +/// copy. +/// +public sealed class AssemblyDriver() + : Quant(new MetaQuant()), IFileDriver +{ + /// + public DomainScheme Scheme => DomainScheme.Assembly; + + /// + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new AssemblyDomain(mount, fileSystem); +} + +internal sealed class AssemblyDomain + : DomainBase +{ + private readonly Assembly _assembly; + + private readonly Dictionary _resources = new(StringComparer.Ordinal); + private readonly HashSet _directories = new(StringComparer.Ordinal) { string.Empty }; + private readonly ConcurrentDictionary> _memory = new(StringComparer.Ordinal); + private readonly long _revision; + private readonly DateTime? _lastWriteTimeUtc; + + private static Assembly Load(string source) + { + if (string.IsNullOrWhiteSpace(source)) + throw new ArgumentException("The source of an asm domain is the name of an assembly"); + + foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) + if (string.Equals(assembly.GetName().Name, source, StringComparison.OrdinalIgnoreCase)) + return assembly; + + return Assembly.Load(new AssemblyName(source)); + } + + public AssemblyDomain(DomainMount mount, IFileSystem fileSystem) + : base(mount, fileSystem, + DomainCapabilities.Read + | DomainCapabilities.Enumerate + | DomainCapabilities.RandomAccess + | DomainCapabilities.Memory) + { + _assembly = Load(mount.Source); + string? prefix = null; + mount.Options?.TryGetValue("prefix", out prefix); + + foreach (var name in _assembly.GetManifestResourceNames()) + { + var logical = name; + if (prefix is not null) + { + if (!name.StartsWith(prefix, StringComparison.Ordinal)) continue; + logical = name.Substring(prefix.Length); + } + + // A resource whose name cannot be a path is not a file of the domain + if (!FileSystemNames.TryNormalizePath(logical, out var path) || path.Length == 0) continue; + if (!_resources.TryAdd(path, name)) continue; + foreach (var ancestor in DomainPaths.AncestorsOf(path)) + _directories.Add(ancestor); + } + + // The same build of the assembly, the same bytes + _revision = BitConverter.ToInt64(_assembly.ManifestModule.ModuleVersionId.ToByteArray(), 0); + _lastWriteTimeUtc = _assembly.Location.Length > 0 ? File.GetLastWriteTimeUtc(_assembly.Location) : null; + } + + private Stream OpenResource(string path) + { + if (!_resources.TryGetValue(path, out var name)) throw NotFound(path); + return _assembly.GetManifestResourceStream(name) ?? throw NotFound(path); + } + + private long LengthOf(string path) + { + using var stream = OpenResource(path); + return stream.CanSeek ? stream.Length : -1; + } + + private sealed unsafe class UnmanagedMemory(byte* pointer, int length) + : MemoryManager + { + public override Span GetSpan() => new(pointer, length); + + public override MemoryHandle Pin(int elementIndex = 0) => new(pointer + elementIndex); + + public override void Unpin() + { + } + + protected override void Dispose(bool disposing) + { + } + } + + protected override bool ExistsCore(string path) => + _resources.ContainsKey(path) || _directories.Contains(path); + + protected override bool TryGetEntryCore(string path, out FileEntry entry) + { + if (_resources.ContainsKey(path)) + { + entry = FileEntryOf(path, LengthOf(path), _lastWriteTimeUtc, _lastWriteTimeUtc, _revision); + return true; + } + + entry = _directories.Contains(path) + ? DirectoryEntryOf(path, _lastWriteTimeUtc, _lastWriteTimeUtc) + : default; + + return !entry.Path.IsEmpty; + } + + protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) + { + if (!_directories.Contains(directory)) + throw DirectoryNotFound(directory); + + var entries = new List(); + foreach (var path in _directories) + if (DomainPaths.IsIn(path, directory, recursive) && DomainPaths.Matches(pattern, DomainPaths.NameOf(path))) + entries.Add(DirectoryEntryOf(path, _lastWriteTimeUtc, _lastWriteTimeUtc)); + + foreach (var path in _resources.Keys) + if (DomainPaths.IsIn(path, directory, recursive) && DomainPaths.Matches(pattern, DomainPaths.NameOf(path))) + entries.Add(FileEntryOf(path, LengthOf(path), _lastWriteTimeUtc, _lastWriteTimeUtc, _revision)); + + entries.Sort((left, right) => left.Path.CompareTo(right.Path)); + return entries; + } + + protected override Stream OpenCore(string path, FileOpenOptions options) + { + if (options.Mode is not (FileMode.Open or FileMode.OpenOrCreate)) + throw Unsupported($"open with {options.Mode}"); + return OpenResource(path); + } + + protected override bool TryGetMemoryCore(string path, out ReadOnlyMemory data) + { + if (_memory.TryGetValue(path, out data)) return true; + if (!_resources.ContainsKey(path)) return false; + + using var stream = OpenResource(path); + if (stream is not UnmanagedMemoryStream unmanaged) return false; + + // The resource lies in the image of the assembly, which lives as long as the domain holds it + unsafe + { + data = new UnmanagedMemory(unmanaged.PositionPointer, checked((int)unmanaged.Length)).Memory; + } + + data = _memory.GetOrAdd(path, data); + return true; + } + + protected override IRandomAccessFile OpenRandomAccessCore(string path) + { + if (TryGetMemoryCore(path, out var data)) return new MemoryRandomAccessFile(PathOf(path), data); + + // A dynamic assembly: its resources are streams only + using var stream = OpenResource(path); + var copy = new MemoryStream(); + stream.CopyTo(copy); + return new MemoryRandomAccessFile(PathOf(path), copy.ToArray()); + } +} diff --git a/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs new file mode 100644 index 0000000..6d1498a --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Drivers/DirectoryDriver.cs @@ -0,0 +1,427 @@ +using System.IO.Enumeration; +using Microsoft.Win32.SafeHandles; +using Stellar.Core.Quantization; +using Stellar.FileSystem.Domains; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Drivers; + +/// +/// Mounts a directory of the machine (dir). The source is its full path, which the runtime resolves from +/// $(StellarRoot), the project or the folders of the user; a relative one is refused. +/// +/// +/// Options: +/// +/// readonly=true: no writes. A missing directory is then an error; otherwise it is created. +/// 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. +/// +public sealed class DirectoryDriver() + : Quant(new MetaQuant()), IFileDriver +{ + /// + public DomainScheme Scheme => DomainScheme.Directory; + + /// + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new DirectoryDomain(mount, fileSystem); +} + +/// +/// Writes beside a file and puts the result in its place when closed: the file is the old one or the new one, +/// never a part of the new one. +/// +internal sealed class AtomicFileStream + : FileStream +{ + private readonly string _target; + private readonly string _temporary; + private readonly bool _overwrite; + private int _committed; + + public AtomicFileStream(string target, bool overwrite, FileOptions options) + : this(target, TemporaryOf(target), overwrite, options) + { + } + + private AtomicFileStream(string target, string temporary, bool overwrite, FileOptions options) + : base(temporary, + new FileStreamOptions + { Mode = FileMode.CreateNew, Access = FileAccess.Write, Share = FileShare.None, Options = options }) + { + _target = target; + _temporary = temporary; + _overwrite = overwrite; + } + + private static string TemporaryOf(string target) => + Path.Combine(Path.GetDirectoryName(target)!, + $".{Path.GetFileName(target)}.{Guid.NewGuid():N}{DirectoryDomain.TemporarySuffix}"); + + 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); + base.Dispose(disposing); + if (commit) Commit(); + } + + public override async ValueTask DisposeAsync() + { + if (Volatile.Read(ref _committed) != 0 || !CanWrite) + { + await base.DisposeAsync().ConfigureAwait(false); + return; + } + + await FlushAsync().ConfigureAwait(false); + Flush(flushToDisk: true); + await base.DisposeAsync().ConfigureAwait(false); + Commit(); + } + + private void Commit() + { + if (Interlocked.Exchange(ref _committed, 1) != 0) return; + + try + { + File.Move(_temporary, _target, _overwrite); + } + catch + { + File.Delete(_temporary); + throw; + } + } +} + +internal sealed class DirectoryDomain + : DomainBase +{ + internal const string TemporarySuffix = ".stellar-tmp"; + + private static readonly bool IgnoreCase = OperatingSystem.IsWindows() || OperatingSystem.IsMacOS(); + + private static readonly StringComparison PathComparison = IgnoreCase + ? StringComparison.OrdinalIgnoreCase + : StringComparison.Ordinal; + + private static readonly char Separator = Path.DirectorySeparatorChar; + + // With a separator at the end, so "C:\Game2" is not inside "C:\Game" + private readonly string _root; + private readonly bool _followLinks; + + private static DomainCapabilities CapabilitiesOf(DomainMount mount) + { + var capabilities = DomainCapabilities.Read | DomainCapabilities.Enumerate | DomainCapabilities.Watch | + DomainCapabilities.RandomAccess; + return GetFlag(mount.Options, "readonly", false) + ? capabilities + : capabilities | DomainCapabilities.Write | DomainCapabilities.AtomicWrite; + } + + public DirectoryDomain(DomainMount mount, IFileSystem fileSystem) + : base(mount, fileSystem, CapabilitiesOf(mount)) + { + if (string.IsNullOrWhiteSpace(mount.Source) + || !Path.IsPathFullyQualified(mount.Source)) + 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); + _root = full + Separator; + _followLinks = Options.TryGetValue("links", out var links) && links == "follow"; + + if (!Directory.Exists(full)) + { + if ((Capabilities & DomainCapabilities.Write) == 0) + throw new DirectoryNotFoundException($"No directory '{full}' for the domain '{Name}'"); + Directory.CreateDirectory(full); + } + } + + // The path of the machine; refuses a link on the way that leads out of the root + private string Resolve(string path) + { + if (path.Length == 0) return _root; + + var full = _root + (Separator == '/' ? path : path.Replace('/', Separator)); + if (_followLinks) return full; + + for (var index = _root.Length;; index++) + { + index = full.IndexOf(Separator, index); + var current = index < 0 ? full : full.Substring(0, index); + + var info = new FileInfo(current); + var attributes = (int)info.Attributes; + if (attributes == -1) break; // Nothing there, nor below + if ((info.Attributes & FileAttributes.ReparsePoint) != 0 && info.LinkTarget is not null + && !IsInside( + info.ResolveLinkTarget(true)?.FullName)) + throw new UnauthorizedAccessException( + $"'{PathOf(path)}' leads out of the domain '{Name}' through a link"); + + if (index < 0) break; + } + + return full; + } + + 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); + return FileEntryOf(path, file.Length, file.CreationTimeUtc, file.LastWriteTimeUtc, revision); + } + + // The path inside the domain of a path of the machine; null for what cannot be one + private string? RelativeOf(string full) + { + 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); + 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 + ? relative + : null; + } + + private bool IsInside(string? full) => + full is not null && (full + Separator).StartsWith(_root, PathComparison); + + private Stream OpenFile(string path, FileOpenOptions options, bool asynchronous) + { + var full = Resolve(path); + if (Directory.Exists(full)) throw new UnauthorizedAccessException($"'{PathOf(path)}' is a directory"); + + var fileOptions = asynchronous ? FileOptions.Asynchronous : FileOptions.None; + if ((options.Flags & FileOpenFlags.Sequential) != 0) fileOptions |= FileOptions.SequentialScan; + if ((options.Flags & FileOpenFlags.RandomAccess) != 0) fileOptions |= FileOptions.RandomAccess; + + if (!options.Writes) + { + if (!File.Exists(full)) throw NotFound(path); + return new FileStream(full, new FileStreamOptions + { + Mode = options.Mode, Access = options.Access, Share = FileShare.ReadWrite | FileShare.Delete, + Options = fileOptions + }); + } + + Directory.CreateDirectory(Path.GetDirectoryName(full)!); + + if ((options.Flags & FileOpenFlags.Atomic) != 0) + { + if (options.Mode == FileMode.CreateNew && File.Exists(full)) + throw new IOException($"'{PathOf(path)}' exists already"); + return new AtomicFileStream(full, options.Mode == FileMode.Create, fileOptions); + } + + return new FileStream(full, new FileStreamOptions + { + Mode = options.Mode, Access = options.Access, Share = FileShare.Read, Options = fileOptions + }); + } + + private sealed class RandomAccessFile(FilePath path, SafeFileHandle handle) + : IRandomAccessFile + { + public FilePath Path { get; } = path; + + public long Length => RandomAccess.GetLength(handle); + + public int Read(long offset, Span buffer) => RandomAccess.Read(handle, buffer, offset); + + public ValueTask ReadAsync(long offset, Memory buffer, + CancellationToken cancellationToken = default) => + RandomAccess.ReadAsync(handle, buffer, offset, cancellationToken); + + public void Dispose() => handle.Dispose(); + } + + protected override bool ExistsCore(string path) + { + try + { + var full = Resolve(path); + return File.Exists(full) || Directory.Exists(full); + } + catch (UnauthorizedAccessException) + { + return false; + } + } + + protected override bool TryGetEntryCore(string path, out FileEntry entry) + { + entry = default; + string full; + try + { + full = Resolve(path); + } + catch (UnauthorizedAccessException) + { + return false; + } + + var file = new FileInfo(full); + if (file.Exists) + { + entry = EntryOf(path, file); + return true; + } + + var directory = new DirectoryInfo(full); + if (!directory.Exists) return false; + + entry = DirectoryEntryOf(path, directory.CreationTimeUtc, directory.LastWriteTimeUtc); + return true; + } + + protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) + { + var full = Resolve(directory); + if (!Directory.Exists(full)) throw DirectoryNotFound(directory); + + var options = new EnumerationOptions + { + RecurseSubdirectories = recursive, + IgnoreInaccessible = true, + AttributesToSkip = 0, + ReturnSpecialDirectories = false + }; + + var entries = new FileSystemEnumerable(full, + (ref FileSystemEntry entry) => entry.ToFileSystemInfo(), options) + { + ShouldIncludePredicate = (ref FileSystemEntry entry) => + !entry.FileName.EndsWith(TemporarySuffix, StringComparison.Ordinal) + && DomainPaths.Matches(pattern, entry.FileName.ToString(), IgnoreCase), + // Never through a link into another place + ShouldRecursePredicate = (ref FileSystemEntry entry) => + _followLinks || (entry.Attributes & FileAttributes.ReparsePoint) == 0 + }; + + return Select(entries); + + IEnumerable Select(IEnumerable infos) + { + foreach (var info in infos) + { + if (RelativeOf(info.FullName) is not { } path) continue; + if (!_followLinks && info.LinkTarget is not null && + !IsInside(info.ResolveLinkTarget(true)?.FullName)) continue; + + yield return info is FileInfo file + ? EntryOf(path, file) + : DirectoryEntryOf(path, info.CreationTimeUtc, info.LastWriteTimeUtc); + } + } + } + + protected override Stream OpenCore(string path, FileOpenOptions options) => + OpenFile(path, options, asynchronous: false); + + protected override ValueTask OpenAsyncCore(string path, FileOpenOptions options, + CancellationToken cancellationToken) => + new(OpenFile(path, options, asynchronous: true)); + + protected override IRandomAccessFile OpenRandomAccessCore(string path) + { + var full = Resolve(path); + if (!File.Exists(full)) throw NotFound(path); + + var 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 bool DeleteCore(string path, bool recursive) + { + var full = Resolve(path); + if (File.Exists(full)) + { + File.Delete(full); + return true; + } + + if (!Directory.Exists(full)) return false; + + // A linked directory goes as a link: Directory.Delete does not walk into it + Directory.Delete(full, recursive); + return true; + } + + protected override void MoveCore(string source, string destination, bool overwrite) + { + var from = Resolve(source); + var to = Resolve(destination); + Directory.CreateDirectory(Path.GetDirectoryName(to)!); + + if (File.Exists(from)) File.Move(from, to, overwrite); + else if (Directory.Exists(from)) Directory.Move(from, to); + else throw NotFound(source); + } + + protected override IDisposable WatchCore(string directory, bool recursive, Action handler) + { + var full = Resolve(directory); + if (!Directory.Exists(full)) throw DirectoryNotFound(directory); + + var watcher = new FileSystemWatcher(full) + { + IncludeSubdirectories = recursive, + NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite | + NotifyFilters.Size | NotifyFilters.CreationTime, + InternalBufferSize = 64 * 1024 + }; + + watcher.Created += (_, e) => Report(FileChangeKind.Created, e.FullPath); + watcher.Deleted += (_, e) => Report(FileChangeKind.Deleted, e.FullPath); + watcher.Changed += (_, e) => + { + // A directory changes when what it holds changes: that is reported on its own + if (!Directory.Exists(e.FullPath)) Report(FileChangeKind.Changed, e.FullPath); + }; + watcher.Renamed += (_, e) => + { + var path = RelativeOf(e.FullPath); + if (path is null) return; + + // The end of an atomic write: the file got new content + if (e.OldFullPath.EndsWith(TemporarySuffix, StringComparison.Ordinal)) + { + handler(new FileChange(FileChangeKind.Changed, PathOf(path))); + return; + } + + var old = RelativeOf(e.OldFullPath); + handler(old is null + ? new FileChange(FileChangeKind.Created, PathOf(path)) + : new FileChange(FileChangeKind.Renamed, PathOf(path), PathOf(old))); + }; + watcher.Error += (_, _) => handler(new FileChange(FileChangeKind.Invalidated, PathOf(directory))); + watcher.EnableRaisingEvents = true; + return watcher; + + void Report(FileChangeKind kind, string fullPath) + { + if (RelativeOf(fullPath) is { } path) handler(new FileChange(kind, PathOf(path))); + } + } +} diff --git a/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs new file mode 100644 index 0000000..04da96e --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Drivers/MemoryDriver.cs @@ -0,0 +1,326 @@ +using Stellar.Core.Quantization; +using Stellar.FileSystem.Domains; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Drivers; + +/// +/// Mounts domains held in memory (mem): tests, generated data, scratch space. The source is not used. +/// +public sealed class MemoryDriver() + : Quant(new MetaQuant()), IFileDriver +{ + /// + public DomainScheme Scheme => DomainScheme.Memory; + + /// + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new MemoryDomain(mount, fileSystem); +} + +/// +/// Files in memory. A write replaces the bytes of a file when its stream is closed, so readers and +/// never see a half-written file, and the memory they hold never changes. +/// +public sealed class MemoryDomain + : DomainBase +{ + private sealed record MemoryFile(byte[] Data, DateTime CreationTimeUtc, DateTime LastWriteTimeUtc, long Revision); + + private sealed record Watcher(string Directory, bool Recursive, Action Handler); + + private readonly Lock _sync = new(); + + private readonly Dictionary _files = new(StringComparer.Ordinal); + private readonly HashSet _directories = new(StringComparer.Ordinal) { string.Empty }; + private volatile Watcher[] _watchers = []; + private long _revision; + + /// + /// Makes the domain, empty. + /// + public MemoryDomain(DomainMount mount, IFileSystem fileSystem) + : base(mount, fileSystem, + DomainCapabilities.Read + | DomainCapabilities.Write + | DomainCapabilities.Enumerate + | DomainCapabilities.Watch + | DomainCapabilities.RandomAccess + | DomainCapabilities.Memory + | DomainCapabilities.AtomicWrite) + { + } + + // Under the lock. A file where a directory must be is an error, as on a disk + 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)) + { + if (_files.ContainsKey(ancestor)) throw new IOException($"'{PathOf(ancestor)}' is a file"); + if (!_directories.Add(ancestor)) break; + } + + _directories.Add(path); + return true; + } + + private void Notify(FileChange change) + { + // Out of the lock: a handler may call the domain + foreach (var 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) + { + FileChangeKind kind; + lock (_sync) + { + if (IsDisposed) return; + if (_directories.Contains(path)) + throw new UnauthorizedAccessException($"'{PathOf(path)}' became a directory"); + + var now = DateTime.UtcNow; + var existed = _files.TryGetValue(path, out var old); + AddDirectories(DomainPaths.ParentOf(path)); + _files[path] = new MemoryFile(data, old?.CreationTimeUtc ?? now, now, ++_revision); + kind = existed ? FileChangeKind.Changed : FileChangeKind.Created; + } + + Notify(new FileChange(kind, PathOf(path))); + } + + private sealed class Unwatch(MemoryDomain domain, Watcher watcher) + : IDisposable + { + public void Dispose() + { + lock (domain._sync) domain._watchers = domain._watchers.Where(w => !ReferenceEquals(w, watcher)).ToArray(); + } + } + + // The new bytes become the file when the stream closes, at once + private sealed class CommitStream + : MemoryStream + { + private readonly MemoryDomain _domain; + private readonly string _path; + private bool _committed; + + public CommitStream(MemoryDomain domain, string path, byte[] initial, bool append) + { + _domain = domain; + _path = path; + Write(initial); + Position = append ? Length : 0; + } + + protected override void Dispose(bool disposing) + { + if (disposing && !_committed) + { + _committed = true; + _domain.Commit(_path, ToArray()); + } + + base.Dispose(disposing); + } + } + + /// + protected override bool ExistsCore(string path) + { + lock (_sync) return _files.ContainsKey(path) || _directories.Contains(path); + } + + /// + protected override bool TryGetEntryCore(string path, out FileEntry entry) + { + lock (_sync) + { + if (_files.TryGetValue(path, out var file)) + { + entry = FileEntryOf(path, file.Data.Length, file.CreationTimeUtc, file.LastWriteTimeUtc, file.Revision); + return true; + } + + entry = _directories.Contains(path) ? DirectoryEntryOf(path) : default; + return !entry.Path.IsEmpty; + } + } + + /// + protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) + { + var entries = new List(); + lock (_sync) + { + if (!_directories.Contains(directory)) throw DirectoryNotFound(directory); + + foreach (var 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) + if (DomainPaths.IsIn(path, directory, recursive) && + DomainPaths.Matches(pattern, DomainPaths.NameOf(path))) + entries.Add(FileEntryOf(path, file.Data.Length, file.CreationTimeUtc, file.LastWriteTimeUtc, + file.Revision)); + } + + entries.Sort((left, right) => left.Path.CompareTo(right.Path)); + return entries; + } + + /// + protected override Stream OpenCore(string path, FileOpenOptions options) + { + MemoryFile? file; + lock (_sync) + { + if (_directories.Contains(path)) + throw new UnauthorizedAccessException($"'{PathOf(path)}' is a directory"); + _files.TryGetValue(path, out file); + } + + switch (options.Mode) + { + case FileMode.Open or FileMode.Truncate when file is null: + throw NotFound(path); + case FileMode.CreateNew when file is not null: + throw new IOException($"'{PathOf(path)}' exists already"); + } + + if (!options.Writes) + return new MemoryStream(file!.Data, 0, file.Data.Length, writable: false, publiclyVisible: true); + + var 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); + } + + /// + protected override bool TryGetMemoryCore(string path, out ReadOnlyMemory data) + { + lock (_sync) + { + var found = _files.TryGetValue(path, out var file); + data = found ? file!.Data : null; + return found; + } + } + + /// + protected override IRandomAccessFile OpenRandomAccessCore(string path) => + TryGetMemoryCore(path, out var data) + ? new MemoryRandomAccessFile(PathOf(path), data) + : throw NotFound(path); + + /// + protected override void CreateDirectoryCore(string path) + { + bool created; + lock (_sync) created = AddDirectories(path); + if (created) Notify(new FileChange(FileChangeKind.Created, PathOf(path))); + } + + /// + protected override bool DeleteCore(string path, bool recursive) + { + lock (_sync) + { + if (!_files.Remove(path)) + { + if (!_directories.Contains(path)) return false; + + var 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) + if (!_files.Remove(item)) + _directories.Remove(item); + _directories.Remove(path); + } + } + + Notify(new FileChange(FileChangeKind.Deleted, PathOf(path))); + return true; + } + + /// + protected override void MoveCore(string source, string destination, bool overwrite) + { + lock (_sync) + { + if (_files.TryGetValue(source, out var file)) + { + if (_directories.Contains(destination)) + throw new IOException($"'{PathOf(destination)}' is a directory"); + if (_files.ContainsKey(destination) && !overwrite) + throw new IOException($"'{PathOf(destination)}' exists already"); + + AddDirectories(DomainPaths.ParentOf(destination)); + _files.Remove(source); + _files[destination] = file with { Revision = ++_revision }; + } + else if (_directories.Contains(source)) + { + if (_files.ContainsKey(destination) || _directories.Contains(destination)) + throw new IOException($"'{PathOf(destination)}' exists already"); + + AddDirectories(DomainPaths.ParentOf(destination)); + var prefix = source + "/"; + foreach (var 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)) + .ToArray()) + { + _files.Remove(path); + _files[destination + path.Substring(source.Length)] = moved with { Revision = ++_revision }; + } + } + else throw NotFound(source); + } + + Notify(new FileChange(FileChangeKind.Renamed, PathOf(destination), PathOf(source))); + } + + /// + protected override IDisposable WatchCore(string directory, bool recursive, Action handler) + { + var watcher = new Watcher(directory, recursive, handler); + lock (_sync) + { + if (!_directories.Contains(directory)) + throw DirectoryNotFound(directory); + _watchers = [.. _watchers, watcher]; + } + + return new Unwatch(this, watcher); + } + + /// + protected override void DisposeCore() + { + lock (_sync) + { + _watchers = []; + _files.Clear(); + } + } +} diff --git a/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs b/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs new file mode 100644 index 0000000..a6bfb39 --- /dev/null +++ b/src/Managed/Stellar.FileSystem/Drivers/OverlayDriver.cs @@ -0,0 +1,220 @@ +using Stellar.Core.Quantization; +using Stellar.FileSystem.Domains; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Drivers; + +/// +/// Mounts several domains as layers of one (overlay): the source names them, first wins, such as +/// mods,dlc,base. +/// +/// +/// A file is read from the first layer that has it; listings merge the layers, the first entry of a path +/// wins. The layers are looked up on each call, so a layer mounted later, or remounted, takes part at once, and a +/// layer not mounted is skipped. Watches cover the layers mounted when the watch starts. +/// The option write=<layer> sends writes to that layer; without it the overlay is read-only. A +/// file of a lower layer opened to be changed is first copied up to it. A delete removes the copy of the write +/// layer only: the file of a lower layer shows again. +/// +public sealed class OverlayDriver() + : Quant(new MetaQuant()), IFileDriver +{ + /// + public DomainScheme Scheme => DomainScheme.Overlay; + + /// + public IDomain Mount(DomainMount mount, IFileSystem fileSystem) => new OverlayDomain(mount, fileSystem); +} + +internal sealed class OverlayDomain + : DomainBase +{ + private readonly string[] _layers; + private readonly string? _writeLayer; + + private static DomainCapabilities CapabilitiesOf(DomainMount mount) + { + var capabilities = DomainCapabilities.Read + | DomainCapabilities.Enumerate + | DomainCapabilities.Watch + | DomainCapabilities.RandomAccess + | DomainCapabilities.Memory; + return mount.Options?.ContainsKey("write") == true + ? capabilities | DomainCapabilities.Write | DomainCapabilities.AtomicWrite + : capabilities; + } + + public OverlayDomain(DomainMount mount, IFileSystem fileSystem) + : base(mount, fileSystem, CapabilitiesOf(mount)) + { + _layers = (mount.Source ?? string.Empty) + .Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries) + .Select(layer => FileSystemNames.NormalizeName(layer, nameof(mount))) + .Distinct(StringComparer.Ordinal) + .ToArray(); + + if (_layers.Length == 0) + throw new ArgumentException($"The overlay '{Name}' names no layers: " + + $"expected a source such as mods,base", nameof(mount)); + 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; + + _writeLayer = FileSystemNames.NormalizeName(write, nameof(mount)); + if (!_layers.Contains(_writeLayer)) + throw new ArgumentException($"The write layer '{write}' " + + $"is not a layer of the overlay '{Name}'", nameof(mount)); + } + + private IEnumerable Layers() + { + foreach (var name in _layers) + if (FileSystem.Domains.TryGet(name, out var layer)) + yield return layer; + } + + private IDomain WriteLayer() => + _writeLayer is not null && FileSystem.Domains.TryGet(_writeLayer, out var 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)); + if (lower is null) + { + if (optional) return; + throw NotFound(path); + } + + if (lower.TryGetEntry(path, out var 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); + source.CopyTo(target); + } + + private IDomain WriteLayerFor(string path, FileOpenOptions options) + { + var layer = WriteLayer(); + if (options.Mode is FileMode.Open or FileMode.OpenOrCreate or FileMode.Append && !layer.Exists(path)) + CopyUp(path, layer, optional: true); + return layer; + } + + private IDomain ReadLayerOf(string path) => + 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(); + } + } + + private sealed class Renamed(FilePath path, IRandomAccessFile file) + : IRandomAccessFile + { + public FilePath Path { get; } = path; + + public long Length => file.Length; + + public int Read(long offset, Span buffer) => file.Read(offset, buffer); + + public ValueTask ReadAsync(long offset, Memory buffer, + CancellationToken cancellationToken = default) => + file.ReadAsync(offset, buffer, cancellationToken); + + public void Dispose() => file.Dispose(); + } + + protected override bool ExistsCore(string path) => + Layers().Any(layer => layer.Exists(path)); + + protected override bool TryGetEntryCore(string path, out FileEntry entry) + { + foreach (var layer in Layers()) + { + if (!layer.TryGetEntry(path, out entry)) continue; + entry = entry with { Path = entry.Path.WithDomain(Name) }; + return true; + } + + entry = default; + return false; + } + + protected override IEnumerable EnumerateCore(string directory, string pattern, bool recursive) + { + var layers = Layers() + .Where(layer => layer.TryGetEntry(directory, out var entry) && entry.IsDirectory) + .ToArray(); + if (layers.Length == 0) + throw DirectoryNotFound(directory); + + return Merge(); + + IEnumerable Merge() + { + var seen = new HashSet(StringComparer.Ordinal); + foreach (var layer in layers) + foreach (var 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 ValueTask OpenAsyncCore(string path, FileOpenOptions options, + CancellationToken cancellationToken) => + options.Writes + ? WriteLayerFor(path, options).OpenAsync(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 bool TryGetMemoryCore(string path, out ReadOnlyMemory data) + { + data = default; + var 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 bool DeleteCore(string path, bool recursive) => WriteLayer().Delete(path, recursive); + + protected override void MoveCore(string source, string destination, bool overwrite) + { + var layer = WriteLayer(); + if (!layer.Exists(source)) CopyUp(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()) + { + if ((layer.Capabilities & DomainCapabilities.Watch) == 0) continue; + if (!layer.TryGetEntry(directory, out var entry) || !entry.IsDirectory) continue; + + watches.Add(layer.Watch(directory, recursive, change => handler(change with + { + Path = change.Path.IsEmpty ? change.Path : change.Path.WithDomain(Name), + OldPath = change.OldPath.IsEmpty ? change.OldPath : change.OldPath.WithDomain(Name) + }))); + } + + return new Watches(watches); + } +} diff --git a/src/Managed/Stellar.FileSystem/FileSystemFiles.cs b/src/Managed/Stellar.FileSystem/FileSystemFiles.cs new file mode 100644 index 0000000..72ba20c --- /dev/null +++ b/src/Managed/Stellar.FileSystem/FileSystemFiles.cs @@ -0,0 +1,132 @@ +using System.Text; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem; + +/// +/// Whole files at once: bytes and text, read and written through any domain. +/// +/// +/// Text is read in the charset of the content type of the file (), UTF-8 by +/// default, and a byte order mark wins over both. For large files, or data shared between owners, open a stream or +/// lease a resource instead. +/// +public static class FileSystemFiles +{ + private static byte[] ReadToEnd(Stream stream) + { + if (stream is MemoryStream memory && memory.TryGetBuffer(out var segment)) + return segment.AsSpan((int)memory.Position).ToArray(); + + var buffer = new MemoryStream(stream.CanSeek ? (int)Math.Min(stream.Length, int.MaxValue) : 0); + stream.CopyTo(buffer); + return buffer.ToArray(); + } + + 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); + + try + { + return Encoding.GetEncoding(charset); + } + catch (ArgumentException) + { + return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); + } + } + + private static string Decode(ReadOnlySpan data, Encoding encoding) + { + // A byte order mark wins over the charset, as StreamReader does + if (data.StartsWith((ReadOnlySpan)[0xEF, 0xBB, 0xBF])) return Encoding.UTF8.GetString(data[3..]); + if (data.StartsWith((ReadOnlySpan)[0xFF, 0xFE])) return Encoding.Unicode.GetString(data[2..]); + if (data.StartsWith((ReadOnlySpan)[0xFE, 0xFF])) return Encoding.BigEndianUnicode.GetString(data[2..]); + return encoding.GetString(data); + } + + /// + /// Reads the bytes of a file. + /// + /// The file system. + /// The file. + /// 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(); + + using var stream = domain.Open(path.Value, + FileOpenOptions.Read with { Flags = FileOpenFlags.Sequential }); + return ReadToEnd(stream); + } + + /// + /// Reads the bytes of a file without blocking on a slow source. + /// + /// The file system. + /// The file. + /// Stops the read. + /// A copy of its bytes. + 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(); + + await using var 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); + await stream.CopyToAsync(buffer, cancellationToken).ConfigureAwait(false); + return buffer.ToArray(); + } + + /// + /// Reads a file as text. + /// + /// The file system. + /// The file. + /// 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); + + using var stream = domain.Open(path.Value, + FileOpenOptions.Read with { Flags = FileOpenFlags.Sequential }); + using var reader = new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks: true); + return reader.ReadToEnd(); + } + + /// + /// Writes the bytes of a file, replacing it. + /// + /// The file system. + /// 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) + { + using var stream = fileSystem.Open(path, atomic ? FileOpenOptions.Replace : FileOpenOptions.Write); + stream.Write(data); + } + + /// + /// Writes a file as text, replacing it, in the charset of its content type; UTF-8 with no byte order mark by default. + /// + /// The file system. + /// 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) + { + ArgumentNullException.ThrowIfNull(text); + fileSystem.WriteAllBytes(path, EncodingOf(fileSystem, path).GetBytes(text), atomic); + } +} diff --git a/src/Managed/Stellar.FileSystem/Stellar.FileSystem.csproj b/src/Managed/Stellar.FileSystem/Stellar.FileSystem.csproj index 95944df..180a641 100644 --- a/src/Managed/Stellar.FileSystem/Stellar.FileSystem.csproj +++ b/src/Managed/Stellar.FileSystem/Stellar.FileSystem.csproj @@ -4,4 +4,8 @@ the dependencies from Stellar.FileSystem.stellar.module, and references Stellar.Kernel and Stellar.Core. Anything set here wins over it. Every property: Docs/Reference/Sdk.Properties.md of the installation. --> + + + true + diff --git a/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs b/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs new file mode 100644 index 0000000..87f65fb --- /dev/null +++ b/src/Managed/Stellar.FileSystem/VirtualFileSystem.cs @@ -0,0 +1,164 @@ +using Stellar.Core.Data.Catalog; +using Stellar.Core.Quantization; +using Stellar.FileSystem.Drivers; +using Stellar.Kernel.Data.Catalog; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem; + +/// +/// The file system of one engine instance: its drivers, the domains they mounted and the content types. +/// +/// +/// Nothing of it is static: make one per engine instance. gives one with the drivers of +/// this module (dir, asm, mem, overlay) and the common content types; mounting the +/// domains is up to the runtime. +/// +public sealed class VirtualFileSystem + : Quant, IFileSystem +{ + // A driver is set under its own scheme + private sealed class DriverCatalog + : Catalog + { + protected override DomainScheme NormalizeKey(DomainScheme key) + { + return string.IsNullOrEmpty(key.Name) + ? throw new ArgumentException("A driver needs a scheme", nameof(key)) + : key; + } + + protected override void Validate(DomainScheme key, IFileDriver value) + { + base.Validate(key, value); + if (value.Scheme != key) + throw new ArgumentException($"The driver of '{value.Scheme}' cannot be set under '{key}'", + nameof(value)); + } + } + + // Names in any case; a missing domain says so + private sealed class DomainCatalog + : Catalog + { + protected override string NormalizeKey(string key) + { + return FileSystemNames.NormalizeName(key, nameof(key)); + } + + protected override Exception NotFound(string key) + { + return new DomainNotFoundException(key); + } + } + + private readonly DriverCatalog _drivers = new(); + private readonly DomainCatalog _domains = new(); + private readonly Lock _mounting = new(); + private volatile bool _disposed; + + /// + public IContentTypeCatalog ContentTypes { get; } + + /// + /// Makes a file system with no drivers and no domains. + /// + /// The content types; an empty catalog if null. + public VirtualFileSystem(IContentTypeCatalog? contentTypes = null) + : base(new MetaQuant()) + { + ContentTypes = contentTypes ?? new ContentTypeCatalog(); + } + + /// + /// Makes a file system with the drivers of this module and the common content types. + /// + /// The file system, with no domain mounted. + public static VirtualFileSystem CreateDefault() + { + var fileSystem = new VirtualFileSystem(ContentTypeCatalog.CreateDefault()); + fileSystem.AddDriver(new DirectoryDriver()); + fileSystem.AddDriver(new AssemblyDriver()); + fileSystem.AddDriver(new MemoryDriver()); + fileSystem.AddDriver(new OverlayDriver()); + return fileSystem; + } + + /// + public ICatalog Drivers => _drivers; + + /// + // ReSharper disable once InconsistentlySynchronizedField + public IReadOnlyCatalog Domains => _domains; + + /// + public event Action? Mounted; + + /// + public event Action? Unmounting; + + /// + 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)) + throw new InvalidOperationException($"No driver of the scheme '{mount.Scheme}' is there, " + + $"for the domain '{name}'"); + + IDomain domain; + lock (_mounting) + { + if (_domains.Contains(name)) + throw new InvalidOperationException($"A domain '{name}' is mounted already"); + + domain = driver.Mount(mount with { Name = name }, this); + if (domain.Name != name) + { + domain.Dispose(); + throw new InvalidOperationException($"The driver of '{mount.Scheme}' " + + $"mounted '{domain.Name}' instead of '{name}'"); + } + + _domains.Set(name, domain); + } + + Mounted?.Invoke(domain); + return domain; + } + + /// + public bool Unmount(string name) + { + ArgumentNullException.ThrowIfNull(name); + + IDomain? domain; + lock (_mounting) + { + if (!_domains.TryRemove(name, out domain)) return false; + } + + // Out of the file system, still working: whoever holds data of it lets go + try + { + Unmounting?.Invoke(domain); + } + finally + { + domain.Dispose(); + } + + return true; + } + + /// + /// Unmounts every domain. + /// + public void Dispose() + { + if (_disposed) return; + _disposed = true; + + foreach (var name in _domains.Keys) Unmount(name); + } +} diff --git a/tests/Stellar.FileSystem.Tests/DirectoryDomainTests.cs b/tests/Stellar.FileSystem.Tests/DirectoryDomainTests.cs new file mode 100644 index 0000000..7864596 --- /dev/null +++ b/tests/Stellar.FileSystem.Tests/DirectoryDomainTests.cs @@ -0,0 +1,138 @@ +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Tests; + +public sealed class DirectoryDomainTests + : IDisposable +{ + private readonly string _root = Path.Combine(Path.GetTempPath(), "Stellar.FileSystem.Tests", Guid.NewGuid().ToString("N")); + private readonly VirtualFileSystem _fileSystem = VirtualFileSystem.CreateDefault(); + + public DirectoryDomainTests() + { + Directory.CreateDirectory(_root); + _fileSystem.Mount(new DomainMount("disk", DomainScheme.Directory, _root)); + } + + public void Dispose() + { + _fileSystem.Dispose(); + // Directory.Delete removes links as links, never what they lead to + if (Directory.Exists(_root)) Directory.Delete(_root, recursive: true); + } + + [Fact] + public void ARelativeSource_IsRefused() + { + _fileSystem.Invoking(fs => fs.Mount(new DomainMount("rel", DomainScheme.Directory, "relative/dir"))) + .Should().Throw(); + } + + [Fact] + public void ReadOnly_NeedsTheDirectory_AndRefusesWrites() + { + var options = new Dictionary { ["readonly"] = "true" }; + _fileSystem.Invoking(fs => fs.Mount(new DomainMount("missing", DomainScheme.Directory, Path.Combine(_root, "missing"), options))) + .Should().Throw(); + + _fileSystem.Mount(new DomainMount("ro", DomainScheme.Directory, _root, options)); + _fileSystem.Invoking(fs => fs.WriteAllText(FilePath.Parse("ro://a.txt"), "x")).Should().Throw(); + } + + [Fact] + public void Files_GoUnderTheRoot() + { + var path = FilePath.Parse("disk://saves/slot1/game.json"); + _fileSystem.WriteAllText(path, "{\"level\":1}"); + + File.ReadAllText(Path.Combine(_root, "saves", "slot1", "game.json")).Should().Be("{\"level\":1}"); + _fileSystem.ReadAllText(path).Should().Be("{\"level\":1}"); + + var entry = _fileSystem.GetEntry(path); + entry.Length.Should().Be(11); + entry.Content.MediaType.Should().Be("application/json"); + entry.Revision.Should().NotBe(0); + } + + [Fact] + public void AtomicWrite_ShowsNoTemporaryFile() + { + var path = FilePath.Parse("disk://settings.ini"); + _fileSystem.WriteAllText(path, "old"); + + using (var stream = _fileSystem.Open(path, FileOpenOptions.Replace)) + { + stream.Write("new"u8); + _fileSystem.ReadAllText(path).Should().Be("old"); + _fileSystem.Enumerate(FilePath.Root("disk")).Select(e => e.Path.Value).Should().Equal("settings.ini"); + } + + _fileSystem.ReadAllText(path).Should().Be("new"); + Directory.GetFiles(_root).Should().ContainSingle(); + } + + [Fact] + public void Enumerate_ListsWithPatterns() + { + _fileSystem.WriteAllText(FilePath.Parse("disk://a/one.txt"), "1"); + _fileSystem.WriteAllText(FilePath.Parse("disk://a/b/two.json"), "2"); + + _fileSystem.Enumerate(FilePath.Parse("disk://a")).Select(e => e.Path.Value).Should().BeEquivalentTo("a/one.txt", "a/b"); + _fileSystem.Enumerate(FilePath.Root("disk"), "*.json", recursive: true).Select(e => e.Path.Value).Should().Equal("a/b/two.json"); + _fileSystem.Invoking(fs => fs.Enumerate(FilePath.Parse("disk://none")).ToList()).Should().Throw(); + } + + [Fact] + public void RandomAccess_ReadsTheDisk() + { + var path = FilePath.Parse("disk://pack.bin"); + _fileSystem.WriteAllBytes(path, [10, 11, 12, 13]); + + using var file = _fileSystem.OpenRandomAccess(path); + var buffer = new byte[2]; + file.Read(2, buffer).Should().Be(2); + buffer.Should().Equal(12, 13); + } + + [Fact] + public void ALinkOutOfTheRoot_IsRefused() + { + var outside = Path.Combine(Path.GetTempPath(), "Stellar.FileSystem.Tests", Guid.NewGuid().ToString("N") + "-outside"); + Directory.CreateDirectory(outside); + File.WriteAllText(Path.Combine(outside, "secret.txt"), "secret"); + + try + { + try { Directory.CreateSymbolicLink(Path.Combine(_root, "escape"), outside); } + catch (Exception e) when (e is IOException or UnauthorizedAccessException) { return; } // No right to make links here + + var path = FilePath.Parse("disk://escape/secret.txt"); + _fileSystem.Exists(path).Should().BeFalse(); + _fileSystem.Invoking(fs => fs.ReadAllText(path)).Should().Throw(); + _fileSystem.Enumerate(FilePath.Root("disk"), recursive: true).Should().BeEmpty(); + } + finally + { + Directory.Delete(outside, recursive: true); + } + } + + [Fact] + public async Task Watch_ReportsChanges() + { + var changes = new List(); + var created = new TaskCompletionSource(); + + using (_fileSystem.Watch(FilePath.Root("disk"), recursive: true, change => + { + lock (changes) changes.Add(change); + if (change.Path.Value == "watched.txt") created.TrySetResult(); + })) + { + _fileSystem.WriteAllText(FilePath.Parse("disk://watched.txt"), "1"); + (await Task.WhenAny(created.Task, Task.Delay(TimeSpan.FromSeconds(10)))).Should().Be(created.Task); + } + + lock (changes) changes.Should().Contain(c => c.Path == FilePath.Parse("disk://watched.txt")); + } +} diff --git a/tests/Stellar.FileSystem.Tests/FileSystemTests.cs b/tests/Stellar.FileSystem.Tests/FileSystemTests.cs new file mode 100644 index 0000000..878b0ae --- /dev/null +++ b/tests/Stellar.FileSystem.Tests/FileSystemTests.cs @@ -0,0 +1,236 @@ +using System.Text; +using Stellar.Kernel.FileSystem; + +namespace Stellar.FileSystem.Tests; + +public class FileSystemTests +{ + private static VirtualFileSystem WithMemory(params string[] names) + { + var fileSystem = VirtualFileSystem.CreateDefault(); + foreach (var name in names) fileSystem.Mount(new DomainMount(name, DomainScheme.Memory, string.Empty)); + return fileSystem; + } + + [Fact] + public void Domains_AreFoundByName() + { + using var fileSystem = WithMemory("assets"); + + fileSystem.Domains.Get("Assets").Name.Should().Be("assets"); + fileSystem.Domains.Contains("ASSETS").Should().BeTrue(); + fileSystem.Domains.Contains("not a name").Should().BeFalse(); + fileSystem.Invoking(fs => fs.Domains.Get("nowhere")).Should().Throw(); + fileSystem.Invoking(fs => fs.Mount(new DomainMount("assets", DomainScheme.Memory, ""))).Should().Throw(); + fileSystem.Invoking(fs => fs.Mount(new DomainMount("net", new DomainScheme("net"), ""))).Should().Throw(); + } + + [Fact] + public void Drivers_AreACatalogBySchemes() + { + using var fileSystem = VirtualFileSystem.CreateDefault(); + + fileSystem.Drivers.Keys.Should().BeEquivalentTo([DomainScheme.Directory, DomainScheme.Assembly, DomainScheme.Memory, DomainScheme.Overlay]); + fileSystem.Invoking(fs => fs.AddDriver(new Drivers.MemoryDriver())).Should().Throw(); + fileSystem.Invoking(fs => fs.Drivers.Set(new DomainScheme("zip"), new Drivers.MemoryDriver())).Should().Throw(); + + fileSystem.Drivers.Remove(DomainScheme.Memory).Should().BeTrue(); + fileSystem.Invoking(fs => fs.Mount(new DomainMount("m", DomainScheme.Memory, ""))).Should().Throw(); + } + + [Fact] + public void ContentTypes_AreACatalogByExtension() + { + var types = ContentTypeCatalog.CreateDefault(); + + types.Get(".PNG").MediaType.Should().Be("image/png"); + types.Resolve(FilePath.Parse("a://b/c.Json")).IsText.Should().BeTrue(); + types.Resolve(FilePath.Parse("a://b/c.unknown")).Should().Be(ContentType.OctetStream); + types.Contains("png").Should().BeFalse(); + types.Invoking(t => t.Set("png", ContentType.PlainText)).Should().Throw(); + types.Invoking(t => t.Set(".x", default)).Should().Throw(); + } + + [Fact] + public void Unmount_TellsAndDisposes() + { + using var fileSystem = WithMemory("assets"); + var domain = fileSystem.Domains.Get("assets"); + IDomain? told = null; + fileSystem.Unmounting += d => told = d; + + fileSystem.Unmount("assets").Should().BeTrue(); + + told.Should().BeSameAs(domain); + domain.Invoking(d => d.Exists("a")).Should().Throw(); + fileSystem.Unmount("assets").Should().BeFalse(); + } + + [Fact] + public void Memory_WritesWhenTheStreamCloses() + { + using var fileSystem = WithMemory("mem"); + var path = FilePath.Parse("mem://levels/1.json"); + + using (var stream = fileSystem.Open(path, FileOpenOptions.Write)) + { + stream.Write("{}"u8); + fileSystem.Exists(path).Should().BeFalse(); + } + + fileSystem.ReadAllText(path).Should().Be("{}"); + var entry = fileSystem.GetEntry(path); + entry.IsFile.Should().BeTrue(); + entry.Length.Should().Be(2); + entry.Content.MediaType.Should().Be("application/json"); + fileSystem.GetEntry(FilePath.Parse("mem://levels")).IsDirectory.Should().BeTrue(); + } + + [Fact] + public void Memory_GivesBytesThatNeverChange() + { + using var fileSystem = WithMemory("mem"); + var path = FilePath.Parse("mem://data.bin"); + fileSystem.WriteAllBytes(path, [1, 2, 3]); + + fileSystem.TryGetMemory(path, out var before).Should().BeTrue(); + var revision = fileSystem.GetEntry(path).Revision; + fileSystem.WriteAllBytes(path, [9]); + + before.ToArray().Should().Equal(1, 2, 3); + fileSystem.ReadAllBytes(path).Should().Equal(9); + fileSystem.GetEntry(path).Revision.Should().NotBe(revision); + } + + [Fact] + public void Memory_ModesAsOnADisk() + { + using var fileSystem = WithMemory("mem"); + var path = FilePath.Parse("mem://log.txt"); + + fileSystem.Invoking(fs => fs.OpenRead(path)).Should().Throw(); + fileSystem.WriteAllText(path, "a"); + using (var append = fileSystem.Open(path, FileOpenOptions.Append)) append.Write("b"u8); + fileSystem.ReadAllText(path).Should().Be("ab"); + fileSystem.Invoking(fs => fs.Open(path, new FileOpenOptions(FileMode.CreateNew, FileAccess.Write))).Should().Throw(); + fileSystem.Invoking(fs => fs.WriteAllText(FilePath.Parse("mem://log.txt/inner.txt"), "x")).Should().Throw(); + } + + [Fact] + public void Memory_ListsMovesAndDeletes() + { + using var fileSystem = WithMemory("mem"); + fileSystem.WriteAllText(FilePath.Parse("mem://a/one.txt"), "1"); + fileSystem.WriteAllText(FilePath.Parse("mem://a/b/two.json"), "2"); + + fileSystem.Enumerate(FilePath.Parse("mem://a")).Select(e => e.Path.ToString()) + .Should().Equal("mem://a/b", "mem://a/one.txt"); + fileSystem.Enumerate(FilePath.Root("mem"), "*.json", recursive: true).Select(e => e.Path.Value) + .Should().Equal("a/b/two.json"); + + fileSystem.Move(FilePath.Parse("mem://a"), FilePath.Parse("mem://c")); + fileSystem.ReadAllText(FilePath.Parse("mem://c/b/two.json")).Should().Be("2"); + fileSystem.Exists(FilePath.Parse("mem://a")).Should().BeFalse(); + + fileSystem.Invoking(fs => fs.Delete(FilePath.Parse("mem://c"))).Should().Throw(); + fileSystem.Delete(FilePath.Parse("mem://c"), recursive: true).Should().BeTrue(); + fileSystem.Enumerate(FilePath.Root("mem"), recursive: true).Should().BeEmpty(); + fileSystem.Invoking(fs => fs.Delete(FilePath.Root("mem"), true)).Should().Throw(); + } + + [Fact] + public void Memory_ReportsChanges() + { + using var fileSystem = WithMemory("mem"); + fileSystem.CreateDirectory(FilePath.Parse("mem://watched")); + var changes = new List(); + + using (fileSystem.Watch(FilePath.Parse("mem://watched"), recursive: true, changes.Add)) + { + fileSystem.WriteAllText(FilePath.Parse("mem://watched/a.txt"), "1"); + fileSystem.WriteAllText(FilePath.Parse("mem://watched/a.txt"), "2"); + fileSystem.WriteAllText(FilePath.Parse("mem://elsewhere.txt"), "3"); + fileSystem.Move(FilePath.Parse("mem://watched/a.txt"), FilePath.Parse("mem://watched/b.txt")); + fileSystem.Delete(FilePath.Parse("mem://watched/b.txt")); + } + + fileSystem.WriteAllText(FilePath.Parse("mem://watched/c.txt"), "after"); + + changes.Select(c => c.Kind).Should().Equal( + FileChangeKind.Created, FileChangeKind.Changed, FileChangeKind.Renamed, FileChangeKind.Deleted); + changes[2].OldPath.Should().Be(FilePath.Parse("mem://watched/a.txt")); + } + + [Fact] + public void RandomAccess_ReadsAtOffsets() + { + using var fileSystem = WithMemory("mem"); + var path = FilePath.Parse("mem://pack.bin"); + fileSystem.WriteAllBytes(path, [0, 1, 2, 3, 4, 5]); + + using var file = fileSystem.OpenRandomAccess(path); + var buffer = new byte[4]; + + file.Length.Should().Be(6); + file.Read(4, buffer).Should().Be(2); + buffer[..2].Should().Equal(4, 5); + file.Read(10, buffer).Should().Be(0); + } + + [Fact] + public void Capabilities_AreCheckedFirst() + { + using var fileSystem = VirtualFileSystem.CreateDefault(); + fileSystem.Mount(new DomainMount("self", DomainScheme.Assembly, typeof(FileSystemTests).Assembly.GetName().Name!)); + + fileSystem.Invoking(fs => fs.WriteAllText(FilePath.Parse("self://data/hello.txt"), "x")).Should().Throw(); + fileSystem.Invoking(fs => fs.Watch(FilePath.Root("self"), true, _ => { })).Should().Throw(); + } + + [Fact] + public void Assembly_ServesEmbeddedFilesWithoutACopy() + { + using var fileSystem = VirtualFileSystem.CreateDefault(); + fileSystem.Mount(new DomainMount("self", DomainScheme.Assembly, typeof(FileSystemTests).Assembly.GetName().Name!)); + var path = FilePath.Parse("self://data/hello.txt"); + + fileSystem.ReadAllText(path).Should().Be("Hello from the assembly"); + fileSystem.TryGetMemory(path, out var memory).Should().BeTrue(); + Encoding.UTF8.GetString(memory.Span).Should().Be("Hello from the assembly"); + fileSystem.GetEntry(path).Content.IsText.Should().BeTrue(); + fileSystem.Enumerate(FilePath.Root("self"), recursive: true).Select(e => e.Path.Value).Should().Contain(["data", "data/hello.txt"]); + } + + [Fact] + public void Overlay_FirstLayerWins_AndWritesGoUp() + { + using var fileSystem = WithMemory("mods", "base"); + fileSystem.WriteAllText(FilePath.Parse("base://textures/hero.txt"), "base hero"); + fileSystem.WriteAllText(FilePath.Parse("base://textures/enemy.txt"), "base enemy"); + fileSystem.WriteAllText(FilePath.Parse("mods://textures/hero.txt"), "mod hero"); + fileSystem.Mount(new DomainMount("game", DomainScheme.Overlay, "mods, base", new Dictionary { ["write"] = "mods" })); + + fileSystem.ReadAllText(FilePath.Parse("game://textures/hero.txt")).Should().Be("mod hero"); + fileSystem.ReadAllText(FilePath.Parse("game://textures/enemy.txt")).Should().Be("base enemy"); + fileSystem.Enumerate(FilePath.Parse("game://textures")).Select(e => e.Path.ToString()) + .Should().BeEquivalentTo("game://textures/hero.txt", "game://textures/enemy.txt"); + fileSystem.GetEntry(FilePath.Parse("game://textures/enemy.txt")).Path.Domain.Should().Be("game"); + + using (var stream = fileSystem.Open(FilePath.Parse("game://textures/enemy.txt"), FileOpenOptions.Append)) stream.Write(" modded"u8); + fileSystem.ReadAllText(FilePath.Parse("mods://textures/enemy.txt")).Should().Be("base enemy modded"); + fileSystem.ReadAllText(FilePath.Parse("base://textures/enemy.txt")).Should().Be("base enemy"); + + fileSystem.Delete(FilePath.Parse("game://textures/enemy.txt")); + fileSystem.ReadAllText(FilePath.Parse("game://textures/enemy.txt")).Should().Be("base enemy"); + } + + [Fact] + public void Overlay_RefusesItself_AndReadsOnlyWithoutAWriteLayer() + { + using var fileSystem = WithMemory("base"); + + fileSystem.Invoking(fs => fs.Mount(new DomainMount("loop", DomainScheme.Overlay, "loop,base"))).Should().Throw(); + fileSystem.Mount(new DomainMount("view", DomainScheme.Overlay, "base")); + fileSystem.Invoking(fs => fs.WriteAllText(FilePath.Parse("view://a.txt"), "x")).Should().Throw(); + } +} diff --git a/tests/Stellar.FileSystem.Tests/Resources/data/hello.txt b/tests/Stellar.FileSystem.Tests/Resources/data/hello.txt new file mode 100644 index 0000000..6f2db29 --- /dev/null +++ b/tests/Stellar.FileSystem.Tests/Resources/data/hello.txt @@ -0,0 +1 @@ +Hello from the assembly \ No newline at end of file diff --git a/tests/Stellar.FileSystem.Tests/Stellar.FileSystem.Tests.csproj b/tests/Stellar.FileSystem.Tests/Stellar.FileSystem.Tests.csproj index eaff17f..cc674e9 100644 --- a/tests/Stellar.FileSystem.Tests/Stellar.FileSystem.Tests.csproj +++ b/tests/Stellar.FileSystem.Tests/Stellar.FileSystem.Tests.csproj @@ -6,4 +6,9 @@ + + + + +