Skip to content

Commit

Permalink
Added InMemoryStorage Write impl
Browse files Browse the repository at this point in the history
  • Loading branch information
niemyjski committed Jan 5, 2024
1 parent efe5cd2 commit f172def
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions src/Foundatio/Storage/InMemoryFileStorage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,40 @@ public async Task<Stream> GetFileStreamAsync(string path, StreamMode streamMode,

using (await _lock.LockAsync().AnyContext())
{
if (!_storage.ContainsKey(normalizedPath))
if (streamMode is StreamMode.Read)
{
if (_storage.TryGetValue(normalizedPath, out var container))
return new MemoryStream(container.Item2);

_logger.LogError("Unable to get file stream for {Path}: File Not Found", normalizedPath);
return null;
}

return new MemoryStream(_storage[normalizedPath].Item2);
var stream = new MemoryStream();
return new ActionableStream(stream, () =>
{
stream.Position = 0;

// Copied from SaveFileAsync
_logger.LogTrace("Saving {Path}", normalizedPath);
byte[] contents = ReadBytes(stream);
if (contents.Length > MaxFileSize)
throw new ArgumentException($"File size {contents.Length.ToFileSizeDisplay()} exceeds the maximum size of {MaxFileSize.ToFileSizeDisplay()}.");

using (_lock.Lock())
{
_storage[normalizedPath] = Tuple.Create(new FileSpec
{
Created = SystemClock.UtcNow,
Modified = SystemClock.UtcNow,
Path = normalizedPath,
Size = contents.Length
}, contents);

if (_storage.Count > MaxFiles)
_storage.Remove(_storage.OrderByDescending(kvp => kvp.Value.Item1.Created).First().Key);
}
});
}
}

Expand Down

0 comments on commit f172def

Please sign in to comment.