Repository navigation
File enumeration extensibility - #26806
Conversation
This is the Windows implementation of System.IO.Enumeration. It adds new find options to existing APIs and a public extensibilty model for richer, low allocation file system enumeration. The Unix implementation is in progress.
|
|
||
| public static string[] GetFiles(string path, string searchPattern, EnumerationOptions enumerationOptions) | ||
| { | ||
| if (path == null) |
There was a problem hiding this comment.
all the callers could move these two null checks inside InternalEnumeratePaths
There was a problem hiding this comment.
Was trying to avoid the extra check when I knew I was providing good data. I'll move the path one.
There was a problem hiding this comment.
Never mind, moving them both.
| public DateTimeOffset LastAccessTimeUtc { get { throw null; } } | ||
| public DateTimeOffset LastWriteTimeUtc { get { throw null; } } | ||
|
|
||
| public bool IsNameDotOrDotDot { get { throw null; } } |
There was a problem hiding this comment.
IsNameDotOrDotDot and ReturnSpecialDirectories seem to be two names for the same thing. Can we make them consistent? Eg., either IsSpecialDirectory or ReturnDotAndDotDot
There was a problem hiding this comment.
They aren't strictly the same. One actually only applies to directories, the other applies to any entry- although I'm unaware of the ability to actually name a file that way. Definitely cannot in Windows, but I'm not positive elsewhere.
There was a problem hiding this comment.
With further reflection I realize having the helper is unnecessary now that we have an option and returning them is turned off by default. Removing the property.
| private readonly string _rootDirectory; | ||
| private readonly EnumerationOptions _options; | ||
|
|
||
| private object _lock = new object(); |
| bool acquiredLock = false; | ||
| FileSystemEntry entry = default; | ||
|
|
||
| Monitor.Enter(_lock, ref acquiredLock); |
There was a problem hiding this comment.
does this have an advantage over a lock{} ? It seems the same.
There was a problem hiding this comment.
Only if we provide the option to avoid it. I was toying with it- I can change it to lock.
There was a problem hiding this comment.
What do you mean by option to avoid it?
| else if (_options.RecurseSubdirectories && ShouldRecurseIntoEntry(ref entry)) | ||
| { | ||
| // Recursion is on and the directory was accepted, Queue it | ||
| string subDirectory = PathHelpers.CombineNoChecks(_currentPath, _entry.InodeName); |
There was a problem hiding this comment.
nit, either the 'd' in subdirectory is capitalized or not. It looks like our pattern is not eg RecurseSubdirectories CreateSubdirectory
There was a problem hiding this comment.
fixed- that came with the copy from the old enumerator
| _currentPath = _rootDirectory; | ||
| } | ||
|
|
||
| private static SafeDirectoryHandle CreateDirectoryHandle(string path) |
There was a problem hiding this comment.
You mentioned that SafeHandle is costly. Is that something you have a plan to avoid?
There was a problem hiding this comment.
Yes. That is part of the pending work.
| private readonly string _rootDirectory; | ||
| private readonly EnumerationOptions _options; | ||
|
|
||
| private object _lock = new object(); |
| if (_lastEntryFound) | ||
| return false; | ||
|
|
||
| // Calling the constructor inside the try block would create a second instance on the stack. |
There was a problem hiding this comment.
C# guarantees that state will not be half finished. If there is a finally/catch, a second copy is made for the constructor to run before it is atomically copied over (so you can't potentially view a half constructed struct).
There was a problem hiding this comment.
It matters as the size of the struct will be relatively large for the final Unix implementation.
There was a problem hiding this comment.
It felt wrong to explain C# behavior in full detail even though it is a not-so-well-known fact
There was a problem hiding this comment.
What ctor and struct is this referring to? I'm lost.
|
|
||
| private unsafe void FindNextEntry() | ||
| { | ||
| Interop.NtDll.FILE_FULL_DIR_INFORMATION* entry = _entry; |
There was a problem hiding this comment.
can be replaced with
_entry = FILE_FULL_DIR_INFORMATION.GetNextInfo(_entry);
if (_entry == null)
return;There was a problem hiding this comment.
Forgot I wrote that. :)
|
|
||
| if (handle == IntPtr.Zero || handle == (IntPtr)(-1)) | ||
| { | ||
| // Historically we throw directory not found rather than file not found |
There was a problem hiding this comment.
this comment should be down by ERROR_FILE_NOT_FOUND
| } | ||
| catch | ||
| { | ||
| // Couldn't queue the handle, close it and rethrow |
There was a problem hiding this comment.
This would only happen if we were out of memory. Are we consistently trying to avoid leaking resources in this situation?
There was a problem hiding this comment.
Yes, we're being extremely careful about this as we're not use SafeHandle
|
|
||
| object IEnumerator.Current => Current; | ||
|
|
||
| [MethodImpl(MethodImplOptions.AggressiveInlining)] |
There was a problem hiding this comment.
This is quite a big method. Do you have perf data that proves inlining is worth it?
There was a problem hiding this comment.
It is only ever used in one place- it was an optimization for code sharing between the various platforms to put it in a method. @jkotas- is there a downside to doing this when you know it is logically "embedded"?
There was a problem hiding this comment.
If you keep this it could use a comment explaining
There was a problem hiding this comment.
- Merging two logically embedded methods into one is not always a win.
- It bit rots as the code is changing. It makes the code hard to maintain.
AggressiveInlining should be only used when you have measured that it improves performance for something you care about. It does not seem to be the case here.
Otherwise, leave it to the compiler to decide.
| goto ExpressionFinished; | ||
| } | ||
|
|
||
| currentState = expressionOffset * 2 + 2; |
There was a problem hiding this comment.
Can you explain the * 2 ? I see this is already in the code but I'm having trouble picturing why the offset is getting multiplied and divided.
There was a problem hiding this comment.
It uses even/odd positioning to track multiple match states. It melts my head as well, but this is a copy of the actual Windows algorithm so I've kept it logically identical. (Tweaked for C# and our use- I added escaping support and the ability to skip the extended wildcards.)
There was a problem hiding this comment.
I don't know that I can write an explanation that wouldn't be more confusing. This came from http://source.dot.net/#System.IO.FileSystem.Watcher/System/IO/PatternMatcher.cs,785116727bd6631b. I did what I could to put better names on things and I couldn't see how the long form comments at the top were more helpful than confusing. I'll give it more thought. Perhaps someone with better algorithm-fu can assist.
danmoseley
left a comment
There was a problem hiding this comment.
Would be interesting to post any perf data you have.
More interesting once the next stage is done. The Windows code really hasn't changed other than being moved around and having new entry points added. |
|
@cdmihai This is the first PR for the enumeration extensibility. Can you take a look and tag relevant build/project system folks? Thanks! We're still settling on how to provide down-level, but the current leaning is to providing the same APIs in a different namespace in an OOB assembly (perhaps |
| /// useful is with remote share enumeration on Windows. Having a large buffer may result in | ||
| /// better performance as more results can be batched over the wire. | ||
| /// </remarks> | ||
| public int BufferSize { get; set; } |
There was a problem hiding this comment.
Rather than taking a buffer size, should we instead have this be a Memory<byte> that would allow the caller to provide their own scratch buffer, such that it could be reused from iteration to iteration (and if we ever need to pin it, they could prepin it)?
There was a problem hiding this comment.
We do have to pin. I thought about how to approach doing this, but tabled it for future as it is a little strange and would require some discussion. We don't always use a buffer, and when we do they have to be a very specific minimum size. The platform-to-platform variance is pretty big, and could conceivably (even likely) change in the future too.
There was a problem hiding this comment.
How does a developer know what to set this to?
There was a problem hiding this comment.
It is advisory and requires pretty intimate knowledge of how things work. It is essentially the equivalent of FIND_FIRST_EX_LARGE_FETCH in FindFirstFileEx which people have been asking for. I started with UseLargeBuffer but feedback was given in API review to change it to a specific number.
I'll add some more comments to try and help clarify. Note that this option is being specifically requested by customers (not in this shape exactly- they want the FIND_FIRST_EX_LARGE_FETCH option).
| /// Set to true to return "." and ".." directory entries. | ||
| /// </summary> | ||
| public bool ReturnSpecialDirectories { get; set; } | ||
| } |
There was a problem hiding this comment.
What about symlinks and whether to follow them? Would I do that via AttributesToSkip and ReparsePoint? Or would it have already followed the symlink by that point?
There was a problem hiding this comment.
I hadn't spent much time rationalizing links/reparse points. We have a lot outstanding in this area and I don't see that we'll be able to get to the area holistically in 2.1. It is high on my backlog, however.
That said, there are a lot of other options I think we'll end up adding over time. If you think we should include any specific ones in 2.1 please let me know.
| public unsafe ref struct FileSystemEntry | ||
| { | ||
| // TODO: Unix implementation https://github.com/dotnet/corefx/issues/26715 | ||
| // Inital implementation is naive and not optimized. |
There was a problem hiding this comment.
I assume the goal is to get this in for 2.1 as well, right?
There was a problem hiding this comment.
Yes. Just intend to do that as separate changes for clarity. The issue is tracking.
| if (enumerator == null) | ||
| enumerator = new DelegateEnumerator(this); | ||
|
|
||
| return enumerator; |
There was a problem hiding this comment.
Nit: Could just be:
return Interlocked.Exchange(ref _enumerator, null) ?? new DelegateEnumerator(this);| /// </summary> | ||
| public delegate TResult FindTransform(ref FileSystemEntry entry); | ||
|
|
||
| private class DelegateEnumerator : FileSystemEnumerator<TResult> |
There was a problem hiding this comment.
We should seal types like this, in particular in case the JIT is then able to do better at devirtualization.
| // is the directory separator and cannot be part of any path segment in Windows). The other three are the | ||
| // special case wildcards that we'll convert some * and ? into. They're also valid as filenames on Unix, | ||
| // which is not true in Windows and as such we'll escape any that occur on the input string. | ||
| private static char[] s_unixEscapeChars = { '\\', '"', '<', '>' }; |
| int error = (int)Interop.NtDll.RtlNtStatusToDosError(status); | ||
|
|
||
| // Note that there are many NT status codes that convert to ERROR_ACCESS_DENIED. | ||
| if (ContinueOnError(error) || (error == Interop.Errors.ERROR_ACCESS_DENIED && _options.IgnoreInaccessible)) |
There was a problem hiding this comment.
Should we switch the order of the checks here? Seems like we shouldn't invoke the delegate when the latter condition is true, as we're just going to ignore what the delegate says in that case, and we may as well then avoid the cost of the invocation.
There was a problem hiding this comment.
My only counter argument is that the derived class may want to know about the error anyway?
There was a problem hiding this comment.
But if it returns false from ContinueOnError even though it set IgnoreInaccessible, wouldn't that mean we should respect it and not continue?
There was a problem hiding this comment.
I've tried to be consistent and make the options always trump if they're set and in all the other cases I'm not passing the info to the virtuals so I'll flip it. No matter which way this goes, the derived class can tweak options to get desired behavior.
| _rootDirectory = Path.GetFullPath(directory); | ||
| _options = options ?? EnumerationOptions.Default; | ||
|
|
||
| // We'll only suppress the media insertion prompt on the topmost directory |
There was a problem hiding this comment.
It'd be helpful if the comment said why.
|
Please add perf tests for enumeration and validate with them that perf of the existing overloads hasn't regressed, both throughput and GC. |
Created an issue to track #26836. Numbers aren't super useful for Unix until I finish refactoring via #26715. Manual testing of the initial Windows changes (which this doesn't fundamentally change) showed significant improvements (in the 2x and up range for throughput and GC reduction of up to 8x range). There will definitely be a significant reduction in allocations for Unix as well, particularly for filtered enumerations as strings will no longer get generated until needed for output (should also be able to remove the SafeHandle instances). |
|
Also delete this from .csproj? It should not be needed anymore now that you have picked up dependency on Linq. |
|
|
||
| // We'll only suppress the media insertion prompt on the topmost directory as that is the | ||
| // most likely scenario and we don't want to take the perf hit for large enumerations. | ||
| // (We weren't consistent with how we handled this historically.) |
There was a problem hiding this comment.
And we are making it inconsistent in different way now. IMHO, we should just get rid of it from everywhere.
There was a problem hiding this comment.
I'm hesitant to remove it completely as removable media is pretty common. Note, however, that I didn't change the behavior in this PR.
I'm not fundamentally opposed to the runtime turning it off completely, although it does make me a little nervous. That said it is a fairly simple P/Invoke to turn it back on...
|
@dotnet-bot test OSX x64 Debug Build |
My bad, I assumed that because we had the reference in the project file that we were actually using it. I suppose it isn't a big deal to introduce it? What do you think? I can clean the other usages up in a follow-up PR. |
|
Is there anything still referencing these? I believe that all references we from the code that you have changed. |
I didn't look close enough. The references are all internal to those files- removed. |
| /// Match using DOS style matching semantics. '*', '?', '<', '>', and '"' | ||
| /// are all considered wildcards. | ||
| /// </summary> | ||
| Dos |
There was a problem hiding this comment.
Modern shells (PowerShell, Bash) use more advanced globbing: '*' and '?' wildcards and charsets like [a-z].
PowerShell Core implementation works on Windows and Unix but expensive.
It will be great to have native implementation PowerShell-like globbing in .Net Core.
Also .Net Core always follow a platform behavior for file system case sensitivity. In PowerShell Core repo we have a feature request to implement case insensitive IntelliSense on Unix - when a user types a file path/name it can help a good. It would be great to have a case sensitive parameter in file system APIs.
There was a problem hiding this comment.
@iSazonov The intent is to offer more matching options. Regex, character sets, **, etc. In this initial release adding the casing option is something I think we should and can do. Maybe:
public enum MatchCasing
{
PlatformDefault,
HonorCasing,
IgnoreCasing
}There was a problem hiding this comment.
@iSazonov Can you link to your globbing code? ASP.net has some algorithms too.
There was a problem hiding this comment.
@JeremyKuhne I see the PR merged - many thanks for the great work!
Is there an Issue for feedback about the new options and globbing?
PowerShell globbing code is possible too specific. I believe @SteveL-MSFT can give right contacts for comments.
There was a problem hiding this comment.
#18922 is probably the best place for globbing input/feedback. #25873 tracks the general extensiblity / performance work around enumeration.
That sounds OK. As long as we can reference it from net46, should be good. CPS (@lifengl) and us will have to agree on a version of the package and put in visual studio's binding redirects, and then we'll have to respect that in our individual repositories to test as closely to VS as possible. It would be helpful to know the OOB nuget package transitive dependency graph to understand the extent to which it might screw up our current graph, but if there's any problems there I think we can fix them. Biggest issue would be if the new package hoists us out of devenv's binding redirects. |
* Windows file enumeration extensibility This is the Windows implementation of System.IO.Enumeration. It adds new find options to existing APIs and a public extensibilty model for richer, low allocation file system enumeration. The Unix implementation is in progress. * Initial naive Unix implementation of FileSystemEnumerator * Move a netcoreapp test to the right group * Fix WinRT build. * Address feedback from @danmosemsft * Remove inline attribute * Remove IsNameDotOrDotDot property * Address futher feedback. * Remove unreferenced common code Commit migrated from dotnet/corefx@66ada72
This change implements the new public API for file enumeration. See https://github.com/dotnet/designs/blob/master/accepted/file-enumeration.md. This is built off of the existing internal Windows implementation.
The initial Unix implementation is not optimized. #26715 tracks getting the performance up to snuff. The current implementation doesn't allow for skipping ReadOnly via the options as that will come more naturally via the pending performance refactoring. The Unix implementation is now aligned with the Windows implementation more closely. Matching will follow the Windows/DOS semantics much more closely for better cross platform search results. This change also introduces a simple match option for both platforms that removes all of the weird corner cases and treats
*and?as 0 or more and 1 no matter where they are in the pattern and what they are next to.All file enumeration goes through this new model and as such existing tests hit it. I've added a few more and I'll be adding more as I work on the Unix optimization. This PR has two commits if you want to look at the Unix changes independently (there are, however, some overall fixes in that change as well).
cc: @danmosemsft, @terrajobst, @KrzysztofCwalina