-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLocalFileSystemStore.cs
More file actions
400 lines (320 loc) · 12.1 KB
/
Copy pathLocalFileSystemStore.cs
File metadata and controls
400 lines (320 loc) · 12.1 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
using ZarrNET.Core.Zarr;
namespace ZarrNET.Core.Zarr.Store;
/// <summary>
/// IZarrStore backed by the local filesystem. Keys map directly to
/// relative paths under the root directory, using the OS path separator.
/// </summary>
public sealed class LocalFileSystemStore : IZarrStore, IDisposable
{
private readonly string _rootPath;
private bool _disposed;
public string RootPath => _rootPath;
public void Dispose()
{
DisposeAsync();
}
public LocalFileSystemStore(string rootPath)
{
var expanded = Path.GetFullPath(rootPath);
if (!Directory.Exists(expanded))
throw new DirectoryNotFoundException($"Zarr store root not found: {expanded}");
_rootPath = expanded;
}
// -------------------------------------------------------------------------
// IZarrStore
// -------------------------------------------------------------------------
public async Task<byte[]?> ReadAsync(string key, CancellationToken ct = default)
{
ThrowIfDisposed();
var fullPath = ResolveKey(key);
if (!File.Exists(fullPath))
return null;
var data = await File.ReadAllBytesAsync(fullPath, ct).ConfigureAwait(false);
return data;
}
public async Task<int?> ReadAsync(string key, Memory<byte> destination, CancellationToken ct = default)
{
ThrowIfDisposed();
var fullPath = ResolveKey(key);
if (!File.Exists(fullPath))
return null;
var length = checked((int)new FileInfo(fullPath).Length);
if (length > destination.Length)
throw new ArgumentException(
$"Destination has {destination.Length} bytes, but key '{key}' contains {length} bytes.",
nameof(destination));
await using var stream = new FileStream(
fullPath,
FileMode.Open,
FileAccess.Read,
FileShare.Read,
bufferSize: 1024 * 1024,
FileOptions.Asynchronous | FileOptions.SequentialScan);
var offset = 0;
while (offset < length)
{
var read = await stream.ReadAsync(destination[offset..length], ct).ConfigureAwait(false);
if (read == 0)
throw new IOException(
$"Short read for '{fullPath}': expected {length} bytes but received {offset} bytes.");
offset += read;
}
return length;
}
public async Task WriteAsync(string key, byte[] data, CancellationToken ct = default)
{
await WriteAsync(key, data.AsMemory(), ct).ConfigureAwait(false);
}
public async Task WriteAsync(string key, ReadOnlyMemory<byte> data, CancellationToken ct = default)
{
ThrowIfDisposed();
var fullPath = ResolveKey(key);
var directory = Path.GetDirectoryName(fullPath)!;
Directory.CreateDirectory(directory);
await using (var stream = new FileStream(
fullPath,
FileMode.Create,
FileAccess.Write,
FileShare.None,
bufferSize: 1024 * 1024,
FileOptions.Asynchronous | FileOptions.SequentialScan))
{
await stream.WriteAsync(data, ct).ConfigureAwait(false);
}
}
public Task WriteManyAsync(
IEnumerable<ZarrStoreWrite> writes,
int maxDegreeOfParallelism,
CancellationToken ct = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(writes);
if (maxDegreeOfParallelism < 1)
throw new ArgumentOutOfRangeException(
nameof(maxDegreeOfParallelism),
maxDegreeOfParallelism,
"Maximum degree of parallelism must be at least 1.");
var writeList = writes as IReadOnlyList<ZarrStoreWrite> ?? writes.ToArray();
var plannedWrites = new LocalWrite[writeList.Count];
for (var i = 0; i < writeList.Count; i++)
{
ct.ThrowIfCancellationRequested();
var write = writeList[i];
plannedWrites[i] = PlanBatchWrite(write);
}
var directories = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < plannedWrites.Length; i++)
{
ct.ThrowIfCancellationRequested();
directories.Add(plannedWrites[i].Directory);
}
foreach (var directory in directories)
{
ct.ThrowIfCancellationRequested();
Directory.CreateDirectory(directory);
}
var options = new ParallelOptions
{
MaxDegreeOfParallelism = maxDegreeOfParallelism,
CancellationToken = ct
};
Parallel.For(
0,
plannedWrites.Length,
options,
i =>
{
ct.ThrowIfCancellationRequested();
var write = plannedWrites[i];
using var stream = new FileStream(
write.FullPath,
FileMode.Create,
FileAccess.Write,
FileShare.None,
bufferSize: 1024 * 1024,
FileOptions.SequentialScan);
stream.Write(write.Data.Span);
});
return Task.CompletedTask;
}
internal Task WriteDecodedChunksAsync(
IReadOnlyList<ZarrDecodedChunkWrite> chunks,
Func<ZarrChunkRef, string> keySelector,
int maxDegreeOfParallelism,
CancellationToken ct = default)
{
ThrowIfDisposed();
ArgumentNullException.ThrowIfNull(chunks);
ArgumentNullException.ThrowIfNull(keySelector);
if (maxDegreeOfParallelism < 1)
throw new ArgumentOutOfRangeException(
nameof(maxDegreeOfParallelism),
maxDegreeOfParallelism,
"Maximum degree of parallelism must be at least 1.");
var plannedWrites = new LocalWrite[chunks.Count];
for (var i = 0; i < chunks.Count; i++)
{
ct.ThrowIfCancellationRequested();
var chunk = chunks[i];
plannedWrites[i] = PlanBatchWrite(keySelector(chunk.Chunk), chunk.DecodedBytes);
}
var directories = new HashSet<string>(StringComparer.Ordinal);
for (var i = 0; i < plannedWrites.Length; i++)
{
ct.ThrowIfCancellationRequested();
directories.Add(plannedWrites[i].Directory);
}
foreach (var directory in directories)
{
ct.ThrowIfCancellationRequested();
Directory.CreateDirectory(directory);
}
var options = new ParallelOptions
{
MaxDegreeOfParallelism = maxDegreeOfParallelism,
CancellationToken = ct
};
Parallel.For(
0,
plannedWrites.Length,
options,
i =>
{
ct.ThrowIfCancellationRequested();
var write = plannedWrites[i];
using var stream = new FileStream(
write.FullPath,
FileMode.Create,
FileAccess.Write,
FileShare.None,
bufferSize: 1024 * 1024,
FileOptions.SequentialScan);
stream.Write(write.Data.Span);
});
return Task.CompletedTask;
}
public Task<bool> ExistsAsync(string key, CancellationToken ct = default)
{
ThrowIfDisposed();
ct.ThrowIfCancellationRequested();
var fullPath = ResolveKey(key);
var exists = File.Exists(fullPath) || Directory.Exists(fullPath);
return Task.FromResult(exists);
}
public Task<IReadOnlyList<string>> ListAsync(string prefix = "", CancellationToken ct = default)
{
ThrowIfDisposed();
ct.ThrowIfCancellationRequested();
var searchRoot = string.IsNullOrEmpty(prefix)
? _rootPath
: ResolveKey(prefix);
if (!Directory.Exists(searchRoot))
return Task.FromResult<IReadOnlyList<string>>(Array.Empty<string>());
var allFiles = Directory
.EnumerateFiles(searchRoot, "*", SearchOption.AllDirectories)
.Select(absPath => ToStoreKey(absPath))
.OrderBy(k => k)
.ToList();
return Task.FromResult<IReadOnlyList<string>>(allFiles);
}
public Task DeleteAsync(string key, CancellationToken ct = default)
{
ThrowIfDisposed();
ct.ThrowIfCancellationRequested();
var fullPath = ResolveKey(key);
if (File.Exists(fullPath))
File.Delete(fullPath);
return Task.CompletedTask;
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
/// <summary>
/// Converts a store key (forward-slash separated) to an absolute filesystem path.
/// Guards against path traversal attacks by ensuring the resolved path stays
/// within the store root.
/// </summary>
private string ResolveKey(string key)
{
// Normalise separator and remove any leading slash
var relativePath = key
.Replace('/', Path.DirectorySeparatorChar)
.TrimStart(Path.DirectorySeparatorChar);
var fullPath = Path.GetFullPath(Path.Combine(_rootPath, relativePath));
if (!fullPath.StartsWith(_rootPath, StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(
$"Key '{key}' resolves outside the store root. Possible path traversal.");
return fullPath;
}
private LocalWrite PlanBatchWrite(ZarrStoreWrite write)
=> PlanBatchWrite(write.Key, write.Data);
private LocalWrite PlanBatchWrite(string key, ReadOnlyMemory<byte> data)
{
if (!IsSafeRelativeStoreKey(key))
{
var resolvedPath = ResolveKey(key);
return new LocalWrite(
resolvedPath,
Path.GetDirectoryName(resolvedPath)!,
data);
}
var lastSeparator = key.LastIndexOf('/');
var directory =
lastSeparator < 0
? _rootPath
: Path.Join(_rootPath, key[..lastSeparator]);
var fullPath = Path.Join(_rootPath, key);
return new LocalWrite(fullPath, directory, data);
}
private static bool IsSafeRelativeStoreKey(string key)
{
if (string.IsNullOrEmpty(key))
return false;
if (key[0] == '/' || key[0] == '\\' || Path.IsPathRooted(key))
return false;
var segmentStart = 0;
for (var i = 0; i < key.Length; i++)
{
var c = key[i];
if (c == '\\' || c == ':')
return false;
if (c == '/')
{
if (IsUnsafePathSegment(key, segmentStart, i))
return false;
segmentStart = i + 1;
}
}
return !IsUnsafePathSegment(key, segmentStart, key.Length);
}
private static bool IsUnsafePathSegment(string key, int start, int end)
{
var length = end - start;
return length == 0 ||
length == 1 && key[start] == '.' ||
length == 2 && key[start] == '.' && key[start + 1] == '.';
}
/// <summary>Converts an absolute filesystem path back to a forward-slash store key.</summary>
private string ToStoreKey(string absolutePath)
{
var relative = Path.GetRelativePath(_rootPath, absolutePath);
return relative.Replace(Path.DirectorySeparatorChar, '/');
}
// -------------------------------------------------------------------------
// Disposal
// -------------------------------------------------------------------------
public ValueTask DisposeAsync()
{
_disposed = true;
return ValueTask.CompletedTask;
}
private void ThrowIfDisposed()
{
if (_disposed)
throw new ObjectDisposedException(nameof(LocalFileSystemStore));
}
private readonly record struct LocalWrite(
string FullPath,
string Directory,
ReadOnlyMemory<byte> Data);
}