-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAzureDirectory.cs
More file actions
339 lines (294 loc) · 14.1 KB
/
AzureDirectory.cs
File metadata and controls
339 lines (294 loc) · 14.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
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Azure;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using Ramstack.Globbing;
namespace Ramstack.FileSystem.Azure;
/// <summary>
/// Represents an implementation of <see cref="VirtualDirectory"/> that maps a directory
/// to the path within an Azure Blob Storage container.
/// </summary>
internal sealed class AzureDirectory : VirtualDirectory
{
private readonly AzureFileSystem _fs;
/// <inheritdoc />
public override IVirtualFileSystem FileSystem => _fs;
/// <summary>
/// Initializes a new instance of the <see cref="AzureDirectory"/> class.
/// </summary>
/// <param name="fileSystem">The file system associated with this directory.</param>
/// <param name="path">The path to the directory within the Azure Blob Storage container.</param>
public AzureDirectory(AzureFileSystem fileSystem, string path) : base(path) =>
_fs = fileSystem;
/// <inheritdoc />
protected override ValueTask<VirtualNodeProperties?> GetPropertiesCoreAsync(CancellationToken cancellationToken) =>
new ValueTask<VirtualNodeProperties?>(VirtualNodeProperties.None);
/// <inheritdoc />
protected override ValueTask<bool> ExistsCoreAsync(CancellationToken cancellationToken) =>
new ValueTask<bool>(true);
/// <inheritdoc />
protected override ValueTask CreateCoreAsync(CancellationToken cancellationToken) =>
default;
/// <inheritdoc />
protected override async ValueTask DeleteCoreAsync(CancellationToken cancellationToken)
{
var collection = _fs.AzureClient
.GetBlobsAsync(
prefix: GetPrefix(FullName),
cancellationToken: cancellationToken);
var client = _fs.AzureClient.GetBlobBatchClient();
var batch = client.CreateBatch();
// https://learn.microsoft.com/en-us/rest/api/storageservices/blob-batch#remarks
// Each batch request supports a maximum of 256 sub requests.
const int MaxSubRequests = 256;
await foreach (var page in collection.AsPages().WithCancellation(cancellationToken).ConfigureAwait(false))
{
foreach (var blob in page.Values)
{
batch.DeleteBlob(_fs.AzureClient.Name, blob.Name, DeleteSnapshotsOption.IncludeSnapshots, conditions: null);
if (batch.RequestCount != MaxSubRequests)
continue;
await DeleteBlobsAsync(client, batch, cancellationToken).ConfigureAwait(false);
batch = client.CreateBatch();
}
}
if (batch.RequestCount != 0)
await DeleteBlobsAsync(client, batch, cancellationToken).ConfigureAwait(false);
static async ValueTask DeleteBlobsAsync(BlobBatchClient client, BlobBatch batch, CancellationToken cancellationToken)
{
try
{
await client.SubmitBatchAsync(batch, throwOnAnyFailure: true, cancellationToken).ConfigureAwait(false);
}
catch (AggregateException e) when (Processed(e.InnerExceptions))
{
}
finally
{
batch.Dispose();
}
static bool Processed(ReadOnlyCollection<Exception> exceptions)
{
for (int count = exceptions.Count, i = 0; i < count; i++)
if (exceptions[i] is not RequestFailedException { Status: 404 })
return false;
return true;
}
}
}
/// <inheritdoc />
protected override async IAsyncEnumerable<VirtualNode> GetFileNodesCoreAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
var collection = _fs.AzureClient
.GetBlobsByHierarchyAsync(
delimiter: "/",
prefix: GetPrefix(FullName),
cancellationToken: cancellationToken);
await foreach (var page in collection.AsPages().WithCancellation(cancellationToken).ConfigureAwait(false))
foreach (var item in page.Values)
yield return item.Prefix is not null
? new AzureDirectory(_fs, VirtualPath.Normalize(item.Prefix))
: CreateVirtualFile(item.Blob);
}
/// <inheritdoc />
protected override async IAsyncEnumerable<VirtualFile> GetFilesCoreAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
var collection = _fs.AzureClient
.GetBlobsByHierarchyAsync(
delimiter: "/",
prefix: GetPrefix(FullName),
cancellationToken: cancellationToken);
await foreach (var page in collection.AsPages().WithCancellation(cancellationToken).ConfigureAwait(false))
foreach (var item in page.Values)
if (item.Prefix is null)
yield return CreateVirtualFile(item.Blob);
}
/// <inheritdoc />
protected override async IAsyncEnumerable<VirtualDirectory> GetDirectoriesCoreAsync([EnumeratorCancellation] CancellationToken cancellationToken)
{
var collection = _fs.AzureClient
.GetBlobsByHierarchyAsync(
delimiter: "/",
prefix: GetPrefix(FullName),
cancellationToken: cancellationToken);
await foreach (var page in collection.AsPages().WithCancellation(cancellationToken).ConfigureAwait(false))
foreach (var item in page.Values)
if (item.Prefix is not null)
yield return new AzureDirectory(_fs, VirtualPath.Normalize(item.Prefix));
}
/// <inheritdoc />
protected override async IAsyncEnumerable<VirtualNode> GetFileNodesCoreAsync(string[] patterns, string[]? excludes, [EnumeratorCancellation] CancellationToken cancellationToken)
{
//
// Cloud storage optimization strategy:
// 1. List all blobs in one batch using prefix filtering (matches our virtual directory).
// 2. Perform pattern matching and exclusion filters locally.
//
// Benefits:
// - Single API call instead of per-directory requests
// - Reduced network latency, especially for deep directory structures
// - More efficient than recursive directory scanning
//
var prefix = GetPrefix(FullName);
var directories = new HashSet<string> { FullName };
await foreach (var page in _fs.AzureClient
.GetBlobsAsync(prefix: prefix, cancellationToken: cancellationToken)
.AsPages()
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
foreach (var blob in page.Values)
{
var path = VirtualPath.Normalize(blob.Name);
var directoryPath = VirtualPath.GetDirectoryName(path);
while (directoryPath.Length != 0 && directories.Add(directoryPath))
{
//
// Directories are yielded in reverse order (deepest first).
//
// Note: We could use a Stack<string> to control the order,
// but since order isn't guaranteed anyway and to avoid
// unnecessary memory allocation, we process them directly.
//
if (IsMatched(directoryPath.AsSpan(FullName.Length), patterns, excludes))
yield return new AzureDirectory(_fs, directoryPath);
directoryPath = VirtualPath.GetDirectoryName(directoryPath);
}
if (IsMatched(blob.Name.AsSpan(prefix.Length), patterns, excludes))
yield return CreateVirtualFile(blob, path);
}
}
}
/// <inheritdoc />
protected override async IAsyncEnumerable<VirtualFile> GetFilesCoreAsync(string[] patterns, string[]? excludes, [EnumeratorCancellation] CancellationToken cancellationToken)
{
//
// Cloud storage optimization strategy:
// 1. List all blobs in one batch using prefix filtering (matches our virtual directory).
// 2. Perform pattern matching and exclusion filters locally.
//
// Benefits:
// - Single API call instead of per-directory requests
// - Reduced network latency, especially for deep directory structures
// - More efficient than recursive directory scanning
//
var prefix = GetPrefix(FullName);
await foreach (var page in _fs.AzureClient
.GetBlobsAsync(prefix: prefix, cancellationToken: cancellationToken)
.AsPages()
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
foreach (var blob in page.Values)
if (IsMatched(blob.Name.AsSpan(prefix.Length), patterns, excludes))
yield return CreateVirtualFile(blob);
}
}
/// <inheritdoc />
protected override async IAsyncEnumerable<VirtualDirectory> GetDirectoriesCoreAsync(string[] patterns, string[]? excludes, [EnumeratorCancellation] CancellationToken cancellationToken)
{
//
// Cloud storage optimization strategy:
// 1. List all blobs in one batch using prefix filtering (matches our virtual directory).
// 2. Perform pattern matching and exclusion filters locally.
//
// Benefits:
// - Single API call instead of per-directory requests
// - Reduced network latency, especially for deep directory structures
// - More efficient than recursive directory scanning
//
var prefix = GetPrefix(FullName);
var directories = new HashSet<string> { FullName };
await foreach (var page in _fs.AzureClient
.GetBlobsAsync(prefix: prefix, cancellationToken: cancellationToken)
.AsPages()
.WithCancellation(cancellationToken)
.ConfigureAwait(false))
{
foreach (var blob in page.Values)
{
var directoryPath = VirtualPath.GetDirectoryName(
VirtualPath.Normalize(blob.Name));
while (directoryPath.Length != 0 && directories.Add(directoryPath))
{
//
// Directories are yielded in reverse order (deepest first).
//
// Note: We could use a Stack<string> to control the order,
// but since order isn't guaranteed anyway and to avoid
// unnecessary memory allocation, we process them directly.
//
if (IsMatched(directoryPath.AsSpan(FullName.Length), patterns, excludes))
yield return new AzureDirectory(_fs, directoryPath);
directoryPath = VirtualPath.GetDirectoryName(directoryPath);
}
}
}
}
/// <summary>
/// Creates a <see cref="AzureFile"/> instance based on the specified blob item.
/// </summary>
/// <param name="blob">The <see cref="BlobItem"/> representing the file.</param>
/// <param name="normalizedPath">The normalized name of the blob.</param>
/// <returns>
/// A new <see cref="AzureFile"/> instance representing the file.
/// </returns>
private AzureFile CreateVirtualFile(BlobItem blob, string? normalizedPath = null)
{
var info = blob.Properties;
var properties = VirtualNodeProperties.CreateFileProperties(
creationTime: info.CreatedOn.GetValueOrDefault(),
lastAccessTime: info.LastAccessedOn.GetValueOrDefault(),
lastWriteTime: info.LastModified.GetValueOrDefault(),
length: info.ContentLength.GetValueOrDefault(defaultValue: -1));
var path = normalizedPath ?? VirtualPath.Normalize(blob.Name);
return new AzureFile(_fs, path, properties);
}
/// <summary>
/// Determines whether the specified path matches any of the inclusion patterns and none of the exclusion patterns.
/// </summary>
/// <param name="path">The path to match.</param>
/// <param name="patterns">The inclusion patterns to match against the path.</param>
/// <param name="excludes">An optional array of exclusion patterns. If the path matches any of these,
/// the method returns <see langword="false"/>.</param>
/// <returns>
/// <see langword="true"/> if the path matches at least one inclusion pattern and no exclusion patterns;
/// otherwise, <see langword="false"/>.
/// </returns>
private static bool IsMatched(scoped ReadOnlySpan<char> path, string[] patterns, string[]? excludes)
{
if (excludes is not null)
foreach (var pattern in excludes)
if (Matcher.IsMatch(path, pattern, MatchFlags.Unix))
return false;
foreach (var pattern in patterns)
if (Matcher.IsMatch(path, pattern, MatchFlags.Unix))
return true;
return false;
}
/// <summary>
/// Returns a cloud storage compatible prefix for the specified directory path.
/// </summary>
/// <param name="path">The directory path.</param>
/// <returns>
/// A string formatted for cloud storage prefix filtering:
/// <list type="bullet">
/// <item><description>Empty string for the root directory ("/")</description></item>
/// <item><description>Path without leading slash but with trailing slash for subdirectories</description></item>
/// </list>
/// </returns>
/// <example>
/// <code>
/// GetPrefix("/") // returns ""
/// GetPrefix("/folder") // returns "folder/"
/// GetPrefix("/sub/folder") // returns "sub/folder/"
/// </code>
/// </example>
private static string GetPrefix(string path)
{
Debug.Assert(VirtualPath.IsNormalized(path));
return path == "/" ? "" : $"{path[1..]}/";
}
}