diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index ae87db5..55300e0 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -1,23 +1,27 @@
name: Docs
-# Builds the documentation site of the module from Docs/ with DocFX (docfx.json) and publishes it to GitHub Pages.
-# Pull requests and manual runs on other branches only build; the site is deployed from master only.
-# Repository setting required once: Settings -> Pages -> Source = "GitHub Actions".
+# Publishes the documentation of this repository to GitHub Pages for the Prometheus site (the team site).
+# GitHub Pages is only the storage of the site: static files (the installer, the schemas), the documentation as data
+# (bundle/) and a small embed that redirects to the site when the site is up.
+#
+# This file is a thin wrapper and does not need updates: the steps (ci.py, the bundle builder, the embed) are
+# downloaded from the site on every run (/docs-kit.zip), so they are always the same version as the site.
+# What to build is described by the repository itself in prometheus.json (format prometheus-repo/1, see the DOCS
+# page of the site); without it: Docs/ and the API of the projects in docfx.json.
+# If the site is down, the static files and a page that leads to the site are published; the next run fixes the rest.
+#
+# Repository settings:
+# Settings -> Pages -> Source = "GitHub Actions" (once)
+# Variables (optional): PROMETHEUS_SITE (https://notagood.org by default),
+# PROMETHEUS_PROJECT, PROMETHEUS_TITLE (override prometheus.json)
+# Secrets (optional): PROMETHEUS_SYNC_KEY an API key of the site with the "sync" scope: the site learns about
+# the new build at once instead of on its next check
+# Pull requests and manual runs on other branches only build; Pages is deployed from master only.
on:
push:
branches: [master]
- paths:
- - 'Docs/**'
- - 'README.md'
- - 'docfx.json'
- - '.github/workflows/docs.yml'
pull_request:
- paths:
- - 'Docs/**'
- - 'README.md'
- - 'docfx.json'
- - '.github/workflows/docs.yml'
workflow_dispatch:
permissions:
@@ -31,39 +35,95 @@ env:
DOCFX_VERSION: '2.81.0'
DOTNET_NOLOGO: 'true'
DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
+ PROMETHEUS_SITE: ${{ vars.PROMETHEUS_SITE || 'https://notagood.org' }}
+ PROMETHEUS_PROJECT: ${{ vars.PROMETHEUS_PROJECT }}
+ PROMETHEUS_TITLE: ${{ vars.PROMETHEUS_TITLE }}
+ OUT: artifacts/pages
jobs:
build:
- name: Build site
- runs-on: ubuntu-latest
+ name: Build
+ runs-on: ubuntu-latest # pwsh, python3 and bash are there: "prepare" scripts may use any of them
steps:
- name: Checkout
uses: actions/checkout@v5
- # The global.json of a module pins Stellar.Sdk, not the .NET SDK
- name: Setup .NET
+ if: hashFiles('global.json') != ''
+ uses: actions/setup-dotnet@v5
+ with:
+ global-json-file: global.json
+
+ - name: Setup .NET (no global.json)
+ if: hashFiles('global.json') == ''
uses: actions/setup-dotnet@v5
with:
dotnet-version: '9.0.x'
+ # Installed outside the checkout so a repository NuGet.config (a local feed) is not involved.
- name: Install DocFX
working-directory: ${{ runner.temp }}
run: dotnet tool install docfx --version "$DOCFX_VERSION" --tool-path "$RUNNER_TEMP/docfx"
- - name: Build documentation
- run: '"$RUNNER_TEMP/docfx/docfx" build docfx.json --warningsAsErrors'
+ - name: Prometheus
+ id: prometheus
+ continue-on-error: true
+ run: |
+ set -euo pipefail
+ # NuGet wants the local feed folder of an installation to exist, even empty
+ mkdir -p packages
+ curl -fsSL --retry 2 "$PROMETHEUS_SITE/docs-kit.zip" -o "$RUNNER_TEMP/kit.zip"
+ unzip -q -o "$RUNNER_TEMP/kit.zip" -d "$RUNNER_TEMP/kit"
+ python3 -m pip install --quiet pyyaml
+ python3 "$RUNNER_TEMP/kit/ci.py" --out "$OUT" --docfx "$RUNNER_TEMP/docfx/docfx"
+
+ # The site is down or the build failed: publish the static files and a page that leads to the site.
+ # Self-contained on purpose (no kit): the installer and the schemas keep their addresses whatever happens.
+ - name: Fallback
+ if: steps.prometheus.outcome == 'failure'
+ run: |
+ echo "::warning title=Prometheus::The documentation was not built (is $PROMETHEUS_SITE up?); publishing the static files only"
+ mkdir -p "$OUT" && touch "$OUT/.nojekyll"
+ python3 - <<'PY'
+ import glob, html, json, os, re, shutil
+ out = os.environ["OUT"]
+ cfg = json.load(open("prometheus.json", encoding="utf-8-sig")) if os.path.isfile("prometheus.json") else {}
+ static = cfg.get("static") or next((a.get("docfx") if isinstance(a, dict) else a for a in cfg.get("api") or []), None) \
+ or ("docfx.json" if os.path.isfile("docfx.json") else None)
+ for config in ([static] if isinstance(static, str) else static or []):
+ if not os.path.isfile(config):
+ continue
+ base = os.path.dirname(os.path.abspath(config))
+ for r in json.load(open(config, encoding="utf-8-sig")).get("build", {}).get("resource", []):
+ src, dest = os.path.join(base, r.get("src", "")), os.path.join(out, r.get("dest", ""))
+ for pattern in r.get("files", []):
+ for f in glob.glob(os.path.join(src, pattern), recursive=True):
+ if os.path.isfile(f):
+ t = os.path.join(dest, os.path.relpath(f, src))
+ os.makedirs(os.path.dirname(t), exist_ok=True)
+ shutil.copy2(f, t)
+ repo = os.environ.get("GITHUB_REPOSITORY", "").rsplit("/", 1)[-1]
+ project = os.environ.get("PROMETHEUS_PROJECT") or cfg.get("project") or re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-")
+ url = html.escape(f"{os.environ['PROMETHEUS_SITE'].rstrip('/')}/docs/{project}")
+ title = html.escape(os.environ.get("PROMETHEUS_TITLE") or cfg.get("title") or repo)
+ with open(os.path.join(out, "index.html"), "w", encoding="utf-8") as f:
+ f.write(f'
{title}'
+ f''
+ f'{title} documentation
')
+ PY
- name: Upload Pages artifact
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
uses: actions/upload-pages-artifact@v5
with:
- path: artifacts/docs/site
+ path: ${{ env.OUT }}
deploy:
name: Deploy to GitHub Pages
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
needs: build
runs-on: ubuntu-latest
+ # Never cancel a deployment that is already running.
concurrency:
group: pages
cancel-in-progress: false
@@ -77,3 +137,13 @@ jobs:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v5
+
+ # The site would notice the new bundle on its next check anyway; this makes it immediate.
+ - name: Nudge the site
+ continue-on-error: true
+ env:
+ KEY: ${{ secrets.PROMETHEUS_SYNC_KEY }}
+ run: |
+ if [ -z "$KEY" ]; then echo "::notice::PROMETHEUS_SYNC_KEY is not set: the site picks the docs up on its next check"; exit 0; fi
+ sleep 30 # Pages needs a moment to serve the new files
+ curl -fsS -X POST -H "Authorization: Bearer $KEY" "$PROMETHEUS_SITE/api/v1/sync"
diff --git a/.github/workflows/marks.yml b/.github/workflows/marks.yml
new file mode 100644
index 0000000..ce1e719
--- /dev/null
+++ b/.github/workflows/marks.yml
@@ -0,0 +1,15 @@
+name: Marks
+
+# The marks in the comments of the code, checked by the workflow of the core (Docs/Engine/Marks.md there).
+
+on:
+ push:
+ branches: [develop, master]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ marks:
+ uses: QuantumDevTeam/StellarEngine-Core/.github/workflows/marks.yml@develop
diff --git a/.github/workflows/restrict-master-prs.yml b/.github/workflows/restrict-master-prs.yml
index b07b852..665d43f 100644
--- a/.github/workflows/restrict-master-prs.yml
+++ b/.github/workflows/restrict-master-prs.yml
@@ -4,6 +4,11 @@ on:
pull_request_target:
types: [opened, reopened]
+permissions:
+ contents: read
+ pull-requests: write
+ issues: write
+
jobs:
restrict:
uses: QuantumDevTeam/.github/.github/workflows/restrict-master-prs.yml@master
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..73cfede
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,18 @@
+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: [master]
+ pull_request:
+ branches: [master]
+
+permissions:
+ contents: read
+
+jobs:
+ tests:
+ uses: QuantumDevTeam/StellarEngine-Core/.github/workflows/tests.yml@develop
diff --git a/Docs/index.md b/Docs/index.md
index bca9296..8dd110b 100644
--- a/Docs/index.md
+++ b/Docs/index.md
@@ -2,8 +2,7 @@
File system of the engine
-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.
+A `CoreModule` module of [StellarEngine](prometheus:stellar-engine). Its documentation is on the [docs site](prometheus:stellar-filesystem), built from the Markdown files of `Docs/`; the whole engine, with every module, is on the site of the orchestra.
## Using it
@@ -42,4 +41,4 @@ with `AddDriver` (the catalog `Drivers`); the contracts are in `Stellar.Kernel.F
stellar modules build Stellar.FileSystem --tests
```
-See [the README](../README.md) for the layout of the module.
+See [the README](https://github.com/QuantumDevTeam/Stellar.FileSystem#readme) for the layout of the module.
diff --git a/Docs/toc.yml b/Docs/toc.yml
index 89c53bd..56c0673 100644
--- a/Docs/toc.yml
+++ b/Docs/toc.yml
@@ -1,7 +1,7 @@
-# Navigation of the documentation site of the module (DocFX). Paths are relative to this file.
+# Navigation of the documentation of the module (the bundle of the site). Paths are relative to this file.
- name: Home
href: index.md
- name: README
- href: ../README.md
+ href: https://github.com/QuantumDevTeam/Stellar.FileSystem#readme
- name: StellarEngine
- href: https://quantumdevteam.github.io/StellarEngine-Mono/
+ href: prometheus:stellar-engine
diff --git a/Stellar.FileSystem.stellar.module b/Stellar.FileSystem.stellar.module
index 98e579d..f0d3a2a 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.9.0",
+ "Version": "0.11.0",
"Level": "CoreModule",
"Description": "File system of the engine",
"Dependencies": []
diff --git a/docfx.json b/docfx.json
index a3c7325..d651cee 100644
--- a/docfx.json
+++ b/docfx.json
@@ -1,39 +1,12 @@
{
"$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json",
"build": {
- "content": [
- {
- "src": "Docs",
- "files": [
- "**/*.md",
- "toc.yml"
- ]
- },
- {
- "files": [
- "README.md"
- ]
- }
- ],
"resource": [
{
"files": [
"Branding/Logo.svg"
]
}
- ],
- "output": "artifacts/docs/site",
- "template": [
- "default",
- "modern"
- ],
- "globalMetadata": {
- "_appName": "Stellar.FileSystem",
- "_appTitle": "Stellar.FileSystem",
- "_appFooter": "Stellar.FileSystem, a module of StellarEngine",
- "_appLogoPath": "Branding/Logo.svg",
- "_appFaviconPath": "Branding/Logo.svg",
- "_enableSearch": true
- }
+ ]
}
}
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/prometheus.json b/prometheus.json
new file mode 100644
index 0000000..2bdc67e
--- /dev/null
+++ b/prometheus.json
@@ -0,0 +1,15 @@
+{
+ "format": "prometheus-repo/1",
+ "project": "stellar-filesystem",
+ "title": "Stellar.FileSystem",
+ "version": {
+ "file": "Stellar.FileSystem.stellar.module",
+ "regex": "\"Version\"\\s*:\\s*\"([^\"]+)\""
+ },
+ "docs": [
+ {
+ "path": "Docs"
+ }
+ ],
+ "static": "docfx.json"
+}
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
new file mode 100644
index 0000000..8e26787
--- /dev/null
+++ b/src/Managed/Stellar.FileSystem/FileSystemEntryPoint.cs
@@ -0,0 +1,47 @@
+using Stellar.Kernel.Configuration;
+using Stellar.Kernel.EntryPoint;
+using Stellar.Kernel.FileSystem;
+using Stellar.Kernel.Services;
+
+namespace Stellar.FileSystem;
+
+///
+/// Publishes the file system of the engine, with the domains of mounted.
+///
+[StellarEntryPoint]
+public sealed class FileSystemEntryPoint(RuntimeConfiguration configuration)
+ : StellarEntryPoint(FileSystemModule.Id, configuration)
+{
+ private IServiceCatalog? _services;
+ private VirtualFileSystem? _fileSystem;
+
+ ///
+ public override int Run(ref readonly TContext context)
+ {
+ if (context.Services is not { } services) return 1;
+
+ _services = services;
+ _fileSystem = VirtualFileSystem.CreateDefault();
+
+ foreach (DomainMount mount in EngineMounts.Of(RuntimeConfiguration)) _fileSystem.Mount(mount);
+
+ services.Set(_fileSystem);
+
+ return 0;
+ }
+
+ ///
+ public override void RequestStop(ref readonly TContext context)
+ {
+ if (_services is not { } services) return;
+ _services = null;
+
+ if (ReferenceEquals(services.Find(), _fileSystem)) services.Remove();
+ }
+
+ ///
+ public override void Dispose()
+ {
+ _fileSystem?.Dispose();
+ }
+}
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
new file mode 100644
index 0000000..c2419fc
--- /dev/null
+++ b/tests/Stellar.FileSystem.Tests/EntryPointTests.cs
@@ -0,0 +1,199 @@
+using Stellar.Core.EntryPoints;
+using Stellar.Core.Services;
+using Stellar.Kernel.Configuration;
+using Stellar.Kernel.EntryPoint;
+using Stellar.Kernel.FileSystem;
+using Stellar.Kernel.Services;
+
+namespace Stellar.FileSystem.Tests;
+
+public sealed class EntryPointTests
+ : IDisposable
+{
+ 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");
+ private readonly ServiceCatalog _services = new();
+
+ public void Dispose()
+ {
+ 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(root, "Starlet");
+ if (Directory.Exists(shared) && !Directory.EnumerateFileSystemEntries(shared).Any())
+ Directory.Delete(shared);
+ }
+ }
+
+ private static void Delete(string path)
+ {
+ if (Directory.Exists(path)) Directory.Delete(path, true);
+ }
+
+ private static FileSystemEntryPoint Make(string company, string project)
+ {
+ return new FileSystemEntryPoint(new RuntimeConfiguration { CompanyName = company, ProjectName = project });
+ }
+
+ private static int Run(FileSystemEntryPoint entryPoint, IServiceCatalog? services)
+ {
+ var context = new RunContext(null, services: services);
+ return entryPoint.Run(in context);
+ }
+
+ private static void RequestStop(FileSystemEntryPoint entryPoint)
+ {
+ var context = new StopContext(null, StopReason.Regular);
+ entryPoint.RequestStop(in context);
+ }
+
+ private static void Stop(FileSystemEntryPoint entryPoint)
+ {
+ RequestStop(entryPoint);
+ entryPoint.Dispose();
+ }
+
+ [Fact]
+ public void Run_PublishesTheFileSystem_AndStopTakesItBack()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, _project);
+ Run(entryPoint, _services).Should().Be(0);
+
+ var files = _services.Find()!;
+ files.Should().BeOfType();
+ files.Domains.Keys.Should().BeEquivalentTo("app", "user", "local", "locallow", "temp");
+
+ Stop(entryPoint);
+ _services.Find().Should().BeNull();
+ files.Domains.Keys.Should().BeEmpty();
+ }
+
+ [Fact]
+ public void User_IsTheFolderOfTheProject_OfTheCompany()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, _project);
+ Run(entryPoint, _services);
+
+ _services.Find()!.WriteAllText(FilePath.Parse("user://a.txt"), "text");
+ File.ReadAllText(Path.Combine(AppData, _company, _project, "a.txt")).Should().Be("text");
+
+ Stop(entryPoint);
+ File.Exists(Path.Combine(AppData, _company, _project, "a.txt")).Should().BeTrue("the files outlive the engine");
+ }
+
+ [Theory]
+ [InlineData("Unknown")]
+ [InlineData("")]
+ [InlineData(null)]
+ 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();
+ }
+
+ [Theory]
+ [InlineData("")]
+ [InlineData(null)]
+ public void User_OfNoProjectName_IsNotMounted(string? project)
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, project!);
+ Run(entryPoint, _services);
+ Stop(entryPoint);
+
+ Directory.Exists(Path.Combine(AppData, _company)).Should().BeFalse();
+ }
+
+ [Fact]
+ public void User_OfNoProject_IsNotMounted()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, "");
+ Run(entryPoint, _services).Should().Be(0);
+
+ _services.Find()!.Domains.Keys.Should().BeEquivalentTo("app");
+
+ Stop(entryPoint);
+ Directory.Exists(Path.Combine(AppData, _company)).Should().BeFalse();
+ }
+
+ [Fact]
+ public void App_CannotBeWritten()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, _project);
+ Run(entryPoint, _services);
+
+ var files = _services.Find()!;
+ files.Invoking(it => it.WriteAllText(FilePath.Parse("app://a.txt"), "text"))
+ .Should().Throw();
+ File.Exists(Path.Combine(AppContext.BaseDirectory, "a.txt")).Should().BeFalse();
+
+ Stop(entryPoint);
+ }
+
+ [Fact]
+ public void WithoutServices_DoesNotStart()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, _project);
+ Run(entryPoint, null).Should().NotBe(0);
+
+ entryPoint.Invoking(Stop).Should().NotThrow();
+ Directory.Exists(Path.Combine(AppData, _company)).Should().BeFalse();
+ }
+
+ [Fact]
+ public void Stop_LeavesTheFileSystemOfAnotherModule()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, _project);
+ Run(entryPoint, _services);
+
+ using var other = new VirtualFileSystem();
+ _services.Set(other);
+
+ Stop(entryPoint);
+ _services.Find().Should().BeSameAs(other);
+ }
+
+ [Fact]
+ public void TwoEngines_HaveTheirOwnFileSystems()
+ {
+ var otherServices = new ServiceCatalog();
+ FileSystemEntryPoint first = Make(_company, _project);
+ FileSystemEntryPoint second = Make(_company, _project);
+ Run(first, _services);
+ Run(second, otherServices);
+
+ Stop(first);
+ otherServices.Find()!.Domains.Keys.Should()
+ .BeEquivalentTo("app", "user", "local", "locallow", "temp");
+
+ Stop(second);
+ }
+
+ [Fact]
+ public void Dispose_MayBeRepeated_AndCalledWithoutRun()
+ {
+ FileSystemEntryPoint entryPoint = Make(_company, _project);
+ entryPoint.Invoking(it => it.Dispose()).Should().NotThrow();
+
+ Run(entryPoint, _services);
+ Stop(entryPoint);
+ entryPoint.Invoking(Stop).Should().NotThrow();
+ }
+}
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();
+ }
+ }
+}