aboutsummaryrefslogtreecommitdiff
path: root/MediaBrowser.Controller/Providers/DirectoryService.cs
blob: f8e0bf4ed9a73e2ef889358463a59d48ceb7ddf2 (plain)
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
#pragma warning disable CS1591

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using MediaBrowser.Model.IO;

namespace MediaBrowser.Controller.Providers
{
    public class DirectoryService : IDirectoryService
    {
        // TODO replace with one shared bounded cache.
        private const int MaxCachedRecords = 100_000;
        private const int AccessIntervalMs = 1_000;
        // Timeout cache if no access for 5 minutes.
        private const int IdleTimeoutMs = 5 * 60 * 1_000;

        private readonly ConcurrentDictionary<string, FileSystemMetadata[]> _cache = new(StringComparer.Ordinal);

        private readonly ConcurrentDictionary<string, FileSystemMetadata> _fileCache = new(StringComparer.Ordinal);

        private readonly ConcurrentDictionary<string, List<string>> _filePathCache = new(StringComparer.Ordinal);

        private readonly IFileSystem _fileSystem;

        // ConcurrentDictionary.Count locks the dictionary, so keep an estimated counter.
        // Concurrent factory runs can overcount and a clear racing an add can undercount,
        // it only has to be roughly right.
        private int _recordCount;
        private long _lastAccess = Environment.TickCount64;

        public DirectoryService(IFileSystem fileSystem)
        {
            _fileSystem = fileSystem;
        }

        public FileSystemMetadata[] GetFileSystemEntries(string path)
        {
            DropCacheIfIdleOrFull();

            return _cache.GetOrAdd(
                path,
                static (p, state) =>
                {
                    FileSystemMetadata[] entries;
                    try
                    {
                        entries = state.FileSystem.GetFileSystemEntries(p).ToArray();
                    }
                    catch (DirectoryNotFoundException)
                    {
                        entries = [];
                    }

                    Interlocked.Add(ref state.Service._recordCount, entries.Length + 1);
                    return entries;
                },
                (FileSystem: _fileSystem, Service: this));
        }

        public List<FileSystemMetadata> GetDirectories(string path)
        {
            var list = new List<FileSystemMetadata>();
            var items = GetFileSystemEntries(path);
            for (var i = 0; i < items.Length; i++)
            {
                var item = items[i];
                if (item.IsDirectory)
                {
                    list.Add(item);
                }
            }

            return list;
        }

        public List<FileSystemMetadata> GetFiles(string path)
        {
            var list = new List<FileSystemMetadata>();
            var items = GetFileSystemEntries(path);
            for (var i = 0; i < items.Length; i++)
            {
                var item = items[i];
                if (!item.IsDirectory)
                {
                    list.Add(item);
                }
            }

            return list;
        }

        public FileSystemMetadata? GetFile(string path)
        {
            var entry = GetFileSystemEntry(path);
            return entry is not null && !entry.IsDirectory ? entry : null;
        }

        public FileSystemMetadata? GetDirectory(string path)
        {
            var entry = GetFileSystemEntry(path);
            return entry is not null && entry.IsDirectory ? entry : null;
        }

        public FileSystemMetadata? GetFileSystemEntry(string path)
        {
            DropCacheIfIdleOrFull();

            if (!_fileCache.TryGetValue(path, out var result))
            {
                var file = _fileSystem.GetFileSystemInfo(path);
                if (file?.Exists ?? false)
                {
                    result = file;
                    if (_fileCache.TryAdd(path, result))
                    {
                        Interlocked.Increment(ref _recordCount);
                    }
                }
            }

            return result;
        }

        public IReadOnlyList<string> GetFilePaths(string path)
            => GetFilePaths(path, false);

        public IReadOnlyList<string> GetFilePaths(string path, bool clearCache)
        {
            if (clearCache && _filePathCache.TryRemove(path, out var cached))
            {
                Interlocked.Add(ref _recordCount, -(cached.Count + 1));
            }

            DropCacheIfIdleOrFull();

            var filePaths = _filePathCache.GetOrAdd(
                path,
                static (p, state) =>
                {
                    List<string> filePaths;
                    try
                    {
                        filePaths = state.FileSystem.GetFilePaths(p).OrderBy(x => x).ToList();
                    }
                    catch (DirectoryNotFoundException)
                    {
                        filePaths = [];
                    }

                    Interlocked.Add(ref state.Service._recordCount, filePaths.Count + 1);
                    return filePaths;
                },
                (FileSystem: _fileSystem, Service: this));

            return filePaths;
        }

        public void Invalidate(string path)
        {
            Forget(path);

            var parent = Path.GetDirectoryName(path);
            if (!string.IsNullOrEmpty(parent))
            {
                Forget(parent);
            }
        }

        public void Move(string source, string destination)
        {
            Directory.Move(source, destination);

            Invalidate(source);
            Invalidate(destination);
        }

        public bool IsAccessible(string path)
        {
            return _fileSystem.GetFileSystemEntryPaths(path).Any();
        }

        private void DropCacheIfIdleOrFull()
        {
            var nowMs = Environment.TickCount64;
            var idleMs = nowMs - _lastAccess;

            if (idleMs >= IdleTimeoutMs || _recordCount >= MaxCachedRecords)
            {
                _cache.Clear();
                _fileCache.Clear();
                _filePathCache.Clear();
                _recordCount = 0;
                _lastAccess = nowMs;
                return;
            }

            if (idleMs >= AccessIntervalMs)
            {
                _lastAccess = nowMs;
            }
        }

        private void Forget(string path)
        {
            if (_cache.TryRemove(path, out var entries))
            {
                Interlocked.Add(ref _recordCount, -(entries.Length + 1));
            }

            if (_fileCache.TryRemove(path, out _))
            {
                Interlocked.Decrement(ref _recordCount);
            }

            if (_filePathCache.TryRemove(path, out var filePaths))
            {
                Interlocked.Add(ref _recordCount, -(filePaths.Count + 1));
            }
        }
    }
}