コード例 #1
0
ファイル: CachedStorage.cs プロジェクト: t6tg/nhitomi
        public async Task <OneOf <StorageFile, NotFound, Exception> > ReadAsync(string name, CancellationToken cancellationToken = default)
        {
            try
            {
                var cache = await _redis.GetObjectAsync <Cache>(_options.Prefix + name, cancellationToken);

                if (cache == null)
                {
                    var result = await _impl.ReadAsync(name, cancellationToken);

                    if (result.TryPickT0(out var file, out _))
                    {
                        await using (file)
                        {
                            cache = new Cache
                            {
                                Data      = await file.Stream.ToArrayAsync(cancellationToken),
                                MediaType = file.MediaType
                            };

                            await _redis.SetObjectAsync(_options.Prefix + name, cache, _options.Expiry, cancellationToken : cancellationToken);
                        }
                    }
                }

                if (cache == null)
                {
                    return(new NotFound());
                }

                return(new StorageFile
                {
                    Name = name,
                    MediaType = cache.MediaType,
                    Stream = _memory.GetStream(cache.Data)
                });
            }
            catch (Exception e)
            {
                _logger.LogWarning(e, $"Failed to read file '{name}'.");
                return(e);
            }
        }