-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSystemStorage.cs
More file actions
240 lines (194 loc) · 7.45 KB
/
Copy pathFileSystemStorage.cs
File metadata and controls
240 lines (194 loc) · 7.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
using Sa.HybridFileStorage.Domain;
using System.Runtime.CompilerServices;
namespace Sa.HybridFileStorage.FileSystem;
/// <summary>
/// fs://share/tenant/filename
/// </summary>
internal sealed class FileSystemStorage(
FileSystemStorageSettings settings,
TimeProvider? timeProvider = null) : IFileStorage
{
private const string SchemeSeparator = "://";
private readonly string _basePath = Path.TrimEndingDirectorySeparator(
Path.GetFullPath(settings.BasePath));
private readonly string _basePathScope = Path.TrimEndingDirectorySeparator(
Path.GetFullPath(Path.Combine(settings.BasePath, settings.Basket)));
private readonly string _schemePrefix = $"{settings.StorageType}{SchemeSeparator}";
private readonly string _storageType = settings.StorageType;
private readonly bool _isReadOnly = settings.IsReadOnly;
private readonly int _bufferSize = settings.BufferSize;
private readonly TimeProvider _timeProvider = timeProvider ?? TimeProvider.System;
public string Basket => settings.Basket;
public string StorageType => _storageType;
public bool IsReadOnly => _isReadOnly;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsureWritable()
{
if (_isReadOnly)
HybridFileStorageThrowHelper.ThrowWritableException();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool CanProcess(string? fileId)
{
if (string.IsNullOrEmpty(fileId)) return false;
if (!fileId.AsSpan().StartsWith(_schemePrefix.AsSpan(), StringComparison.Ordinal))
return false;
return IsPathWithinBase(GetFullPathFast(fileId));
}
public async Task<StorageResult> UploadAsync(
UploadFileInput metadata,
Stream fileStream,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(fileStream);
EnsureWritable();
metadata.Validate();
string filename = PathSanitizer.SanitizeRelativePath(metadata.FileName);
string relativePath = string.Concat(Basket, "/", metadata.TenantId.ToString(), "/", filename);
string filePath = Path.Combine(_basePath, relativePath);
EnsurePathWithinBase(filePath);
string? directory = Path.GetDirectoryName(filePath);
if (!string.IsNullOrEmpty(directory))
EnsureDirectory(directory);
// Smart preallocation: use actual length when available, fall back to 0 for unknown sizes
long preallocationSize = 1024 * 1024;
if (fileStream.CanSeek && fileStream.Length > 0 && fileStream.Length <= int.MaxValue)
{
preallocationSize = fileStream.Length;
}
await using var fileStreamOutput = new FileStream(filePath, new FileStreamOptions
{
Mode = FileMode.Create,
Access = FileAccess.Write,
Share = FileShare.None,
BufferSize = _bufferSize,
Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
PreallocationSize = (int)preallocationSize
});
await fileStream.CopyToAsync(fileStreamOutput, cancellationToken).ConfigureAwait(false);
return new StorageResult(
FileId: string.Concat(_schemePrefix, relativePath),
AbsoluteUrl: Path.GetFullPath(filePath),
StorageType: _storageType,
UploadedAt: _timeProvider.GetUtcNow());
}
public async Task<bool> DownloadAsync(
string fileId,
Func<Stream, CancellationToken, Task> loadStream,
CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(fileId);
ArgumentNullException.ThrowIfNull(loadStream);
if (!CanProcess(fileId))
return false;
string filePath = GetFullPath(fileId);
EnsurePathWithinBase(filePath);
try
{
await using var fs = new FileStream(filePath, new FileStreamOptions
{
Mode = FileMode.Open,
Access = FileAccess.Read,
Share = FileShare.Read,
BufferSize = _bufferSize,
Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
});
await loadStream(fs, cancellationToken).ConfigureAwait(false);
return true;
}
catch (FileNotFoundException)
{
return false;
}
catch (DirectoryNotFoundException)
{
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private string GetFullPath(string fileId)
{
var filePath = FileIdToPath(fileId);
return Path.IsPathRooted(filePath)
? filePath
: Path.Combine(_basePath, filePath);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private string GetFullPathFast(string fileId)
{
var relativePath = FileIdToPath(fileId);
return Path.Combine(_basePath, relativePath);
}
public async Task<bool> DeleteAsync(string fileId, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(fileId);
EnsureWritable();
if (!CanProcess(fileId))
return false;
var filePath = GetFullPath(fileId);
EnsurePathWithinBase(filePath);
if (!File.Exists(filePath))
return false;
try
{
await FileRetryHelper.RetryAsync(
() => File.Delete(filePath),
cancellationToken: cancellationToken).ConfigureAwait(false);
return true;
}
catch (IOException)
{
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void EnsureDirectory(string? dir)
{
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static string FileIdToPath(string fileId)
{
ArgumentException.ThrowIfNullOrWhiteSpace(fileId);
ReadOnlySpan<char> span = fileId.AsSpan();
int separatorIndex = span.IndexOf(SchemeSeparator.AsSpan());
if (separatorIndex == -1)
HybridFileStorageThrowHelper.ThrowInvalidFileIdFormat();
return span[(separatorIndex + SchemeSeparator.Length)..].ToString();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private bool IsPathWithinBase(string path)
{
return Path.GetFullPath(path)
.AsSpan()
.StartsWith(_basePathScope.AsSpan(), StringComparison.Ordinal);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void EnsurePathWithinBase(string path)
{
if (!IsPathWithinBase(path))
{
HybridFileStorageThrowHelper.ThrowSecurityException(path, _basePath);
}
}
public Task<FileMetadata?> GetMetadataAsync(
string fileId,
CancellationToken cancellationToken = default)
{
if (!CanProcess(fileId))
return Task.FromResult<FileMetadata?>(null);
if (!FileIdParser.TryParse(fileId, out var basket, out var tenantId, out _, out var fileName))
return Task.FromResult<FileMetadata?>(null);
var metadata = new FileMetadata
{
StorageType = StorageType,
Basket = basket,
FileName = fileName,
TenantId = tenantId
};
return Task.FromResult<FileMetadata?>(metadata);
}
}