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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
|
/**
* このファイルでは、チャートに関する処理を行います。
*/
const nestedProperty = require('nested-property');
import autobind from 'autobind-decorator';
import * as mongo from 'mongodb';
import db from '../db/mongodb';
import Note, { INote } from '../models/note';
import User, { isLocalUser, IUser } from '../models/user';
import DriveFile, { IDriveFile } from '../models/drive-file';
import { ICollection } from 'monk';
type Obj = { [key: string]: any };
type Partial<T> = {
[P in keyof T]?: Partial<T[P]>;
};
type ArrayValue<T> = {
[P in keyof T]: T[P] extends number ? Array<T[P]> : ArrayValue<T[P]>;
};
type Span = 'day' | 'hour';
//#region Chart Core
type ChartDocument<T extends Obj> = {
_id: mongo.ObjectID;
/**
* 集計のグループ
*/
group?: any;
/**
* 集計日時
*/
date: Date;
/**
* 集計期間
*/
span: Span;
/**
* データ
*/
data: T;
/**
* ユニークインクリメント用
*/
unique?: Obj;
};
/**
* 様々なチャートの管理を司るクラス
*/
abstract class Chart<T> {
protected collection: ICollection<ChartDocument<T>>;
protected abstract async generateTemplate(initial: boolean, mostRecentStats?: T): Promise<T>;
constructor(name: string) {
this.collection = db.get<ChartDocument<T>>(`stats.${name}`);
this.collection.createIndex({ span: -1, date: -1 }, { unique: true });
this.collection.createIndex('group');
}
@autobind
private convertQuery(x: Obj, path: string): Obj {
const query: Obj = {};
const dive = (x: Obj, path: string) => {
Object.entries(x).forEach(([k, v]) => {
const p = path ? `${path}.${k}` : k;
if (typeof v === 'number') {
query[p] = v;
} else {
dive(v, p);
}
});
};
dive(x, path);
return query;
}
@autobind
private async getCurrentStats(span: Span, group?: Obj): Promise<ChartDocument<T>> {
const now = new Date();
const y = now.getFullYear();
const m = now.getMonth();
const d = now.getDate();
const h = now.getHours();
const current =
span == 'day' ? new Date(y, m, d) :
span == 'hour' ? new Date(y, m, d, h) :
null;
// 現在(今日または今のHour)の統計
const currentStats = await this.collection.findOne({
group: group,
span: span,
date: current
});
if (currentStats) {
return currentStats;
}
// 集計期間が変わってから、初めてのチャート更新なら
// 最も最近の統計を持ってくる
// * 例えば集計期間が「日」である場合で考えると、
// * 昨日何もチャートを更新するような出来事がなかった場合は、
// * 統計がそもそも作られずドキュメントが存在しないということがあり得るため、
// * 「昨日の」と決め打ちせずに「もっとも最近の」とします
const mostRecentStats = await this.collection.findOne({
group: group,
span: span
}, {
sort: {
date: -1
}
});
if (mostRecentStats) {
// 現在の統計を初期挿入
const data = await this.generateTemplate(false, mostRecentStats.data);
const stats = await this.collection.insert({
group: group,
span: span,
date: current,
data: data
});
return stats;
} else {
// 統計が存在しなかったら
// * Misskeyインスタンスを建てて初めてのチャート更新時など
// 空の統計を作成
const data = await this.generateTemplate(true);
const stats = await this.collection.insert({
group: group,
span: span,
date: current,
data: data
});
return stats;
}
}
@autobind
protected commit(query: Obj, group?: Obj, uniqueKey?: string, uniqueValue?: string): void {
const update = (stats: ChartDocument<T>) => {
// ユニークインクリメントの場合、指定のキーに指定の値が既に存在していたら弾く
if (uniqueKey && stats.unique && stats.unique[uniqueKey] && stats.unique[uniqueKey].includes(uniqueValue)) return;
if (uniqueKey) {
query['$push'] = {
[`unique.${uniqueKey}`]: uniqueValue
};
}
this.collection.update({
_id: stats._id
}, query);
};
this.getCurrentStats('day', group).then(stats => update(stats));
this.getCurrentStats('hour', group).then(stats => update(stats));
}
@autobind
protected inc(inc: Partial<T>, group?: Obj): void {
this.commit({
$inc: this.convertQuery(inc, 'data')
}, group);
}
@autobind
protected incIfUnique(inc: Partial<T>, key: string, value: string, group?: Obj): void {
this.commit({
$inc: this.convertQuery(inc, 'data')
}, group, key, value);
}
@autobind
public async getStats(span: Span, range: number, group?: Obj): Promise<ArrayValue<T>> {
const promisedChart: Promise<T>[] = [];
const now = new Date();
const y = now.getFullYear();
const m = now.getMonth();
const d = now.getDate();
const h = now.getHours();
const gt =
span == 'day' ? new Date(y, m, d - range) :
span == 'hour' ? new Date(y, m, d, h - range) : null;
const stats = await this.collection.find({
group: group,
span: span,
date: {
$gt: gt
}
}, {
sort: {
date: -1
},
fields: {
_id: 0
}
});
for (let i = (range - 1); i >= 0; i--) {
const current =
span == 'day' ? new Date(y, m, d - i) :
span == 'hour' ? new Date(y, m, d, h - i) :
null;
const stat = stats.find(s => s.date.getTime() == current.getTime());
if (stat) {
promisedChart.unshift(Promise.resolve(stat.data));
} else { // 隙間埋め
const mostRecent = stats.find(s => s.date.getTime() < current.getTime());
promisedChart.unshift(this.generateTemplate(false, mostRecent ? mostRecent.data : null));
}
}
const chart = await Promise.all(promisedChart);
const res: ArrayValue<T> = {} as any;
/**
* [{
* x: 1,
* y: 5
* }, {
* x: 2,
* y: 6
* }, {
* x: 3,
* y: 7
* }]
*
* を
*
* {
* x: [1, 2, 3],
* y: [5, 6, 7]
* }
*
* にする
*/
const dive = (x: Obj, path?: string) => {
Object.entries(x).forEach(([k, v]) => {
const p = path ? `${path}.${k}` : k;
if (typeof v == 'object') {
dive(v, p);
} else {
nestedProperty.set(res, p, chart.map(s => nestedProperty.get(s, p)));
}
});
};
dive(chart[0]);
return res;
}
}
//#endregion
//#region Users stats
/**
* ユーザーに関する統計
*/
type UsersStats = {
local: {
/**
* 集計期間時点での、全ユーザー数 (ローカル)
*/
total: number;
/**
* 増加したユーザー数 (ローカル)
*/
inc: number;
/**
* 減少したユーザー数 (ローカル)
*/
dec: number;
};
remote: {
/**
* 集計期間時点での、全ユーザー数 (リモート)
*/
total: number;
/**
* 増加したユーザー数 (リモート)
*/
inc: number;
/**
* 減少したユーザー数 (リモート)
*/
dec: number;
};
};
class UsersChart extends Chart<UsersStats> {
constructor() {
super('users');
}
@autobind
protected async generateTemplate(initial: boolean, mostRecentStats?: UsersStats): Promise<UsersStats> {
const [localCount, remoteCount] = initial ? await Promise.all([
User.count({ host: null }),
User.count({ host: { $ne: null } })
]) : [
mostRecentStats ? mostRecentStats.local.total : 0,
mostRecentStats ? mostRecentStats.remote.total : 0
];
return {
local: {
total: localCount,
inc: 0,
dec: 0
},
remote: {
total: remoteCount,
inc: 0,
dec: 0
}
};
}
@autobind
public async update(user: IUser, isAdditional: boolean) {
const update: Obj = {};
update.total = isAdditional ? 1 : -1;
if (isAdditional) {
update.inc = 1;
} else {
update.dec = 1;
}
await this.inc({
[isLocalUser(user) ? 'local' : 'remote']: update
});
}
}
export const usersChart = new UsersChart();
//#endregion
//#region Notes stats
/**
* 投稿に関する統計
*/
type NotesStats = {
local: {
/**
* 集計期間時点での、全投稿数 (ローカル)
*/
total: number;
/**
* 増加した投稿数 (ローカル)
*/
inc: number;
/**
* 減少した投稿数 (ローカル)
*/
dec: number;
diffs: {
/**
* 通常の投稿数の差分 (ローカル)
*/
normal: number;
/**
* リプライの投稿数の差分 (ローカル)
*/
reply: number;
/**
* Renoteの投稿数の差分 (ローカル)
*/
renote: number;
};
};
remote: {
/**
* 集計期間時点での、全投稿数 (リモート)
*/
total: number;
/**
* 増加した投稿数 (リモート)
*/
inc: number;
/**
* 減少した投稿数 (リモート)
*/
dec: number;
diffs: {
/**
* 通常の投稿数の差分 (リモート)
*/
normal: number;
/**
* リプライの投稿数の差分 (リモート)
*/
reply: number;
/**
* Renoteの投稿数の差分 (リモート)
*/
renote: number;
};
};
};
class NotesChart extends Chart<NotesStats> {
constructor() {
super('notes');
}
@autobind
protected async generateTemplate(initial: boolean, mostRecentStats?: NotesStats): Promise<NotesStats> {
const [localCount, remoteCount] = initial ? await Promise.all([
Note.count({ '_user.host': null }),
Note.count({ '_user.host': { $ne: null } })
]) : [
mostRecentStats ? mostRecentStats.local.total : 0,
mostRecentStats ? mostRecentStats.remote.total : 0
];
return {
local: {
total: localCount,
inc: 0,
dec: 0,
diffs: {
normal: 0,
reply: 0,
renote: 0
}
},
remote: {
total: remoteCount,
inc: 0,
dec: 0,
diffs: {
normal: 0,
reply: 0,
renote: 0
}
}
};
}
@autobind
public async update(note: INote, isAdditional: boolean) {
const update: Obj = {
diffs: {}
};
update.total = isAdditional ? 1 : -1;
if (isAdditional) {
update.inc = 1;
} else {
update.dec = 1;
}
if (note.replyId != null) {
update.diffs.reply = isAdditional ? 1 : -1;
} else if (note.renoteId != null) {
update.diffs.renote = isAdditional ? 1 : -1;
} else {
update.diffs.normal = isAdditional ? 1 : -1;
}
await this.inc({
[isLocalUser(note._user) ? 'local' : 'remote']: update
});
}
}
export const notesChart = new NotesChart();
//#endregion
//#region Drive stats
/**
* ドライブに関する統計
*/
type DriveStats = {
local: {
/**
* 集計期間時点での、全ドライブファイル数 (ローカル)
*/
totalCount: number;
/**
* 集計期間時点での、全ドライブファイルの合計サイズ (ローカル)
*/
totalSize: number;
/**
* 増加したドライブファイル数 (ローカル)
*/
incCount: number;
/**
* 増加したドライブ使用量 (ローカル)
*/
incSize: number;
/**
* 減少したドライブファイル数 (ローカル)
*/
decCount: number;
/**
* 減少したドライブ使用量 (ローカル)
*/
decSize: number;
};
remote: {
/**
* 集計期間時点での、全ドライブファイル数 (リモート)
*/
totalCount: number;
/**
* 集計期間時点での、全ドライブファイルの合計サイズ (リモート)
*/
totalSize: number;
/**
* 増加したドライブファイル数 (リモート)
*/
incCount: number;
/**
* 増加したドライブ使用量 (リモート)
*/
incSize: number;
/**
* 減少したドライブファイル数 (リモート)
*/
decCount: number;
/**
* 減少したドライブ使用量 (リモート)
*/
decSize: number;
};
};
class DriveChart extends Chart<DriveStats> {
constructor() {
super('drive');
}
@autobind
protected async generateTemplate(initial: boolean, mostRecentStats?: DriveStats): Promise<DriveStats> {
const calcSize = (local: boolean) => DriveFile
.aggregate([{
$match: {
'metadata._user.host': local ? null : { $ne: null },
'metadata.deletedAt': { $exists: false }
}
}, {
$project: {
length: true
}
}, {
$group: {
_id: null,
usage: { $sum: '$length' }
}
}])
.then(res => res.length > 0 ? res[0].usage : 0);
const [localCount, remoteCount, localSize, remoteSize] = initial ? await Promise.all([
DriveFile.count({ 'metadata._user.host': null }),
DriveFile.count({ 'metadata._user.host': { $ne: null } }),
calcSize(true),
calcSize(false)
]) : [
mostRecentStats ? mostRecentStats.local.totalCount : 0,
mostRecentStats ? mostRecentStats.remote.totalCount : 0,
mostRecentStats ? mostRecentStats.local.totalSize : 0,
mostRecentStats ? mostRecentStats.remote.totalSize : 0
];
return {
local: {
totalCount: localCount,
totalSize: localSize,
incCount: 0,
incSize: 0,
decCount: 0,
decSize: 0
},
remote: {
totalCount: remoteCount,
totalSize: remoteSize,
incCount: 0,
incSize: 0,
decCount: 0,
decSize: 0
}
};
}
@autobind
public async update(file: IDriveFile, isAdditional: boolean) {
const update: Obj = {};
update.totalCount = isAdditional ? 1 : -1;
update.totalSize = isAdditional ? file.length : -file.length;
if (isAdditional) {
update.incCount = 1;
update.incSize = file.length;
} else {
update.decCount = 1;
update.decSize = file.length;
}
await this.inc({
[isLocalUser(file.metadata._user) ? 'local' : 'remote']: update
});
}
}
export const driveChart = new DriveChart();
//#endregion
//#region Network stats
/**
* ネットワークに関する統計
*/
type NetworkStats = {
/**
* 受信したリクエスト数
*/
incomingRequests: number;
/**
* 送信したリクエスト数
*/
outgoingRequests: number;
/**
* 応答時間の合計
* TIP: (totalTime / incomingRequests) でひとつのリクエストに平均でどれくらいの時間がかかったか知れる
*/
totalTime: number;
/**
* 合計受信データ量
*/
incomingBytes: number;
/**
* 合計送信データ量
*/
outgoingBytes: number;
};
class NetworkChart extends Chart<NetworkStats> {
constructor() {
super('network');
}
@autobind
protected async generateTemplate(initial: boolean, mostRecentStats?: NetworkStats): Promise<NetworkStats> {
return {
incomingRequests: 0,
outgoingRequests: 0,
totalTime: 0,
incomingBytes: 0,
outgoingBytes: 0
};
}
@autobind
public async update(incomingRequests: number, time: number, incomingBytes: number, outgoingBytes: number) {
const inc: Partial<NetworkStats> = {
incomingRequests: incomingRequests,
totalTime: time,
incomingBytes: incomingBytes,
outgoingBytes: outgoingBytes
};
await this.inc(inc);
}
}
export const networkChart = new NetworkChart();
//#endregion
|