Lean  $LEAN_TAG$
DiskDataCacheProvider.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  *
15 */
16 
17 using System.IO;
18 using Ionic.Zip;
19 using System.Linq;
20 using QuantConnect.Util;
21 using QuantConnect.Logging;
23 using System.Collections.Generic;
24 
25 namespace QuantConnect.Data
26 {
27  /// <summary>
28  /// Simple data cache provider, writes and reads directly from disk
29  /// Used as default for <see cref="LeanDataWriter"/>
30  /// </summary>
32  {
33  private readonly KeyStringSynchronizer _synchronizer;
34 
35  /// <summary>
36  /// Property indicating the data is temporary in nature and should not be cached.
37  /// </summary>
38  public bool IsDataEphemeral => false;
39 
40  /// <summary>
41  /// Creates a new instance
42  /// </summary>
44  {
45  }
46 
47  /// <summary>
48  /// Creates a new instance using the given synchronizer
49  /// </summary>
50  /// <param name="locker">The synchronizer instance to use</param>
52  {
53  _synchronizer = locker;
54  }
55 
56  /// <summary>
57  /// Fetch data from the cache
58  /// </summary>
59  /// <param name="key">A string representing the key of the cached data</param>
60  /// <returns>An <see cref="Stream"/> of the cached data</returns>
61  public Stream Fetch(string key)
62  {
63  LeanData.ParseKey(key, out var filePath, out var entryName);
64 
65  return _synchronizer.Execute(filePath, () =>
66  {
67  if (!File.Exists(filePath))
68  {
69  return null;
70  }
71 
72  try
73  {
74  using (var zip = ZipFile.Read(filePath))
75  {
76  ZipEntry entry;
77  if (entryName.IsNullOrEmpty())
78  {
79  // Return the first entry
80  entry = zip[0];
81  }
82  else
83  {
84  // Attempt to find our specific entry
85  if (!zip.ContainsEntry(entryName))
86  {
87  return null;
88  }
89 
90  entry = zip[entryName];
91  }
92 
93  // Extract our entry and return it
94  var stream = new MemoryStream();
95  entry.Extract(stream);
96  stream.Position = 0;
97  return stream;
98  }
99  }
100  catch (ZipException exception)
101  {
102  Log.Error("DiskDataCacheProvider.Fetch(): Corrupt file: " + key + " Error: " + exception);
103  return null;
104  }
105  });
106  }
107 
108  /// <summary>
109  /// Store the data in the cache. Not implemented in this instance of the IDataCacheProvider
110  /// </summary>
111  /// <param name="key">The source of the data, used as a key to retrieve data in the cache</param>
112  /// <param name="data">The data as a byte array</param>
113  public void Store(string key, byte[] data)
114  {
115  LeanData.ParseKey(key, out var filePath, out var entryName);
116 
117  _synchronizer.Execute(filePath, singleExecution: false, () =>
118  {
119  Compression.ZipCreateAppendData(filePath, entryName, data, true);
120  });
121  }
122 
123  /// <summary>
124  /// Returns a list of zip entries in a provided zip file
125  /// </summary>
126  public List<string> GetZipEntries(string zipFile)
127  {
128  return _synchronizer.Execute(zipFile, () =>
129  {
130  using var stream = new FileStream(FileExtension.ToNormalizedPath(zipFile), FileMode.Open, FileAccess.Read);
131  return Compression.GetZipEntryFileNames(stream).ToList();
132  });
133  }
134 
135  /// <summary>
136  /// Dispose for this class
137  /// </summary>
138  public void Dispose()
139  {
140  //NOP
141  }
142  }
143 }