Repository navigation
Expand file tree
/
Copy pathTsFileKLineStore.cs
More file actions
265 lines (238 loc) · 10 KB
/
Copy pathTsFileKLineStore.cs
File metadata and controls
265 lines (238 loc) · 10 KB
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
using System.Collections.Concurrent;
using StockData.Contract;
using TSFile.Net.File;
using TSFile.Net.Data;
using TSFile.Net.Schema;
using TSFile.Net.Common;
using TSFile.Net.Reader;
namespace TsFileDriver;
/// <summary>
/// K线 TSFile 存储。每股票每周期一个文件,文件内按天一个 ChunkGroup(device = code.ktype.date)。
/// 增量 = 追加新一天的 ChunkGroup;当天重取 = 整体重写文件(读旧 + 替换当天 + 写回)。
/// </summary>
public class TsFileKLineStore : IKLineStore
{
private readonly string _baseDir;
// Per-file lock: different stocks write to different files, so serializing on a
// single static lock would defeat DataSync's concurrency. A per-path lock lets
// independent files be written concurrently while still protecting same-file access.
private static readonly ConcurrentDictionary<string, object> _fileLocks = new();
private static object LockFor(string path) => _fileLocks.GetOrAdd(path, static _ => new object());
private static List<MeasurementSchema> GetSchemas() => new()
{
new("open", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
new("high", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
new("low", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
new("close", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
new("volume", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
};
public TsFileKLineStore(string datadir)
{
_baseDir = Path.Combine(datadir, "tsfile");
}
private static string KTypeName(KLineType ktype) => ktype switch
{
KLineType.Day => "day", KLineType.OneMin => "1min", KLineType.FiveMin => "5min",
KLineType.Week => "week", KLineType.Month => "month",
KLineType.Quarter => "quarter", KLineType.HalfYear => "halfyear", KLineType.Year => "year",
KLineType.Min15 => "15min", KLineType.Min30 => "30min", KLineType.Min60 => "60min",
KLineType.Hour2 => "2hour",
_ => ktype.ToString().ToLower(),
};
private static string FilePath(string baseDir, string code, MarketCode market, KLineType ktype)
{
var dir = Path.Combine(baseDir, market.ToString().ToLower(), KTypeName(ktype));
Directory.CreateDirectory(dir);
return Path.Combine(dir, $"{code}.tsfile");
}
private static string DeviceId(string code, KLineType ktype, DateOnly date)
=> $"{code}.{KTypeName(ktype)}.{date:yyyyMMdd}";
private static DateOnly? ParseDate(string deviceName)
{
var segs = deviceName.Split('.');
if (segs.Length < 3) return null;
return DateOnly.TryParseExact(segs[^1], "yyyyMMdd", out var d) ? d : null;
}
private static List<string> QueryPaths(string deviceName) => new()
{
$"{deviceName}.open", $"{deviceName}.high", $"{deviceName}.low",
$"{deviceName}.close", $"{deviceName}.volume"
};
public KLineRecord[]? Get(string code, MarketCode market, KLineType ktype, DateOnly start, DateOnly end)
{
var path = FilePath(_baseDir, code, market, ktype);
if (!File.Exists(path)) return null;
var records = new List<KLineRecord>();
lock (LockFor(path))
{
try
{
using var reader = TsFileReader.Open(path);
foreach (var d in reader.GetAllDeviceIds())
{
var date = ParseDate(d.GetDeviceName());
if (date == null || date < start || date > end) continue;
var rs = reader.Query(QueryPaths(d.GetDeviceName()), 0, long.MaxValue);
while (rs.Next())
{
records.Add(new KLineRecord
{
Time = new DateTime(rs.GetTimestamp()),
Open = rs.GetFloat(0), High = rs.GetFloat(1), Low = rs.GetFloat(2),
Close = rs.GetFloat(3), Volume = rs.GetFloat(4),
});
}
}
reader.Close();
}
catch (InvalidOperationException)
{
// 读取失败不删文件:InvalidOperationException 来自 ChunkReader 的
// 元数据不一致(非文件损坏,损坏抛 TsFileCorruptedException/IOException),
// 删文件会导致数据永久丢失。
return null;
}
}
return records.ToArray();
}
public DateOnly? GetLastDate(string code, MarketCode market, KLineType ktype)
{
var path = FilePath(_baseDir, code, market, ktype);
if (!File.Exists(path)) return null;
DateOnly? max = null;
lock (LockFor(path))
{
try
{
using var reader = TsFileReader.Open(path);
foreach (var d in reader.GetAllDeviceIds())
{
var date = ParseDate(d.GetDeviceName());
if (date != null && (max == null || date > max)) max = date;
}
reader.Close();
}
catch (InvalidOperationException)
{
// 读取失败不删文件:InvalidOperationException 来自 ChunkReader 的
// 元数据不一致(非文件损坏,损坏抛 TsFileCorruptedException/IOException),
// 删文件会导致数据永久丢失。
return null;
}
}
return max;
}
public void Append(string code, MarketCode market, KLineType ktype, KLineRecord[] records)
{
if (records.Length == 0) return;
var path = FilePath(_baseDir, code, market, ktype);
// 按天分组
var dayGroups = records
.GroupBy(r => DateOnly.FromDateTime(r.Time))
.OrderBy(g => g.Key)
.ToDictionary(g => g.Key, g => g.OrderBy(r => r.Time).ToArray());
lock (LockFor(path))
{
// 现有日期
var existingDates = GetExistingDates(path);
bool needsRewrite = dayGroups.Keys.Any(existingDates.Contains);
if (!needsRewrite && File.Exists(path))
{
// 纯增量:追加新天
AppendNewDays(path, code, ktype, dayGroups);
}
else
{
// 有当天重取:整体重写(读旧 + 合并 + 写新临时文件 + 原子替换)
Rewrite(path, code, ktype, dayGroups);
}
}
}
private static HashSet<DateOnly> GetExistingDates(string path)
{
var dates = new HashSet<DateOnly>();
if (!File.Exists(path)) return dates;
using var reader = TsFileReader.Open(path);
foreach (var d in reader.GetAllDeviceIds())
{
var date = ParseDate(d.GetDeviceName());
if (date != null) dates.Add(date.Value);
}
reader.Close();
return dates;
}
private static void AppendNewDays(string path, string code, KLineType ktype,
Dictionary<DateOnly, KLineRecord[]> dayGroups)
{
var schemas = GetSchemas();
using var writer = TsFileWriter.OpenAppend(path);
foreach (var (date, dayRecords) in dayGroups.OrderBy(kv => kv.Key))
{
WriteDay(writer, DeviceId(code, ktype, date), schemas, dayRecords);
}
writer.Close();
}
private static void Rewrite(string path, string code, KLineType ktype,
Dictionary<DateOnly, KLineRecord[]> newDayGroups)
{
// 读旧文件所有天
var allDays = ReadAllDays(path, ktype);
// 合并新天(覆盖同一天)
foreach (var (date, records) in newDayGroups) allDays[date] = records;
var schemas = GetSchemas();
var tmpPath = path + ".tmp";
if (File.Exists(tmpPath)) File.Delete(tmpPath);
using (var writer = TsFileWriter.Open(tmpPath))
{
foreach (var (date, dayRecords) in allDays.OrderBy(kv => kv.Key))
{
WriteDay(writer, DeviceId(code, ktype, date), schemas, dayRecords);
}
writer.Close();
}
if (File.Exists(path)) File.Delete(path);
File.Move(tmpPath, path);
}
private static Dictionary<DateOnly, KLineRecord[]> ReadAllDays(string path, KLineType ktype)
{
var result = new Dictionary<DateOnly, KLineRecord[]>();
if (!File.Exists(path)) return result;
using var reader = TsFileReader.Open(path);
foreach (var d in reader.GetAllDeviceIds())
{
var date = ParseDate(d.GetDeviceName());
if (date == null) continue;
var records = new List<KLineRecord>();
var rs = reader.Query(QueryPaths(d.GetDeviceName()), 0, long.MaxValue);
while (rs.Next())
{
records.Add(new KLineRecord
{
Time = new DateTime(rs.GetTimestamp()),
Open = rs.GetFloat(0), High = rs.GetFloat(1), Low = rs.GetFloat(2),
Close = rs.GetFloat(3), Volume = rs.GetFloat(4),
});
}
result[date.Value] = records.ToArray();
}
reader.Close();
return result;
}
private static void WriteDay(TsFileWriter writer, string deviceId,
List<MeasurementSchema> schemas, KLineRecord[] records)
{
var devId = new StringArrayDeviceId(deviceId.Split('.'));
writer.RegisterAlignedTimeseries(devId, schemas);
var tablet = new Tablet(deviceId, schemas, (uint)records.Length);
for (int i = 0; i < records.Length; i++)
{
tablet.SetTimestamp(i, records[i].Time.Ticks);
tablet.AddValue(i, 0, records[i].Open);
tablet.AddValue(i, 1, records[i].High);
tablet.AddValue(i, 2, records[i].Low);
tablet.AddValue(i, 3, records[i].Close);
tablet.AddValue(i, 4, records[i].Volume);
}
writer.WriteTabletAligned(tablet);
}
}