Repository navigation
Expand file tree
/
Copy pathFileDirectoryBinder.cs
More file actions
1182 lines (1086 loc) · 48.4 KB
/
Copy pathFileDirectoryBinder.cs
File metadata and controls
1182 lines (1086 loc) · 48.4 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2005-2026, OPC Federation AISBL
// SPDX-License-Identifier: MIT
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
namespace Opc.Ua.Server.FileSystem
{
/// <summary>
/// Options that control how a bound FileDirectoryType materialises provider entries.
/// </summary>
public sealed class FileDirectoryBindingOptions
{
/// <summary>
/// Gets or sets a value indicating whether CreateFile and CreateDirectory are exposed as writable operations.
/// </summary>
public bool AllowCreate { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether DeleteFileSystemObject is exposed as a writable operation.
/// </summary>
public bool AllowDelete { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether MoveOrCopy is exposed as a writable operation.
/// </summary>
public bool AllowMoveOrCopy { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether anonymous sessions may modify the bound
/// directory (open for writing, create, delete, move or copy). Defaults to
/// <c>false</c>: only sessions with a non-anonymous user identity may modify it.
/// The nodes materialised below the bound directory carry no RolePermissions of
/// their own, so enable this only when the directory is meant to be writable by
/// every client.
/// </summary>
public bool AllowAnonymousWrite { get; set; }
/// <summary>
/// Gets or sets the maximum number of entries materialised per directory.
/// </summary>
public int MaxEntries { get; set; } = DefaultMaxEntries;
/// <summary>
/// Gets or sets the maximum directory nesting materialised below the bound root.
/// </summary>
public int MaxDepth { get; set; } = 8;
/// <summary>
/// Gets or sets the files one Session can keep open below the bound directory through
/// <c>FileType.Open</c>, 64 by default; zero means no limit. An open beyond it fails
/// with <see cref="StatusCodes.BadTooManyOperations"/>.
/// </summary>
public int MaxOpenFilesPerSession { get; set; } = FileOpenQuota.DefaultMaxOpenFilesPerSession;
/// <summary>
/// Gets or sets the files all Sessions together can keep open below the bound directory
/// through <c>FileType.Open</c>, 1024 by default; zero means no limit. An open beyond it
/// fails with <see cref="StatusCodes.BadTooManyOperations"/>.
/// </summary>
public int MaxOpenFiles { get; set; } = FileOpenQuota.DefaultMaxOpenFiles;
/// <summary>
/// Gets or sets the lifecycle wait limit. Active provider operations and their reservations remain
/// owned after this limit; a subsequent disposal can observe their eventual cleanup outcome.
/// </summary>
public TimeSpan CloseTimeout
{
get => m_closeTimeout;
set => m_closeTimeout = FileHandle.ValidateCloseTimeout(value);
}
internal const int DefaultMaxEntries = 1024;
/// <summary>Bounds lifecycle waiting without shortening provider operation ownership.</summary>
private TimeSpan m_closeTimeout = TimeSpan.FromSeconds(10);
}
/// <summary>
/// Represents an active binding between a FileDirectoryType node and an IFileSystemProvider.
/// </summary>
public interface IFileDirectoryBinding : IAsyncDisposable
{
/// <summary>
/// Gets the bound directory node.
/// </summary>
FileDirectoryState Directory { get; }
/// <summary>
/// Gets the provider that backs the directory node.
/// </summary>
IFileSystemProvider Provider { get; }
/// <summary>
/// Re-reads the provider and reconciles materialised child nodes.
/// </summary>
/// <param name="cancellationToken">The token used to cancel reconciliation.</param>
/// <returns>A task that completes when reconciliation finishes, or reports the refresh failure.</returns>
ValueTask RefreshAsync(CancellationToken cancellationToken = default);
}
/// <summary>
/// Creates bindings that back existing FileDirectoryType nodes with file-system providers.
/// </summary>
/// <remarks>
/// With a ServerSystemContext, bindings observe the server session lifecycle and release the closing
/// session's file handles, including pending opens. The application owns the binding's lifetime and
/// must dispose it when its directory is removed or the node manager shuts down.
/// </remarks>
public interface IFileDirectoryBinder
{
/// <summary>
/// Binds a FileDirectoryType node to a provider and materialises its current contents.
/// </summary>
/// <param name="directory">The existing directory node to bind.</param>
/// <param name="provider">The file-system provider that backs the directory.</param>
/// <param name="context">The system context used to create and register child nodes.</param>
/// <param name="options">The binding options, or null to use the defaults.</param>
/// <param name="registerNode">The callback that registers a materialised node with its node manager.</param>
/// <param name="deregisterNode">The callback that removes a materialised node from its node manager.</param>
/// <param name="cancellationToken">The token used to cancel initial materialisation.</param>
/// <returns>The initialized binding, which the caller must dispose asynchronously.</returns>
ValueTask<IFileDirectoryBinding> BindAsync(
FileDirectoryState directory,
IFileSystemProvider provider,
ISystemContext context,
FileDirectoryBindingOptions? options = null,
Func<NodeState, CancellationToken, ValueTask>? registerNode = null,
Func<NodeState, CancellationToken, ValueTask>? deregisterNode = null,
CancellationToken cancellationToken = default);
}
/// <summary>
/// Default FileDirectoryType binder implementation.
/// </summary>
public sealed class FileDirectoryBinder : IFileDirectoryBinder
{
/// <inheritdoc/>
public async ValueTask<IFileDirectoryBinding> BindAsync(
FileDirectoryState directory,
IFileSystemProvider provider,
ISystemContext context,
FileDirectoryBindingOptions? options = null,
Func<NodeState, CancellationToken, ValueTask>? registerNode = null,
Func<NodeState, CancellationToken, ValueTask>? deregisterNode = null,
CancellationToken cancellationToken = default)
{
if (directory == null)
{
throw new ArgumentNullException(nameof(directory));
}
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var binding = new FileDirectoryBinding(
directory,
provider,
context,
options ?? new FileDirectoryBindingOptions(),
registerNode,
deregisterNode);
bool initialized = false;
try
{
await binding.InitializeAsync(cancellationToken).ConfigureAwait(false);
initialized = true;
return binding;
}
finally
{
if (!initialized)
{
await binding.DisposeAsync().ConfigureAwait(false);
}
}
}
/// <summary>
/// Owns materialized directory nodes, open handles, and serialized provider reconciliation.
/// </summary>
private sealed class FileDirectoryBinding : IFileDirectoryBinding, IFileSystemHost
{
/// <summary>
/// Creates a directory binding with validated materialization limits and an optional node registrar.
/// </summary>
public FileDirectoryBinding(
FileDirectoryState directory,
IFileSystemProvider provider,
ISystemContext context,
FileDirectoryBindingOptions options,
Func<NodeState, CancellationToken, ValueTask>? registerNode,
Func<NodeState, CancellationToken, ValueTask>? deregisterNode)
{
Directory = directory;
Provider = provider;
m_context = context;
m_logger = context.Telemetry.CreateLogger<FileDirectoryBinder>();
m_options = ValidateOptions(options);
m_openQuota = new FileOpenQuota
{
MaxOpenFilesPerSession = m_options.MaxOpenFilesPerSession,
MaxOpenFiles = m_options.MaxOpenFiles
};
m_registerNode = registerNode;
m_deregisterNode = deregisterNode;
m_nodeIdPrefix = "FileDirectoryBinding:" + directory.NodeId;
}
/// <inheritdoc/>
public FileDirectoryState Directory { get; }
/// <inheritdoc/>
public IFileSystemProvider Provider { get; }
/// <inheritdoc/>
public bool AllowCreate => m_options.AllowCreate;
/// <inheritdoc/>
public bool AllowDelete => m_options.AllowDelete;
/// <inheritdoc/>
public bool AllowMoveOrCopy => m_options.AllowMoveOrCopy;
/// <inheritdoc/>
public bool UsesVirtualDirectoryBrowsing => false;
/// <inheritdoc/>
public void RegisterDirectoryCursor(DirectoryCursorOwnership ownership)
{
throw new InvalidOperationException("Materialized bindings do not create directory cursors.");
}
/// <inheritdoc/>
public void CompleteDirectoryCursor(DirectoryCursorOwnership ownership)
{
throw new InvalidOperationException("Materialized bindings do not create directory cursors.");
}
/// <inheritdoc/>
/// <remarks>
/// Materialized bindings never create virtual directory cursors, so there is nothing to join.
/// </remarks>
public void TrackCursorCleanup(Task cleanup)
{
}
/// <inheritdoc/>
public async ValueTask RefreshAsync(CancellationToken cancellationToken = default)
{
if (!TryTrackOperation())
{
return;
}
bool entered = false;
try
{
await m_gate.WaitAsync(cancellationToken).ConfigureAwait(false);
entered = true;
// The binding may have been disposed while this refresh was
// queued behind another one.
if (m_disposed)
{
return;
}
await RefreshCoreAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
CompleteOperation(entered);
}
}
/// <summary>
/// Tears the binding down under the same gate a refresh takes, so a
/// refresh that is in flight or queued completes first. Disposing
/// the gate underneath a refresh would fault its release and let
/// the teardown race the node materialisation.
/// </summary>
public async ValueTask DisposeAsync()
{
Task cleanup;
FileHandle[] handles = [];
TaskCompletionSource<bool>? completion = null;
lock (m_lock)
{
if (m_disposal == null)
{
completion = new(TaskCreationOptions.RunContinuationsAsynchronously);
m_disposal = completion.Task;
handles = [.. m_handles.Values];
}
cleanup = m_disposal;
}
if (completion != null)
{
foreach (FileHandle handle in handles)
{
_ = handle.RequestShutdown();
}
_ = CompleteDisposalAsync(completion);
}
if (await FileHandle.CompletesWithinAsync(cleanup, m_options.CloseTimeout).ConfigureAwait(false))
{
await cleanup.ConfigureAwait(false);
}
}
private async Task CompleteDisposalAsync(TaskCompletionSource<bool> completion)
{
try
{
await DisposeCoreAsync().ConfigureAwait(false);
completion.TrySetResult(true);
}
catch (Exception exception)
{
completion.TrySetException(exception);
}
}
private async ValueTask DisposeCoreAsync()
{
if (!TryTrackOperation(disposing: true))
{
return;
}
bool entered = false;
try
{
await m_gate.WaitAsync().ConfigureAwait(false);
entered = true;
if (m_disposed)
{
return;
}
FileHandle[] handles;
lock (m_lock)
{
m_disposed = true;
m_lookupById = [];
handles = new FileHandle[m_handles.Count];
m_handles.Values.CopyTo(handles, 0);
m_handles.Clear();
}
DetachSessionLifecycle();
DetachDirectoryCallbacks(Directory);
foreach (MaterializedNode entry in m_nodesByPath.Values)
{
DetachCallbacks(entry.Node);
}
List<Task> cleanup = [];
foreach (FileHandle handle in handles)
{
cleanup.Add(handle.RequestShutdown());
}
Task all = Task.WhenAll(cleanup);
Exception? cleanupError = null;
try
{
await all.ConfigureAwait(false);
}
catch
{
cleanupError = all.Exception ?? new AggregateException("File cleanup failed.");
}
await RemoveStaleNodesAsync([], CancellationToken.None).ConfigureAwait(false);
if (cleanupError != null)
{
throw cleanupError;
}
}
finally
{
CompleteOperation(entered);
}
}
/// <inheritdoc/>
public NodeId BuildDirectoryNodeId(string providerPath)
{
return string.IsNullOrEmpty(providerPath)
? Directory.NodeId
: CreateMaterializedNodeId("dir", providerPath);
}
/// <inheritdoc/>
public NodeId BuildFileNodeId(string providerPath)
{
return CreateMaterializedNodeId("file", providerPath);
}
/// <inheritdoc/>
public string CombineProviderPath(string parent, string name)
{
if (string.IsNullOrEmpty(parent))
{
return name;
}
return parent.TrimEnd('/') + "/" + name;
}
/// <inheritdoc/>
public NodeId GetParentNodeId(string providerPath)
{
if (string.IsNullOrEmpty(providerPath))
{
return NodeId.Null;
}
int slash = providerPath.LastIndexOf('/', StringComparison.Ordinal);
string parent = slash < 0 ? string.Empty : providerPath[..slash];
return string.IsNullOrEmpty(parent) ? Directory.NodeId : BuildDirectoryNodeId(parent);
}
/// <inheritdoc/>
public FileHandle? GetOrCreateHandle(NodeId nodeId, string providerPath)
{
if (nodeId.NamespaceIndex != Directory.NodeId.NamespaceIndex)
{
return null;
}
EnsureSessionLifecycle();
string identity = FileSystemDirectoryOperations.GetPathIdentity(Provider, providerPath);
lock (m_lock)
{
if (m_disposed || m_disposal != null)
{
return null;
}
if (m_handles.TryGetValue(identity, out FileHandle? handle))
{
return handle;
}
handle = new FileHandle(Provider, providerPath, IsSessionTerminated)
{
CloseTimeout = m_options.CloseTimeout,
OpenQuota = m_openQuota
};
FileSystemDirectoryOperations.BlockForRunningMutations(Provider, m_mutations, handle);
m_handles.Add(identity, handle);
return handle;
}
}
/// <inheritdoc/>
public FileHandle? FindHandle(string providerPath)
{
string identity = FileSystemDirectoryOperations.GetPathIdentity(Provider, providerPath);
lock (m_lock)
{
return !m_disposed && m_disposal == null &&
m_handles.TryGetValue(identity, out FileHandle? handle) ? handle : null;
}
}
/// <inheritdoc/>
public void ReleaseHandle(FileHandle handle)
{
string identity = FileSystemDirectoryOperations.GetPathIdentity(Provider, handle.ProviderPath);
lock (m_lock)
{
if (m_handles.TryGetValue(identity, out FileHandle? current) &&
ReferenceEquals(current, handle) &&
handle.TryRetire())
{
m_handles.Remove(identity);
}
}
}
/// <inheritdoc/>
public void ForgetHandle(NodeId nodeId)
{
FileHandle? retired = null;
lock (m_lock)
{
if (m_lookupById.TryGetValue(nodeId, out MaterializedNode? entry))
{
string identity = FileSystemDirectoryOperations.GetPathIdentity(Provider, entry.ProviderPath);
if (m_handles.TryGetValue(identity, out retired))
{
m_handles.Remove(identity);
}
}
}
retired?.Dispose();
}
/// <inheritdoc/>
public bool TryBeginMutation(string providerPath)
{
lock (m_lock)
{
return FileSystemDirectoryOperations.TryBeginMutation(
Provider, m_handles.Values, m_mutations, providerPath);
}
}
/// <inheritdoc/>
public void EndMutation(string providerPath)
{
lock (m_lock)
{
FileSystemDirectoryOperations.EndMutation(
Provider, m_handles.Values, m_mutations, providerPath);
}
}
/// <inheritdoc/>
/// <remarks>
/// The bound directory lives in the integrator's address space, but the
/// nodes materialised below it carry no RolePermissions, so anonymous
/// sessions are denied unless the binding options allow them.
/// </remarks>
public bool CanUserWrite(ISystemContext context)
{
return m_options.AllowAnonymousWrite ||
FileSystemDirectoryOperations.IsNonAnonymousOrInternal(context);
}
/// <inheritdoc/>
public async ValueTask ApplyMutationAsync(
FileSystemMutationKind kind,
string path,
string targetPath,
NodeId sourceNodeId,
CancellationToken cancellationToken)
{
if (!TryTrackOperation())
{
throw new ServiceResultException(StatusCodes.BadShutdown);
}
bool entered = false;
try
{
await m_gate.WaitAsync(cancellationToken).ConfigureAwait(false);
entered = true;
if (m_disposed)
{
throw new ServiceResultException(StatusCodes.BadShutdown);
}
if (m_refreshRequired)
{
await RefreshForMutationAsync(mutationCommitted: false, cancellationToken)
.ConfigureAwait(false);
}
await CheckCapacityAsync(kind, path, targetPath, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
await FileSystemDirectoryOperations.ApplyProviderMutationAsync(
this, kind, path, targetPath, sourceNodeId, cancellationToken).ConfigureAwait(false);
await RefreshForMutationAsync(mutationCommitted: true, cancellationToken).ConfigureAwait(false);
}
finally
{
CompleteOperation(entered);
}
}
/// <inheritdoc/>
public bool TryGetProviderPath(
NodeId nodeId,
out string providerPath,
out bool isDirectory,
out bool isRoot)
{
lock (m_lock)
{
if (!m_disposed)
{
if (nodeId == Directory.NodeId)
{
providerPath = string.Empty;
isDirectory = true;
isRoot = true;
return true;
}
if (m_lookupById.TryGetValue(nodeId, out MaterializedNode? entry))
{
providerPath = entry.ProviderPath;
isDirectory = entry.IsDirectory;
isRoot = false;
return true;
}
}
}
providerPath = string.Empty;
isDirectory = false;
isRoot = false;
return false;
}
/// <summary>
/// Wires directory methods and completes the initial provider reconciliation before publishing the binding.
/// </summary>
public async ValueTask InitializeAsync(CancellationToken cancellationToken)
{
WireDirectoryCallbacks(Directory, providerPath: string.Empty);
m_initializing = true;
try
{
await RefreshAsync(cancellationToken).ConfigureAwait(false);
}
finally
{
m_initializing = false;
}
}
/// <summary>
/// Attaches lazily because address-space setup can precede creation of the server session manager.
/// </summary>
private void EnsureSessionLifecycle()
{
// SessionManager raises callbacks under its own event gate. Never hold m_lock while
// subscribing or unsubscribing: the callback itself needs m_lock to snapshot the handles.
lock (m_sessionLifecycleLock)
{
if (!m_disposed && m_sessions == null &&
m_context is ServerSystemContext { Server.SessionManager: { } sessions })
{
m_sessions = sessions;
sessions.SessionClosing += OnSessionClosing;
}
}
}
/// <summary>
/// Removes lifecycle callbacks after admission has been stopped by binding disposal.
/// </summary>
private void DetachSessionLifecycle()
{
lock (m_sessionLifecycleLock)
{
if (m_sessions != null)
{
m_sessions.SessionClosing -= OnSessionClosing;
m_sessions = null;
}
}
}
/// <summary>
/// Checks the live session registry instead of retaining an unbounded set of terminated identifiers.
/// </summary>
private bool IsSessionTerminated(NodeId sessionId)
{
ISessionManager? sessions = Volatile.Read(ref m_sessions);
if (sessions == null)
{
return false;
}
foreach (ISession session in sessions.GetSessions())
{
if (session.Id == sessionId)
{
return SessionTermination.IsClosingOrClaimed(session) || session.HasExpired;
}
}
return true;
}
/// <summary>
/// Releases only the closing session, without waiting for a provider open or the reconciliation gate.
/// </summary>
private void OnSessionClosing(ISession session, SessionEventReason reason)
{
FileHandle[] handles;
lock (m_lock)
{
handles = [.. m_handles.Values];
}
foreach (FileHandle handle in handles)
{
try
{
handle.CloseSession(session.Id);
}
finally
{
ReleaseHandle(handle);
}
}
}
private Task? m_disposal;
private bool TryTrackOperation(bool disposing = false)
{
lock (m_lock)
{
if (m_disposed || (!disposing && m_disposal != null))
{
return false;
}
m_activeOperations++;
return true;
}
}
private void CompleteOperation(bool entered)
{
if (entered)
{
m_gate.Release();
}
lock (m_lock)
{
if (--m_activeOperations == 0 && m_disposed)
{
m_gate.Dispose();
}
}
}
private async ValueTask CheckCapacityAsync(
FileSystemMutationKind kind,
string path,
string targetPath,
CancellationToken cancellationToken)
{
if (kind == FileSystemMutationKind.Delete)
{
return;
}
string destination = kind is FileSystemMutationKind.Move or FileSystemMutationKind.Copy
? targetPath
: path;
string parent = GetParentPath(destination);
if (kind == FileSystemMutationKind.Move && parent == GetParentPath(path))
{
return;
}
if (await Provider.GetEntryAsync(destination, cancellationToken).ConfigureAwait(false) != null)
{
return;
}
int count = 0;
await foreach (FileSystemEntry _ in Provider.EnumerateAsync(parent, cancellationToken)
.ConfigureAwait(false))
{
if (++count >= m_options.MaxEntries)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded,
"The directory cannot admit another entry within the configured binding limit.");
}
}
if (m_options.MaxEntries == 0)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded,
"The directory binding does not admit entries.");
}
}
private async ValueTask RefreshForMutationAsync(bool mutationCommitted, CancellationToken cancellationToken)
{
try
{
await RefreshCoreAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or
NotSupportedException or ServiceResultException or InvalidOperationException ||
(mutationCommitted && ex is OperationCanceledException))
{
m_refreshRequired = true;
m_logger.FileDirectoryRefreshFailed(ex, Directory.NodeId, mutationCommitted);
}
}
private async ValueTask RefreshCoreAsync(CancellationToken cancellationToken)
{
var seen = new HashSet<string>(StringComparer.Ordinal);
await ReconcileDirectoryAsync(Directory, string.Empty, 0, seen, cancellationToken)
.ConfigureAwait(false);
await RemoveStaleNodesAsync(seen, cancellationToken).ConfigureAwait(false);
if (m_initializing)
{
m_initializing = false;
foreach (MaterializedNode entry in m_nodesByPath.Values)
{
await RegisterNodeAsync(entry, cancellationToken).ConfigureAwait(false);
}
}
lock (m_lock)
{
m_lookupById = new Dictionary<NodeId, MaterializedNode>(m_nodesById);
}
m_refreshRequired = false;
}
private static string GetParentPath(string path)
{
int slash = path.LastIndexOf('/', StringComparison.Ordinal);
return slash < 0 ? string.Empty : path[..slash];
}
private async ValueTask ReconcileDirectoryAsync(
FileDirectoryState parent,
string providerPath,
int depth,
HashSet<string> seen,
CancellationToken cancellationToken)
{
List<FileSystemEntry> entries = [];
await foreach (FileSystemEntry entry in Provider.EnumerateAsync(providerPath, cancellationToken)
.ConfigureAwait(false))
{
if (entries.Count >= m_options.MaxEntries)
{
throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded,
"The directory contains more entries than the configured binding limit.");
}
entries.Add(entry);
}
foreach (FileSystemEntry entry in entries)
{
if (entry.IsDirectory)
{
if (depth >= m_options.MaxDepth)
{
continue;
}
FileDirectoryState child = await GetOrCreateDirectoryAsync(parent, entry, cancellationToken)
.ConfigureAwait(false);
seen.Add(entry.Path);
if (depth + 1 < m_options.MaxDepth)
{
await ReconcileDirectoryAsync(child, entry.Path, depth + 1, seen, cancellationToken)
.ConfigureAwait(false);
}
}
else
{
await GetOrCreateFileAsync(parent, entry, cancellationToken).ConfigureAwait(false);
seen.Add(entry.Path);
}
}
}
private async ValueTask<FileDirectoryState> GetOrCreateDirectoryAsync(
FileDirectoryState parent,
FileSystemEntry entry,
CancellationToken cancellationToken)
{
if (m_nodesByPath.TryGetValue(entry.Path, out MaterializedNode? existing))
{
if (existing.Node is FileDirectoryState directory)
{
await RegisterNodeAsync(existing, cancellationToken).ConfigureAwait(false);
return directory;
}
await RemoveNodeAsync(existing, cancellationToken).ConfigureAwait(false);
}
var node = new DirectoryObjectState(
m_context,
BuildDirectoryNodeId(entry.Path),
entry.Path,
entry.Name,
isRoot: false,
this);
parent.AddChild(node);
MaterializedNode materialized = AddMaterializedNode(entry.Path, node, isDirectory: true);
await RegisterNodeAsync(materialized, cancellationToken).ConfigureAwait(false);
return node;
}
private async ValueTask<FileState> GetOrCreateFileAsync(
FileDirectoryState parent,
FileSystemEntry entry,
CancellationToken cancellationToken)
{
if (m_nodesByPath.TryGetValue(entry.Path, out MaterializedNode? existing))
{
if (existing.Node is FileState file)
{
await RegisterNodeAsync(existing, cancellationToken).ConfigureAwait(false);
return file;
}
await RemoveNodeAsync(existing, cancellationToken).ConfigureAwait(false);
}
var node = new FileObjectState(m_context, BuildFileNodeId(entry.Path), entry.Path, entry.Name, this);
parent.AddChild(node);
MaterializedNode materialized = AddMaterializedNode(entry.Path, node, isDirectory: false);
await RegisterNodeAsync(materialized, cancellationToken).ConfigureAwait(false);
return node;
}
private async ValueTask RegisterNodeAsync(MaterializedNode entry, CancellationToken cancellationToken)
{
if (entry.Registered)
{
return;
}
if (m_registerNode == null)
{
entry.Registered = true;
return;
}
if (m_initializing)
{
return;
}
await m_registerNode(entry.Node, cancellationToken).ConfigureAwait(false);
entry.Registered = true;
}
private async ValueTask RemoveStaleNodesAsync(
HashSet<string> seen,
CancellationToken cancellationToken)
{
List<MaterializedNode> stale = [];
foreach (MaterializedNode entry in m_nodesByPath.Values)
{
if (!seen.Contains(entry.ProviderPath))
{
stale.Add(entry);
}
}
stale.Sort(static (left, right) => right.ProviderPath.Length.CompareTo(left.ProviderPath.Length));
foreach (MaterializedNode entry in stale)
{
await RemoveNodeAsync(entry, cancellationToken).ConfigureAwait(false);
}
}
private async ValueTask RemoveNodeAsync(
MaterializedNode entry,
CancellationToken cancellationToken)
{
List<MaterializedNode> descendants = [];
string prefix = entry.ProviderPath + "/";
foreach (MaterializedNode candidate in m_nodesByPath.Values)
{
if (candidate.ProviderPath.StartsWith(prefix, StringComparison.Ordinal))
{
descendants.Add(candidate);
}
}
descendants.Sort(static (left, right) => right.ProviderPath.Length.CompareTo(left.ProviderPath.Length));
foreach (MaterializedNode descendant in descendants)
{
await RemoveSingleNodeAsync(descendant, cancellationToken).ConfigureAwait(false);
}
await RemoveSingleNodeAsync(entry, cancellationToken).ConfigureAwait(false);
}
private async ValueTask RemoveSingleNodeAsync(
MaterializedNode entry,
CancellationToken cancellationToken)
{
if (entry.Registered && m_deregisterNode != null)
{
await m_deregisterNode(entry.Node, cancellationToken).ConfigureAwait(false);
}
DetachCallbacks(entry.Node);
ForgetHandle(entry.Node.NodeId);
entry.Node.Parent?.RemoveChild(entry.Node);
m_nodesByPath.Remove(entry.ProviderPath);
m_nodesById.Remove(entry.Node.NodeId);
}
private MaterializedNode AddMaterializedNode(string providerPath, BaseInstanceState node, bool isDirectory)
{
var entry = new MaterializedNode(providerPath, node, isDirectory);
m_nodesByPath[providerPath] = entry;
m_nodesById[node.NodeId] = entry;
return entry;
}
private void WireDirectoryCallbacks(FileDirectoryState directory, string providerPath)
{
EnsureDirectoryMethods(directory);
directory.DeleteFileSystemObject!.OnCallAsync = (context, method, objectId, objectToDelete, ct) =>
FileSystemDirectoryOperations.DeleteAsync(this, context, providerPath, objectToDelete, ct);
directory.CreateFile!.OnCallAsync = (context, method, objectId, fileName, requestFileOpen, ct) =>
FileSystemDirectoryOperations.CreateFileAsync(
this, context, providerPath, fileName, requestFileOpen, ct);
directory.CreateDirectory!.OnCallAsync = (context, method, objectId, directoryName, ct) =>
FileSystemDirectoryOperations.CreateDirectoryAsync(this, context, providerPath, directoryName, ct);
directory.MoveOrCopy!.OnCallAsync = (
context,
method,