-
Notifications
You must be signed in to change notification settings - Fork 5
/
chart.ts
331 lines (296 loc) · 8.62 KB
/
chart.ts
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import { createCanvas } from '@napi-rs/canvas';
import type { SKRSContext2D } from '@napi-rs/canvas';
import type { ChartConfiguration } from 'chart.js';
import { Chart, registerables } from 'chart.js';
import { getDbo } from './db.js';
import { Timeframe } from './types.js';
// Register Chart.js components
Chart.register(...registerables);
// Create a compatibility layer for the canvas context
const createCompatibleContext = (ctx: SKRSContext2D) => {
return new Proxy(ctx, {
get: (target, prop) => {
if (prop === 'drawFocusIfNeeded') {
return () => {}; // Noop implementation
}
return target[prop as keyof SKRSContext2D];
},
}) as unknown as CanvasRenderingContext2D;
};
export type TimeSeriesData = {
_id: number; // Block height
count: number;
}[];
export type ChartData = {
config: ChartConfiguration;
width: number;
height: number;
};
const generateChart = (
timeSeriesData: TimeSeriesData,
globalChart: boolean
): { chartBuffer: Buffer; chartConfig: ChartConfiguration } => {
console.log('Generating chart with data:', { timeSeriesData, globalChart });
const dpi = 2;
const width = 1280 / (globalChart ? 1 : 4);
const height = 300 / (globalChart ? 1 : 4);
const labels = timeSeriesData.map((d) => d._id);
const dataValues = timeSeriesData.map((d) => d.count);
console.log('Chart data points:', { labels, dataValues });
const minBlock = Math.min(...labels);
const maxBlock = Math.max(...labels);
const chartConfig: ChartConfiguration = {
type: 'line',
data: {
labels,
datasets: [
{
label: 'Count',
data: dataValues,
fill: true,
borderColor: 'rgba(213, 99, 255, 0.5)',
borderWidth: 3,
pointBackgroundColor: 'rgba(255, 99, 255, 0.5)',
pointRadius: 3,
tension: 0.4,
backgroundColor: 'rgba(255, 99, 255, 0.5)',
},
],
},
options: {
responsive: false,
animation: false,
devicePixelRatio: dpi,
plugins: {
legend: {
display: false,
},
tooltip: {
enabled: true,
mode: 'index',
intersect: false,
backgroundColor: 'rgba(0, 0, 0, 0.8)',
titleFont: { size: 14 },
bodyFont: { size: 13 },
padding: 10,
displayColors: false,
callbacks: {
title: (items) => `Block Height: ${items[0].label}`,
label: (item) => `Count: ${item.raw}`,
},
},
},
scales: globalChart
? {
x: {
type: 'linear',
min: minBlock,
max: maxBlock,
title: {
display: true,
text: 'Block Height',
color: '#fff',
font: { size: 14 },
},
grid: { color: '#333' },
ticks: {
color: '#fff',
font: { size: 14 },
callback: (value) => value.toString(),
maxTicksLimit: 10,
autoSkip: true,
},
},
y: {
type: 'linear',
title: {
display: true,
text: 'Count',
color: '#fff',
font: { size: 14 },
},
grid: { color: '#333' },
ticks: {
color: '#fff',
font: { size: 14 },
callback: (value) => value.toString(),
},
},
}
: {
x: {
type: 'linear',
min: minBlock,
max: maxBlock,
display: true,
ticks: {
display: false,
},
grid: {
display: false,
},
},
y: {
type: 'linear',
display: true,
ticks: {
display: false,
},
grid: {
display: false,
},
},
},
},
};
console.log('Chart config:', JSON.stringify(chartConfig, null, 2));
// Create canvas and render chart
const canvas = createCanvas(width * dpi, height * dpi);
const ctx = canvas.getContext('2d');
// Scale context for high DPI
ctx.scale(dpi, dpi);
// Set background color
ctx.fillStyle = 'transparent';
ctx.fillRect(0, 0, width, height);
// Create chart with compatible context
const compatibleCtx = createCompatibleContext(ctx);
new Chart(compatibleCtx, chartConfig);
// Get buffer
const chartBuffer = canvas.toBuffer('image/png');
return { chartBuffer, chartConfig };
};
export type ChartResult = {
chartBuffer: Buffer;
chartData: ChartData;
};
const generateTotalsChart = async (
collectionName: string,
startBlock: number,
endBlock: number,
blockRange = 10
): Promise<ChartResult> => {
console.log('Generating totals chart:', { collectionName, startBlock, endBlock, blockRange });
const timeSeriesData = await getTimeSeriesData(collectionName, startBlock, endBlock, blockRange);
console.log('Time series data:', timeSeriesData);
const { chartBuffer, chartConfig } = generateChart(timeSeriesData, false);
const chartData = {
config: chartConfig,
width: 1280 / 4,
height: 300 / 4,
};
console.log('Generated chart data:', chartData);
return { chartBuffer, chartData };
};
const generateCollectionChart = async (
collectionName: string | undefined,
startBlock: number,
endBlock: number,
range: number
): Promise<ChartResult> => {
console.log('Generating collection chart:', { collectionName, startBlock, endBlock, range });
const dbo = await getDbo();
const allCollections = await dbo.listCollections().toArray();
const allDataPromises = allCollections.map((c) =>
getTimeSeriesData(c.name, startBlock, endBlock, range)
);
const allTimeSeriesData = await Promise.all(allDataPromises);
console.log('All time series data:', allTimeSeriesData);
const globalData: Record<number, number> = {};
for (const collectionData of allTimeSeriesData) {
for (const { _id, count } of collectionData) {
globalData[_id] = (globalData[_id] || 0) + count;
}
}
const aggregatedData = Object.keys(globalData).map((blockHeight) => ({
_id: Number(blockHeight),
count: globalData[blockHeight],
}));
console.log('Aggregated data:', aggregatedData);
const { chartBuffer, chartConfig } = generateChart(aggregatedData, true);
const chartData = {
config: chartConfig,
width: 1280,
height: 300,
};
console.log('Final chart data:', JSON.stringify(chartData, null, 2));
return { chartBuffer, chartData };
};
async function getTimeSeriesData(
collectionName: string,
startBlock: number,
endBlock: number,
blockRange = 10
): Promise<TimeSeriesData> {
const dbo = await getDbo();
try {
// First check if collection exists and has any documents
const count = await dbo.collection(collectionName).countDocuments({
'blk.i': { $gte: startBlock, $lte: endBlock },
});
if (count === 0) {
console.log(`No data found for ${collectionName} between blocks ${startBlock}-${endBlock}`);
return [];
}
const pipeline = [
{
$match: {
'blk.i': {
$gte: startBlock,
$lte: endBlock,
},
},
},
{
$project: {
blockGroup: {
$subtract: ['$blk.i', { $mod: ['$blk.i', blockRange] }],
},
},
},
{
$group: {
_id: '$blockGroup',
count: { $sum: 1 },
},
},
{
$sort: { _id: 1 },
},
];
const result = await dbo.collection(collectionName).aggregate(pipeline).toArray();
console.log(`Found ${result.length} data points for ${collectionName}`);
return result as TimeSeriesData;
} catch (error) {
console.error(`Error getting time series data for ${collectionName}:`, error);
return [];
}
}
function timeframeToBlocks(period: string) {
switch (period) {
case Timeframe.Day:
return 144;
case Timeframe.Week:
return 1008;
case Timeframe.Month:
return 4320;
case Timeframe.Year:
return 52560;
case Timeframe.All:
return 0;
default:
return 0;
}
}
function getBlocksRange(currentBlockHeight: number, timeframe: string): [number, number] {
const blocks = timeframeToBlocks(timeframe);
const startBlock = currentBlockHeight - blocks;
const endBlock = currentBlockHeight;
return [startBlock, endBlock];
}
export {
generateChart,
generateCollectionChart,
generateTotalsChart,
getBlocksRange,
getTimeSeriesData,
};