Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions .github/workflows/windows-native.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: Windows native build
on: [pull_request, workflow_dispatch]
permissions:
contents: read

jobs:
win-x64:
runs-on: windows-2022
timeout-minutes: 40
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-dotnet@67a3573c9a986a3f9c594539f4ab511d57bb3ce9 # v4
with:
dotnet-version: '10.0.x'
- name: Build and test the managed engine, native DLL and clients
shell: pwsh
run: |
$env:MNXBuildNumber = (Get-Content BuildNumber.txt).Trim()
$env:MNXReleaseRoot = Join-Path $env:RUNNER_TEMP 'release'
./build.ps1 -Runtime win-x64 -Test
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: mnxfile-win-x64
path: ${{ runner.temp }}/release/win-x64/
if-no-files-found: error
2 changes: 1 addition & 1 deletion BuildNumber.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
10
11
4 changes: 2 additions & 2 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
<RepositoryType>git</RepositoryType>
<PackageProjectUrl>https://github.com/Mashrien/MNXFile</PackageProjectUrl>
<PackageLicenseExpression>GPL-3.0-only</PackageLicenseExpression>
<MNXVersionPrefix>1.3.1</MNXVersionPrefix>
<MNXVersionPrefix>1.4.0</MNXVersionPrefix>
<MNXCounterFile>$(MSBuildThisFileDirectory)BuildNumber.txt</MNXCounterFile>
<MNXBuildNumberReserved Condition="'$(MNXBuildNumber)' != ''">true</MNXBuildNumberReserved>
<MNXBuildNumber Condition="'$(MNXBuildNumber)' == ''">$([System.IO.File]::ReadAllText('$(MNXCounterFile)').Trim())</MNXBuildNumber>
<Version>$(MNXVersionPrefix)-alpha.$(MNXBuildNumber)</Version>
<Version>$(MNXVersionPrefix)</Version>
<InformationalVersion>$(Version)</InformationalVersion>
<AssemblyVersion>$(MNXVersionPrefix).$(MNXBuildNumber)</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.targets
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@
</MNXAllocateBuildNumber>
<PropertyGroup>
<MNXBuildNumberReserved>true</MNXBuildNumberReserved>
<Version>$(MNXVersionPrefix)-alpha.$(MNXBuildNumber)</Version>
<Version>$(MNXVersionPrefix)</Version>
<InformationalVersion>$(Version)</InformationalVersion>
<AssemblyVersion>$(MNXVersionPrefix).$(MNXBuildNumber)</AssemblyVersion>
<FileVersion>$(AssemblyVersion)</FileVersion>
Expand Down
117 changes: 27 additions & 90 deletions MNX/Archive.cs
Original file line number Diff line number Diff line change
Expand Up @@ -663,84 +663,29 @@ public byte[] ReadFileRange(Guid id, long offset, int count) {

lock (_state.SyncRoot) {
CheckOpen();
VFile? file = RequireFile(id);
if (UsesStreamCompression) {
if ((ulong)offset >= file.SizeOriginal || count == 0) {
return Array.Empty<byte>();
}

int length = (int)Math.Min((ulong)count, file.SizeOriginal - (ulong)offset);
byte[] data = new byte[length];
using ContinuousArchiveReadStream decoded = new ContinuousArchiveReadStream(this, file);
decoded.Seek(offset, SeekOrigin.Begin);
decoded.ReadExactly(data);
return data;
}

using FileStream archive = DiskFile.OpenRead(_state.Path!);
return ReadFileRangeCore(archive, file, offset, count);
}
}

