Repository navigation
Expand file tree
/
Copy pathTsFileTransStore.cs
More file actions
256 lines (233 loc) · 9.4 KB
/
Copy pathTsFileTransStore.cs
File metadata and controls
256 lines (233 loc) · 9.4 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
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>
/// 分笔成交 TSFile 存储。每股票一个文件(去日期后缀),文件内按天一个 ChunkGroup(device = code.trans.date)。
/// 增量 = 追加新一天的 ChunkGroup;当天重取 = 整体重写文件。
/// </summary>
public class TsFileTransStore : ITransStore
{
private readonly string _baseDir;
// Per-file lock: independent files write concurrently; same-file access stays serialized.
private static readonly ConcurrentDictionary<string, object> _fileLocks = new();
private static object LockFor(string path) => _fileLocks.GetOrAdd(path, static _ => new object());
private static readonly List<MeasurementSchema> Schemas = new()
{
new("price", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
new("volume", TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.LZ4),
new("count", TSDataType.INT32, TSEncoding.TS_2DIFF, CompressionType.LZ4),
new("direction", TSDataType.INT32, TSEncoding.TS_2DIFF, CompressionType.LZ4),
};
public TsFileTransStore(string datadir)
{
_baseDir = Path.Combine(datadir, "tsfile");
}
private static string FilePath(string baseDir, string code, MarketCode market)
{
var dir = Path.Combine(baseDir, market.ToString().ToLower(), "trans");
Directory.CreateDirectory(dir);
return Path.Combine(dir, $"{code}.tsfile");
}
private static string DeviceId(string code, DateOnly date) => $"{code}.trans.{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) =>
Schemas.Select(s => $"{deviceName}.{s.MeasurementName}").ToList();
public TransRecord[]? Get(string code, MarketCode market, DateOnly date)
{
var path = FilePath(_baseDir, code, market);
if (!File.Exists(path)) return null;
var records = new List<TransRecord>();
lock (LockFor(path))
{
try
{
using var reader = TsFileReader.Open(path);
var deviceName = DeviceId(code, date);
var rs = reader.Query(QueryPaths(deviceName), 0, long.MaxValue);
while (rs.Next())
{
records.Add(new TransRecord
{
Time = new DateTime(rs.GetTimestamp()),
Price = rs.GetFloat(0),
Volume = rs.GetFloat(1),
Count = rs.GetInt32(2),
Direction = rs.GetInt32(3),
});
}
reader.Close();
}
catch (InvalidOperationException)
{
return null;
}
}
return records.ToArray();
}
public DateOnly? GetLastDate(string code, MarketCode market)
{
var path = FilePath(_baseDir, code, market);
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)
{
return null;
}
}
return max;
}
public void Append(string code, MarketCode market, DateOnly date, TransRecord[] records)
{
if (records.Length == 0) return;
AppendDays(code, market, new Dictionary<DateOnly, TransRecord[]> { [date] = records });
}
/// <summary>
/// 批量追加多天:一次打开文件写入全部新天,避免逐天 Append 时每次都要
/// GetExistingDates + 恢复索引 + 重建索引造成的 O(n²) 开销。
/// 任一日期已存在(当天重取)则整体重写。
/// </summary>
public void AppendDays(string code, MarketCode market, IReadOnlyDictionary<DateOnly, TransRecord[]> days)
{
if (days.Count == 0) return;
var path = FilePath(_baseDir, code, market);
lock (LockFor(path))
{
var existingDates = GetExistingDates(path);
bool hasOverlap = days.Keys.Any(existingDates.Contains);
if (!hasOverlap && File.Exists(path))
{
// 纯增量:一次打开,批量追加多天
using var writer = TsFileWriter.OpenAppend(path);
foreach (var (d, records) in days.OrderBy(kv => kv.Key))
WriteDay(writer, DeviceId(code, d), records);
writer.Close();
}
else
{
// 新文件或当天重取:整体重写(读旧 + 合并 + 写临时文件 + 原子替换)
var allDays = ReadAllDays(path);
foreach (var (d, records) in days)
allDays[d] = records.OrderBy(r => r.Time).ToArray();
var tmpPath = path + ".tmp";
if (File.Exists(tmpPath)) File.Delete(tmpPath);
using (var writer = TsFileWriter.Open(tmpPath))
{
foreach (var (d, dayRecords) in allDays.OrderBy(kv => kv.Key))
WriteDay(writer, DeviceId(code, d), dayRecords);
writer.Close();
}
if (File.Exists(path)) File.Delete(path);
File.Move(tmpPath, path);
}
}
}
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 Dictionary<DateOnly, TransRecord[]> ReadAllDays(string path)
{
var result = new Dictionary<DateOnly, TransRecord[]>();
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<TransRecord>();
var rs = reader.Query(QueryPaths(d.GetDeviceName()), 0, long.MaxValue);
while (rs.Next())
{
records.Add(new TransRecord
{
Time = new DateTime(rs.GetTimestamp()),
Price = rs.GetFloat(0),
Volume = rs.GetFloat(1),
Count = rs.GetInt32(2),
Direction = rs.GetInt32(3),
});
}
result[date.Value] = records.ToArray();
}
reader.Close();
return result;
}
private static void WriteDay(TsFileWriter writer, string deviceId, TransRecord[] records)
{
records = NormalizeTransTimestamps(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].Price);
tablet.AddValue(i, 1, records[i].Volume);
tablet.AddValue(i, 2, records[i].Count);
tablet.AddValue(i, 3, records[i].Direction);
}
writer.WriteTabletAligned(tablet);
}
/// <summary>
/// trans 原始数据时间只到分钟(HH:mm:00),同一分钟多笔成交时间戳相同。
/// 为满足 TSFile aligned 模式时间戳严格递增的要求,对同一时间戳的多笔按
/// 毫秒序号递增:HH:mm:00.000、HH:mm:00.001、HH:mm:00.002 ... 日期与分钟
/// 不变,仅用毫秒位区分序号(实测单分钟最多 ~40 笔,远小于 1000ms)。
/// </summary>
private static TransRecord[] NormalizeTransTimestamps(TransRecord[] records)
{
var sorted = records.OrderBy(r => r.Time.Ticks).ToArray();
long lastRaw = long.MinValue;
int seq = 0;
for (int i = 0; i < sorted.Length; i++)
{
long raw = sorted[i].Time.Ticks;
if (raw == lastRaw) seq++;
else { lastRaw = raw; seq = 0; }
if (seq > 0)
{
var r = sorted[i];
sorted[i] = new TransRecord
{
Time = new DateTime(raw + seq * TimeSpan.TicksPerMillisecond),
Price = r.Price,
Volume = r.Volume,
Count = r.Count,
Direction = r.Direction,
};
}
}
return sorted;
}
}