private byte[] ReadFileRangeCore(Stream archive, VFile file, long offset, int count) {
if ((ulong)offset >= file.SizeOriginal || count == 0) {
return Array.Empty<byte>();
}

int length = (int)Math.Min((ulong)count, file.SizeOriginal - (ulong)offset);
byte[] output = new byte[length];
int copied = 0;
long cursor = offset;
while (copied < length) {
uint sequence;
int within;
(sequence, within) = file.LocateByte((ulong)cursor);
uint index = file.PhysicalChunk(sequence);
byte[] payload = ChunkFormat.ReadChunk(
archive,
index,
out ChunkHeader slot,
_state.Codec,
LogicalChunkLength(file, sequence),
_state.ChunkSize
);
if (slot.Id != file.FileID || slot.Sequence != sequence) {
throw new InvalidDataException("Chunk does not match the file index.");
}

if (within >= payload.Length) {
throw new InvalidDataException("Chunk length does not cover the requested offset.");
VFile file = RequireFile(id);
if ((ulong)offset >= file.SizeOriginal || count == 0) {
return Array.Empty<byte>();
}

int take = Math.Min(length - copied, payload.Length - within);
payload.AsSpan(within, take).CopyTo(output.AsSpan(copied));
copied += take;
cursor += take;
int length = (int)Math.Min((ulong)count, file.SizeOriginal - (ulong)offset);
byte[] data = new byte[length];
using Stream reader = CreateReadStream(file);
reader.Position = offset;
reader.ReadExactly(data);
return data;
}

return output;
}

/// <summary>Read a chunk payload; continuous compression returns a slice of the compressed file stream.</summary>
public byte[] GetFileChunk(Guid id, uint sequence) {
lock (_state.SyncRoot) {
CheckOpen();
VFile? file = RequireFile(id);
uint index = file.PhysicalChunk(sequence);
using FileStream archive = DiskFile.OpenRead(_state.Path!);
byte[] payload = ChunkFormat.ReadChunk(
archive,
index,
out ChunkHeader slot,
_state.Codec,
LogicalChunkLength(file, sequence),
_state.ChunkSize
);
if (slot.Id != id || slot.Sequence != sequence) {
throw new InvalidDataException("Chunk does not match the file index.");
if (sequence >= file.ChunkCount) {
throw new ArgumentOutOfRangeException(nameof(sequence));
}

return payload;
using ChunkReadWindow reader = new ChunkReadWindow(this, file);
return reader.Read(sequence, 1);
}
}

Expand All @@ -749,7 +694,7 @@ public ReturnCode VerifyArchive() {
lock (_state.SyncRoot) {
CheckOpen();
try {
using FileStream archive = DiskFile.OpenRead(_state.Path!);
using FileStream archive = ChunkReadWindow.OpenInput(this);
ArchiveFormat.HeaderInfo? header = ArchiveFormat.ReadHeader(archive);
if (header.version == 7) {
archive.Position = _state.ChunkSize;
Expand Down Expand Up @@ -791,22 +736,10 @@ public ReturnCode VerifyArchive() {
occupiedChunks = checked(occupiedChunks + extent.Count);
}
ulong size = 0;
using ChunkReadWindow reader = new ChunkReadWindow(this, file, archive);
for (uint sequence = 0; sequence < file.ChunkCount; sequence++) {
uint index = file.PhysicalChunk(sequence);
byte[] payload = ChunkFormat.ReadChunk(
archive,
index,
out ChunkHeader slot,
_state.Codec,
LogicalChunkLength(file, sequence),
_state.ChunkSize
);
uint expectedNext = sequence + 1 < file.ChunkCount ? file.PhysicalChunk(sequence + 1) : 0;
if (payload.Length != LogicalChunkLength(file, sequence) || slot.Id != file.FileID || slot.Sequence != sequence || slot.Next != expectedNext || (sequence == 0 && slot.Type != (file.IsDirectory ? NodeType.Directory : NodeType.File)) || (sequence > 0 && slot.Type != NodeType.Continuation)) {
throw new InvalidDataException($"Chunk chain mismatch for {file.Name}.");
}

size += (uint)LogicalChunkLength(file, sequence);
byte[] payload = reader.Read(sequence, file.ChunkCount - sequence);
size += (uint)payload.Length;
checkedBytes += _state.ChunkSize;
if (progressTimer.ElapsedMilliseconds >= Options.ProgressReportFrequency) {
RaiseProgress("verify", checkedBytes, totalBytes);
Expand All @@ -820,7 +753,7 @@ public ReturnCode VerifyArchive() {

if (UsesStreamCompression && !file.IsDirectory) {
using ContinuousArchiveReadStream decoded = new ContinuousArchiveReadStream(this, file);
byte[] buffer = new byte[64 * 1024];
byte[] buffer = CreateTransferBuffer(file.SizeOriginal);
long remaining = checked((long)file.SizeOriginal);
while (remaining > 0) {
int read = decoded.Read(buffer, 0, (int)Math.Min(buffer.Length, remaining));
Expand Down Expand Up @@ -867,11 +800,14 @@ private void ValidateParentChain(VFile file) {
public Stream OpenRead(Guid id) {
lock (_state.SyncRoot) {
CheckOpen();
VFile? file = RequireFile(id);
return UsesStreamCompression ? new ContinuousArchiveReadStream(this, file) : new ArchiveReadStream(this, file);
return CreateReadStream(RequireFile(id));
}
}

private Stream CreateReadStream(VFile file) {
return UsesStreamCompression ? new ContinuousArchiveReadStream(this, file) : new ArchiveReadStream(this, file);
}

/// <summary>Copy a file range through a fixed-size buffer without materializing the range.</summary>
public long CopyFileRange(Guid id, Stream destination, long offset, long length, int bufferSize = 64 * 1024) {
ArgumentNullException.ThrowIfNull(destination);
Expand Down Expand Up @@ -931,7 +867,7 @@ public ReturnCode ExtractFile(Guid id, FileInfo destination, bool? overwrite = n
FileMode mode = overwrite ?? Options.OverrideByDefault ? FileMode.Create : FileMode.CreateNew;
using (FileStream output = new FileStream(destination.FullName, mode, FileAccess.Write, FileShare.None)) {
outputOpened = true;
byte[] buffer = new byte[64 * 1024];
byte[] buffer = CreateTransferBuffer(file.SizeOriginal);
long completed = 0;
while (true) {
Options.CancellationToken.ThrowIfCancellationRequested();
Expand Down Expand Up @@ -1175,8 +1111,9 @@ private static Attribs MapAttributes(FileAttributes attributes) {
return result;
}

private int LogicalChunkLength(VFile file, uint sequence) {
return file.LogicalLength(sequence);
private byte[] CreateTransferBuffer(ulong fileSize) {
int capacity = Options.ReadWorkers == 1 ? 64 * 1024 : Options.ReadWorkers * ChunkReadWindow.BytesPerWorker;
return new byte[(int)Math.Clamp(fileSize, 1, (ulong)capacity)];
}

private static VFile FromSource(Guid id, Guid parent, string name, FileSystemInfo source, bool directory, ulong size, uint first) => FromMetadata(id, parent, name, SourceMetadata(source), directory, size, first);
Expand Down
137 changes: 137 additions & 0 deletions MNX/Archive/Chunks/ChunkReadWindow.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
using System.Buffers;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;
using MNX.Codecs;

namespace MNX.Storage;

/// <summary>Reads adjacent disk chunks in batches and delivers validated payloads in file order.</summary>
internal sealed class ChunkReadWindow(Archive owner, VFile file, FileStream input) : IDisposable {
internal const int BytesPerWorker = 256 * 1024;
private readonly bool _ownsInput;
private byte[][] _payloads = [];
private uint _first;
private bool _singleChunkOnly;

internal ChunkReadWindow(Archive owner, VFile file)
: this(owner, file, OpenInput(owner)) {
_ownsInput = true;
}

internal static FileStream OpenInput(Archive owner) {
return new FileStream(owner.State.Path!, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 1, FileOptions.Asynchronous | FileOptions.RandomAccess);
}

// The coordinator holds the archive gate until every worker has completed.
// Workers use positional I/O and never acquire the gate or invoke a user callback.
internal byte[] Read(uint sequence, uint requestedChunks) {
CancellationToken cancellation = owner.Options.CancellationToken;
cancellation.ThrowIfCancellationRequested();
if (sequence >= _first && sequence - _first < _payloads.Length) {
return _payloads[sequence - _first];
}

int workers = owner.Options.ReadWorkers;
int chunkSize = owner.State.ChunkSize;
int capacity = BytesPerWorker / chunkSize * workers;
uint available = file.ChunkCount - sequence;
int count = (int)Math.Min(Math.Min(requestedChunks, available), (uint)capacity);
_payloads = [];
_first = sequence;
if (workers > 1 && count > 1 && !_singleChunkOnly) {
try {
_payloads = FillWindowAsync(sequence, count, workers, chunkSize, cancellation).GetAwaiter().GetResult();
return _payloads[0];
}
catch (Exception error) when (error is IOException or InvalidDataException or CryptographicException) {
// A decoder can request bytes ahead of the caller. Deliver good earlier chunks
// and report damage when the caller actually reaches the affected sequence.
_singleChunkOnly = true;
}
}

uint physical = file.PhysicalChunk(sequence);
byte[] payload = ChunkFormat.ReadChunk(input, physical, out ChunkHeader header,
owner.State.Codec, file.LogicalLength(sequence), chunkSize);
ValidateChain(sequence, header, payload.Length);
_payloads = [payload];
return payload;
}

private async Task<byte[][]> FillWindowAsync(uint first, int count, int workers, int chunkSize, CancellationToken cancellation) {
int groups = Math.Min(workers, count);
byte[][] ordered = new byte[count][];
Task[] pending = new Task[groups];
SafeFileHandle handle = input.SafeFileHandle;
for (int worker = 0; worker < groups; worker++) {
int begin = count * worker / groups;
int end = count * (worker + 1) / groups;
pending[worker] = ReadGroupAsync(handle, first, begin, end, chunkSize, ordered, cancellation);
}
await Task.WhenAll(pending).ConfigureAwait(false);
return ordered;
}

private async Task ReadGroupAsync(SafeFileHandle handle, uint first, int begin, int end, int chunkSize,
byte[][] ordered, CancellationToken cancellation) {
byte[] buffer = ArrayPool<byte>.Shared.Rent((end - begin) * chunkSize);
try {
ArchiveCodec? codec = owner.State.Codec;
using AesGcm? cipher = codec?.CreateReadCipher();
int cursor = begin;
while (cursor < end) {
cancellation.ThrowIfCancellationRequested();
uint physical = file.PhysicalChunk(first + (uint)cursor);
int run = 1;
while (cursor + run < end && (ulong)physical + (uint)run == file.PhysicalChunk(first + (uint)(cursor + run))) {
run++;
}

long offset = (long)physical * chunkSize;
Memory<byte> remaining = buffer.AsMemory(0, run * chunkSize);
while (!remaining.IsEmpty) {
int read = await RandomAccess.ReadAsync(handle, remaining, offset, cancellation).ConfigureAwait(false);
if (read == 0) {
throw new EndOfStreamException("The archive ended inside a chunk.");
}
offset += read;
remaining = remaining.Slice(read);
}

for (int slot = 0; slot < run; slot++) {
cancellation.ThrowIfCancellationRequested();
uint sequence = first + (uint)cursor;
ordered[cursor] = ChunkFormat.DecodeChunk(buffer.AsSpan(slot * chunkSize, chunkSize),
physical + (uint)slot, out ChunkHeader header, codec, file.LogicalLength(sequence), cipher);
ValidateChain(sequence, header, ordered[cursor].Length);
cursor++;
}
}
}
finally {
ArrayPool<byte>.Shared.Return(buffer);
}
}

private void ValidateChain(uint sequence, in ChunkHeader header, int payloadLength) {
if (payloadLength != file.LogicalLength(sequence)) {
throw new InvalidDataException($"Chunk length mismatch for {file.Name} at sequence {sequence}.");
}
NodeType expectedType = NodeType.Continuation;
if (sequence == 0) {
expectedType = file.IsDirectory ? NodeType.Directory : NodeType.File;
}
uint next = sequence + 1 < file.ChunkCount ? file.PhysicalChunk(sequence + 1) : 0;
if (header.Id != file.FileID || header.Sequence != sequence || header.Type != expectedType || header.Next != next) {
throw new InvalidDataException($"Chunk chain mismatch for {file.Name} at sequence {sequence}.");
}
}

public void Dispose() {
_payloads = [];
if (_ownsInput) {
input.Dispose();
}
}
}
Loading
Loading