2019-04-07 12:50:36 +00:00
|
|
|
/**
|
|
|
|
* チャートエンジン
|
|
|
|
*
|
|
|
|
* Tests located in test/chart
|
|
|
|
*/
|
|
|
|
|
|
|
|
import * as nestedProperty from 'nested-property';
|
|
|
|
import autobind from 'autobind-decorator';
|
|
|
|
import Logger from '../logger';
|
2021-03-23 08:43:07 +00:00
|
|
|
import { Schema } from '@/misc/schema';
|
2020-03-07 02:23:31 +00:00
|
|
|
import { EntitySchema, getRepository, Repository, LessThan, Between } from 'typeorm';
|
|
|
|
import { dateUTC, isTimeSame, isTimeBefore, subtractTime, addTime } from '../../prelude/time';
|
2021-03-23 08:43:07 +00:00
|
|
|
import { getChartInsertLock } from '@/misc/app-lock';
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
const logger = new Logger('chart', 'white', process.env.NODE_ENV !== 'test');
|
|
|
|
|
|
|
|
export type Obj = { [key: string]: any };
|
|
|
|
|
|
|
|
export type DeepPartial<T> = {
|
|
|
|
[P in keyof T]?: DeepPartial<T[P]>;
|
|
|
|
};
|
|
|
|
|
|
|
|
type ArrayValue<T> = {
|
|
|
|
[P in keyof T]: T[P] extends number ? T[P][] : ArrayValue<T[P]>;
|
|
|
|
};
|
|
|
|
|
|
|
|
type Log = {
|
|
|
|
id: number;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 集計のグループ
|
|
|
|
*/
|
|
|
|
group: string | null;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* 集計日時のUnixタイムスタンプ(秒)
|
|
|
|
*/
|
|
|
|
date: number;
|
|
|
|
};
|
|
|
|
|
|
|
|
const camelToSnake = (str: string) => {
|
|
|
|
return str.replace(/([A-Z])/g, s => '_' + s.charAt(0).toLowerCase());
|
|
|
|
};
|
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
const removeDuplicates = (array: any[]) => Array.from(new Set(array));
|
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
/**
|
|
|
|
* 様々なチャートの管理を司るクラス
|
|
|
|
*/
|
|
|
|
export default abstract class Chart<T extends Record<string, any>> {
|
|
|
|
private static readonly columnPrefix = '___';
|
|
|
|
private static readonly columnDot = '_';
|
|
|
|
|
|
|
|
private name: string;
|
2021-06-30 15:50:19 +00:00
|
|
|
private buffer: {
|
2021-03-18 02:17:05 +00:00
|
|
|
diff: DeepPartial<T>;
|
|
|
|
group: string | null;
|
|
|
|
}[] = [];
|
2019-04-07 12:50:36 +00:00
|
|
|
public schema: Schema;
|
|
|
|
protected repository: Repository<Log>;
|
2021-03-18 02:17:05 +00:00
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
protected abstract genNewLog(latest: T): DeepPartial<T>;
|
2021-03-18 02:17:05 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* @param logs 日時が新しい方が先頭
|
|
|
|
*/
|
|
|
|
protected abstract aggregate(logs: T[]): T;
|
|
|
|
|
|
|
|
protected abstract fetchActual(group: string | null): Promise<DeepPartial<T>>;
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
@autobind
|
|
|
|
private static convertSchemaToFlatColumnDefinitions(schema: Schema) {
|
|
|
|
const columns = {} as any;
|
|
|
|
const flatColumns = (x: Obj, path?: string) => {
|
|
|
|
for (const [k, v] of Object.entries(x)) {
|
|
|
|
const p = path ? `${path}${this.columnDot}${k}` : k;
|
|
|
|
if (v.type === 'object') {
|
|
|
|
flatColumns(v.properties, p);
|
2021-03-18 02:17:05 +00:00
|
|
|
} else if (v.type === 'number') {
|
2019-04-07 12:50:36 +00:00
|
|
|
columns[this.columnPrefix + p] = {
|
2019-04-16 08:52:09 +00:00
|
|
|
type: 'bigint',
|
2019-04-07 12:50:36 +00:00
|
|
|
};
|
2021-03-18 02:17:05 +00:00
|
|
|
} else if (v.type === 'array' && v.items.type === 'string') {
|
|
|
|
columns[this.columnPrefix + p] = {
|
|
|
|
type: 'varchar',
|
|
|
|
array: true,
|
|
|
|
};
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2019-04-12 16:43:22 +00:00
|
|
|
flatColumns(schema.properties!);
|
2019-04-07 12:50:36 +00:00
|
|
|
return columns;
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2021-05-28 00:34:42 +00:00
|
|
|
private static convertFlattenColumnsToObject(x: Record<string, any>): Record<string, any> {
|
2019-04-07 12:50:36 +00:00
|
|
|
const obj = {} as any;
|
|
|
|
for (const k of Object.keys(x).filter(k => k.startsWith(Chart.columnPrefix))) {
|
|
|
|
// now k is ___x_y_z
|
|
|
|
const path = k.substr(Chart.columnPrefix.length).split(Chart.columnDot).join('.');
|
|
|
|
nestedProperty.set(obj, path, x[k]);
|
|
|
|
}
|
|
|
|
return obj;
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
|
|
|
private static convertObjectToFlattenColumns(x: Record<string, any>) {
|
2021-03-18 02:17:05 +00:00
|
|
|
const columns = {} as Record<string, number | unknown[]>;
|
2019-04-07 12:50:36 +00:00
|
|
|
const flatten = (x: Obj, path?: string) => {
|
|
|
|
for (const [k, v] of Object.entries(x)) {
|
|
|
|
const p = path ? `${path}${this.columnDot}${k}` : k;
|
2021-03-18 02:17:05 +00:00
|
|
|
if (typeof v === 'object' && !Array.isArray(v)) {
|
2019-04-07 12:50:36 +00:00
|
|
|
flatten(v, p);
|
|
|
|
} else {
|
|
|
|
columns[this.columnPrefix + p] = v;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
flatten(x);
|
|
|
|
return columns;
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2021-03-18 02:17:05 +00:00
|
|
|
private static countUniqueFields(x: Record<string, any>) {
|
|
|
|
const exec = (x: Obj) => {
|
|
|
|
const res = {} as Record<string, any>;
|
|
|
|
for (const [k, v] of Object.entries(x)) {
|
|
|
|
if (typeof v === 'object' && !Array.isArray(v)) {
|
|
|
|
res[k] = exec(v);
|
|
|
|
} else if (Array.isArray(v)) {
|
|
|
|
res[k] = Array.from(new Set(v)).length;
|
|
|
|
} else {
|
|
|
|
res[k] = v;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return res;
|
|
|
|
};
|
|
|
|
return exec(x);
|
|
|
|
}
|
2019-04-07 12:50:36 +00:00
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
@autobind
|
|
|
|
private static convertQuery(diff: Record<string, number | unknown[]>) {
|
|
|
|
const query: Record<string, Function> = {};
|
2019-04-07 12:50:36 +00:00
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
for (const [k, v] of Object.entries(diff)) {
|
|
|
|
if (typeof v === 'number') {
|
|
|
|
if (v > 0) query[k] = () => `"${k}" + ${v}`;
|
|
|
|
if (v < 0) query[k] = () => `"${k}" - ${Math.abs(v)}`;
|
|
|
|
} else if (Array.isArray(v)) {
|
|
|
|
// TODO: item が文字列以外の場合も対応
|
|
|
|
// TODO: item をSQLエスケープ
|
|
|
|
const items = v.map(item => `"${item}"`).join(',');
|
|
|
|
query[k] = () => `array_cat("${k}", '{${items}}'::varchar[])`;
|
|
|
|
}
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return query;
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2019-07-24 16:36:48 +00:00
|
|
|
private static dateToTimestamp(x: Date): Log['date'] {
|
|
|
|
return Math.floor(x.getTime() / 1000);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
2020-03-06 16:04:36 +00:00
|
|
|
@autobind
|
2020-03-07 02:23:31 +00:00
|
|
|
private static parseDate(date: Date): [number, number, number, number, number, number, number] {
|
2020-03-06 16:04:36 +00:00
|
|
|
const y = date.getUTCFullYear();
|
|
|
|
const m = date.getUTCMonth();
|
|
|
|
const d = date.getUTCDate();
|
|
|
|
const h = date.getUTCHours();
|
2020-03-07 02:23:31 +00:00
|
|
|
const _m = date.getUTCMinutes();
|
|
|
|
const _s = date.getUTCSeconds();
|
|
|
|
const _ms = date.getUTCMilliseconds();
|
2020-03-06 16:04:36 +00:00
|
|
|
|
2020-03-07 02:23:31 +00:00
|
|
|
return [y, m, d, h, _m, _s, _ms];
|
2020-03-06 16:04:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2020-03-07 02:23:31 +00:00
|
|
|
private static getCurrentDate() {
|
|
|
|
return Chart.parseDate(new Date());
|
2020-03-06 16:04:36 +00:00
|
|
|
}
|
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
@autobind
|
|
|
|
public static schemaToEntity(name: string, schema: Schema): EntitySchema {
|
|
|
|
return new EntitySchema({
|
|
|
|
name: `__chart__${camelToSnake(name)}`,
|
|
|
|
columns: {
|
|
|
|
id: {
|
|
|
|
type: 'integer',
|
|
|
|
primary: true,
|
|
|
|
generated: true
|
|
|
|
},
|
|
|
|
date: {
|
|
|
|
type: 'integer',
|
|
|
|
},
|
|
|
|
group: {
|
|
|
|
type: 'varchar',
|
|
|
|
length: 128,
|
|
|
|
nullable: true
|
|
|
|
},
|
|
|
|
...Chart.convertSchemaToFlatColumnDefinitions(schema)
|
|
|
|
},
|
2019-06-18 08:10:28 +00:00
|
|
|
indices: [{
|
|
|
|
columns: ['date']
|
|
|
|
}, {
|
|
|
|
columns: ['group']
|
2019-06-18 08:11:28 +00:00
|
|
|
}, {
|
|
|
|
columns: ['date', 'group']
|
2019-06-18 08:10:28 +00:00
|
|
|
}]
|
2019-04-07 12:50:36 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
constructor(name: string, schema: Schema, grouped = false) {
|
|
|
|
this.name = name;
|
|
|
|
this.schema = schema;
|
|
|
|
const entity = Chart.schemaToEntity(name, schema);
|
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
const keys = ['date'];
|
2019-04-07 12:50:36 +00:00
|
|
|
if (grouped) keys.push('group');
|
|
|
|
|
|
|
|
entity.options.uniques = [{
|
|
|
|
columns: keys
|
|
|
|
}];
|
|
|
|
|
|
|
|
this.repository = getRepository<Log>(entity);
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2019-04-12 16:43:22 +00:00
|
|
|
private getNewLog(latest: T | null): T {
|
2019-04-07 12:50:36 +00:00
|
|
|
const log = latest ? this.genNewLog(latest) : {};
|
|
|
|
const flatColumns = (x: Obj, path?: string) => {
|
|
|
|
for (const [k, v] of Object.entries(x)) {
|
|
|
|
const p = path ? `${path}.${k}` : k;
|
|
|
|
if (v.type === 'object') {
|
|
|
|
flatColumns(v.properties, p);
|
|
|
|
} else {
|
|
|
|
if (nestedProperty.get(log, p) == null) {
|
2021-03-18 02:17:05 +00:00
|
|
|
const emptyValue = v.type === 'number' ? 0 : [];
|
|
|
|
nestedProperty.set(log, p, emptyValue);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
2019-04-12 16:43:22 +00:00
|
|
|
flatColumns(this.schema.properties!);
|
2019-04-07 12:50:36 +00:00
|
|
|
return log as T;
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2021-03-18 02:17:05 +00:00
|
|
|
private getLatestLog(group: string | null = null): Promise<Log | null> {
|
2019-04-07 12:50:36 +00:00
|
|
|
return this.repository.findOne({
|
|
|
|
group: group,
|
|
|
|
}, {
|
|
|
|
order: {
|
|
|
|
date: -1
|
|
|
|
}
|
2019-04-12 16:43:22 +00:00
|
|
|
}).then(x => x || null);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2021-03-18 02:17:05 +00:00
|
|
|
private async getCurrentLog(group: string | null = null): Promise<Log> {
|
2020-03-06 16:04:36 +00:00
|
|
|
const [y, m, d, h] = Chart.getCurrentDate();
|
2019-04-07 12:50:36 +00:00
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
const current = dateUTC([y, m, d, h]);
|
2019-04-07 12:50:36 +00:00
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
// 現在(=今のHour)のログ
|
2019-04-07 12:50:36 +00:00
|
|
|
const currentLog = await this.repository.findOne({
|
2019-07-24 16:36:48 +00:00
|
|
|
date: Chart.dateToTimestamp(current),
|
2019-04-07 12:50:36 +00:00
|
|
|
...(group ? { group: group } : {})
|
|
|
|
});
|
|
|
|
|
|
|
|
// ログがあればそれを返して終了
|
|
|
|
if (currentLog != null) {
|
|
|
|
return currentLog;
|
|
|
|
}
|
|
|
|
|
|
|
|
let log: Log;
|
|
|
|
let data: T;
|
|
|
|
|
|
|
|
// 集計期間が変わってから、初めてのチャート更新なら
|
|
|
|
// 最も最近のログを持ってくる
|
|
|
|
// * 例えば集計期間が「日」である場合で考えると、
|
|
|
|
// * 昨日何もチャートを更新するような出来事がなかった場合は、
|
|
|
|
// * ログがそもそも作られずドキュメントが存在しないということがあり得るため、
|
|
|
|
// * 「昨日の」と決め打ちせずに「もっとも最近の」とします
|
2021-03-18 02:17:05 +00:00
|
|
|
const latest = await this.getLatestLog(group);
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
if (latest != null) {
|
2021-05-28 00:34:42 +00:00
|
|
|
const obj = Chart.convertFlattenColumnsToObject(latest) as T;
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
// 空ログデータを作成
|
2020-01-10 07:04:25 +00:00
|
|
|
data = this.getNewLog(obj);
|
2019-04-07 12:50:36 +00:00
|
|
|
} else {
|
|
|
|
// ログが存在しなかったら
|
2020-02-17 17:27:18 +00:00
|
|
|
// (Misskeyインスタンスを建てて初めてのチャート更新時など)
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
// 初期ログデータを作成
|
2020-01-10 07:04:25 +00:00
|
|
|
data = this.getNewLog(null);
|
2019-04-07 12:50:36 +00:00
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
logger.info(`${this.name + (group ? `:${group}` : '')}: Initial commit created`);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
2020-03-06 13:33:54 +00:00
|
|
|
const date = Chart.dateToTimestamp(current);
|
2021-03-18 02:17:05 +00:00
|
|
|
const lockKey = `${this.name}:${date}:${group}`;
|
2020-03-06 13:33:54 +00:00
|
|
|
|
|
|
|
const unlock = await getChartInsertLock(lockKey);
|
2019-04-07 12:50:36 +00:00
|
|
|
try {
|
2020-03-06 13:33:54 +00:00
|
|
|
// ロック内でもう1回チェックする
|
|
|
|
const currentLog = await this.repository.findOne({
|
|
|
|
date: date,
|
|
|
|
...(group ? { group: group } : {})
|
|
|
|
});
|
|
|
|
|
|
|
|
// ログがあればそれを返して終了
|
|
|
|
if (currentLog != null) return currentLog;
|
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
// 新規ログ挿入
|
|
|
|
log = await this.repository.save({
|
|
|
|
group: group,
|
2020-03-06 13:33:54 +00:00
|
|
|
date: date,
|
2019-04-07 12:50:36 +00:00
|
|
|
...Chart.convertObjectToFlattenColumns(data)
|
|
|
|
});
|
2020-01-10 06:55:40 +00:00
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
logger.info(`${this.name + (group ? `:${group}` : '')}: New commit created`);
|
2019-04-07 12:50:36 +00:00
|
|
|
|
2020-03-06 13:33:54 +00:00
|
|
|
return log;
|
|
|
|
} finally {
|
|
|
|
unlock();
|
|
|
|
}
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2021-03-18 02:17:05 +00:00
|
|
|
protected commit(diff: DeepPartial<T>, group: string | null = null): void {
|
2021-06-30 15:50:19 +00:00
|
|
|
this.buffer.push({
|
2021-03-18 02:17:05 +00:00
|
|
|
diff, group,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
|
|
|
public async save() {
|
2021-06-30 15:50:19 +00:00
|
|
|
if (this.buffer.length === 0) {
|
2021-03-18 02:17:05 +00:00
|
|
|
logger.info(`${this.name}: Write skipped`);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-06-30 15:50:19 +00:00
|
|
|
// TODO: 前の時間のログがbufferにあった場合のハンドリング
|
2021-03-18 02:17:05 +00:00
|
|
|
// 例えば、save が20分ごとに行われるとして、前回行われたのは 01:50 だったとする。
|
2021-06-30 15:50:19 +00:00
|
|
|
// 次に save が行われるのは 02:10 ということになるが、もし 01:55 に新規ログが buffer に追加されたとすると、
|
2021-03-18 02:17:05 +00:00
|
|
|
// そのログは本来は 01:00~ のログとしてDBに保存されて欲しいのに、02:00~ のログ扱いになってしまう。
|
|
|
|
// これを回避するための実装は複雑になりそうなため、一旦保留。
|
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
const update = async (log: Log) => {
|
2021-03-18 02:17:05 +00:00
|
|
|
const finalDiffs = {} as Record<string, number | unknown[]>;
|
|
|
|
|
2021-06-30 15:50:19 +00:00
|
|
|
for (const diff of this.buffer.filter(q => q.group === log.group).map(q => q.diff)) {
|
2021-03-18 02:17:05 +00:00
|
|
|
const columns = Chart.convertObjectToFlattenColumns(diff);
|
|
|
|
|
|
|
|
for (const [k, v] of Object.entries(columns)) {
|
|
|
|
if (finalDiffs[k] == null) {
|
|
|
|
finalDiffs[k] = v;
|
|
|
|
} else {
|
|
|
|
if (typeof finalDiffs[k] === 'number') {
|
|
|
|
(finalDiffs[k] as number) += v as number;
|
|
|
|
} else {
|
|
|
|
(finalDiffs[k] as unknown[]) = (finalDiffs[k] as unknown[]).concat(v);
|
|
|
|
}
|
|
|
|
}
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
const query = Chart.convertQuery(finalDiffs);
|
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
// ログ更新
|
|
|
|
await this.repository.createQueryBuilder()
|
|
|
|
.update()
|
|
|
|
.set(query)
|
|
|
|
.where('id = :id', { id: log.id })
|
|
|
|
.execute();
|
2021-03-18 02:17:05 +00:00
|
|
|
|
|
|
|
logger.info(`${this.name + (log.group ? `:${log.group}` : '')}: Updated`);
|
|
|
|
|
2021-06-30 15:50:19 +00:00
|
|
|
// TODO: この一連の処理が始まった後に新たにbufferに入ったものは消さないようにする
|
|
|
|
this.buffer = this.buffer.filter(q => q.group !== log.group);
|
2019-04-07 12:50:36 +00:00
|
|
|
};
|
|
|
|
|
2021-06-30 15:50:19 +00:00
|
|
|
const groups = removeDuplicates(this.buffer.map(log => log.group));
|
2021-03-18 02:17:05 +00:00
|
|
|
|
|
|
|
await Promise.all(groups.map(group => this.getCurrentLog(group).then(log => update(log))));
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
2019-09-01 19:41:26 +00:00
|
|
|
@autobind
|
|
|
|
public async resync(group: string | null = null): Promise<any> {
|
|
|
|
const data = await this.fetchActual(group);
|
|
|
|
|
|
|
|
const update = async (log: Log) => {
|
|
|
|
await this.repository.createQueryBuilder()
|
|
|
|
.update()
|
|
|
|
.set(Chart.convertObjectToFlattenColumns(data))
|
|
|
|
.where('id = :id', { id: log.id })
|
|
|
|
.execute();
|
|
|
|
};
|
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
return this.getCurrentLog(group).then(log => update(log));
|
2019-09-01 19:41:26 +00:00
|
|
|
}
|
|
|
|
|
2019-04-07 12:50:36 +00:00
|
|
|
@autobind
|
2019-04-12 16:43:22 +00:00
|
|
|
protected async inc(inc: DeepPartial<T>, group: string | null = null): Promise<void> {
|
2021-03-18 02:17:05 +00:00
|
|
|
await this.commit(inc, group);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
@autobind
|
2021-03-18 02:17:05 +00:00
|
|
|
public async getChart(span: 'hour' | 'day', amount: number, cursor: Date | null, group: string | null = null): Promise<ArrayValue<T>> {
|
|
|
|
const [y, m, d, h, _m, _s, _ms] = cursor ? Chart.parseDate(subtractTime(addTime(cursor, 1, span), 1)) : Chart.getCurrentDate();
|
|
|
|
const [y2, m2, d2, h2] = cursor ? Chart.parseDate(addTime(cursor, 1, span)) : [] as never;
|
2020-03-06 16:04:36 +00:00
|
|
|
|
2020-03-07 02:23:31 +00:00
|
|
|
const lt = dateUTC([y, m, d, h, _m, _s, _ms]);
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
const gt =
|
2021-03-18 02:17:05 +00:00
|
|
|
span === 'day' ? subtractTime(cursor ? dateUTC([y2, m2, d2, 0]) : dateUTC([y, m, d, 0]), amount - 1, 'day') :
|
|
|
|
span === 'hour' ? subtractTime(cursor ? dateUTC([y2, m2, d2, h2]) : dateUTC([y, m, d, h]), amount - 1, 'hour') :
|
2019-04-12 16:43:22 +00:00
|
|
|
null as never;
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
// ログ取得
|
|
|
|
let logs = await this.repository.find({
|
|
|
|
where: {
|
|
|
|
group: group,
|
2020-03-07 02:23:31 +00:00
|
|
|
date: Between(Chart.dateToTimestamp(gt), Chart.dateToTimestamp(lt))
|
2019-04-07 12:50:36 +00:00
|
|
|
},
|
|
|
|
order: {
|
|
|
|
date: -1
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
// 要求された範囲にログがひとつもなかったら
|
|
|
|
if (logs.length === 0) {
|
|
|
|
// もっとも新しいログを持ってくる
|
|
|
|
// (すくなくともひとつログが無いと隙間埋めできないため)
|
|
|
|
const recentLog = await this.repository.findOne({
|
|
|
|
group: group,
|
|
|
|
}, {
|
|
|
|
order: {
|
|
|
|
date: -1
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (recentLog) {
|
|
|
|
logs = [recentLog];
|
|
|
|
}
|
|
|
|
|
|
|
|
// 要求された範囲の最も古い箇所に位置するログが存在しなかったら
|
2019-07-24 16:36:48 +00:00
|
|
|
} else if (!isTimeSame(new Date(logs[logs.length - 1].date * 1000), gt)) {
|
2019-04-07 12:50:36 +00:00
|
|
|
// 要求された範囲の最も古い箇所時点での最も新しいログを持ってきて末尾に追加する
|
|
|
|
// (隙間埋めできないため)
|
|
|
|
const outdatedLog = await this.repository.findOne({
|
|
|
|
group: group,
|
2019-07-24 16:36:48 +00:00
|
|
|
date: LessThan(Chart.dateToTimestamp(gt))
|
2019-04-07 12:50:36 +00:00
|
|
|
}, {
|
|
|
|
order: {
|
|
|
|
date: -1
|
|
|
|
},
|
|
|
|
});
|
|
|
|
|
|
|
|
if (outdatedLog) {
|
|
|
|
logs.push(outdatedLog);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const chart: T[] = [];
|
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
if (span === 'hour') {
|
|
|
|
for (let i = (amount - 1); i >= 0; i--) {
|
|
|
|
const current = subtractTime(dateUTC([y, m, d, h]), i, 'hour');
|
|
|
|
|
|
|
|
const log = logs.find(l => isTimeSame(new Date(l.date * 1000), current));
|
|
|
|
|
|
|
|
if (log) {
|
2021-05-28 00:34:42 +00:00
|
|
|
const data = Chart.convertFlattenColumnsToObject(log);
|
|
|
|
chart.unshift(Chart.countUniqueFields(data) as T);
|
2021-03-18 02:17:05 +00:00
|
|
|
} else {
|
|
|
|
// 隙間埋め
|
|
|
|
const latest = logs.find(l => isTimeBefore(new Date(l.date * 1000), current));
|
2021-05-28 00:34:42 +00:00
|
|
|
const data = latest ? Chart.convertFlattenColumnsToObject(latest) as T : null;
|
|
|
|
chart.unshift(Chart.countUniqueFields(this.getNewLog(data)) as T);
|
2021-03-18 02:17:05 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if (span === 'day') {
|
|
|
|
const logsForEachDays: T[][] = [];
|
|
|
|
let currentDay = -1;
|
|
|
|
let currentDayIndex = -1;
|
|
|
|
for (let i = ((amount - 1) * 24) + h; i >= 0; i--) {
|
|
|
|
const current = subtractTime(dateUTC([y, m, d, h]), i, 'hour');
|
|
|
|
const _currentDay = Chart.parseDate(current)[2];
|
|
|
|
if (currentDay != _currentDay) currentDayIndex++;
|
|
|
|
currentDay = _currentDay;
|
|
|
|
|
|
|
|
const log = logs.find(l => isTimeSame(new Date(l.date * 1000), current));
|
|
|
|
|
|
|
|
if (log) {
|
|
|
|
if (logsForEachDays[currentDayIndex]) {
|
2021-05-28 00:34:42 +00:00
|
|
|
logsForEachDays[currentDayIndex].unshift(Chart.convertFlattenColumnsToObject(log) as T);
|
2021-03-18 02:17:05 +00:00
|
|
|
} else {
|
2021-05-28 00:34:42 +00:00
|
|
|
logsForEachDays[currentDayIndex] = [Chart.convertFlattenColumnsToObject(log) as T];
|
2021-03-18 02:17:05 +00:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// 隙間埋め
|
|
|
|
const latest = logs.find(l => isTimeBefore(new Date(l.date * 1000), current));
|
2021-05-28 00:34:42 +00:00
|
|
|
const data = latest ? Chart.convertFlattenColumnsToObject(latest) as T : null;
|
2021-03-18 02:17:05 +00:00
|
|
|
const newLog = this.getNewLog(data);
|
|
|
|
if (logsForEachDays[currentDayIndex]) {
|
|
|
|
logsForEachDays[currentDayIndex].unshift(newLog);
|
|
|
|
} else {
|
|
|
|
logsForEachDays[currentDayIndex] = [newLog];
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
for (const logs of logsForEachDays) {
|
|
|
|
const log = this.aggregate(logs);
|
2021-05-28 00:34:42 +00:00
|
|
|
chart.unshift(Chart.countUniqueFields(log) as T);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const res: ArrayValue<T> = {} as any;
|
|
|
|
|
|
|
|
/**
|
|
|
|
* [{ foo: 1, bar: 5 }, { foo: 2, bar: 6 }, { foo: 3, bar: 7 }]
|
|
|
|
* を
|
|
|
|
* { foo: [1, 2, 3], bar: [5, 6, 7] }
|
|
|
|
* にする
|
|
|
|
*/
|
2021-03-18 02:17:05 +00:00
|
|
|
const compact = (x: Obj, path?: string) => {
|
2019-04-07 12:50:36 +00:00
|
|
|
for (const [k, v] of Object.entries(x)) {
|
|
|
|
const p = path ? `${path}.${k}` : k;
|
2021-03-18 02:17:05 +00:00
|
|
|
if (typeof v === 'object' && !Array.isArray(v)) {
|
|
|
|
compact(v, p);
|
2019-04-07 12:50:36 +00:00
|
|
|
} else {
|
2021-03-18 02:17:05 +00:00
|
|
|
const values = chart.map(s => nestedProperty.get(s, p));
|
2019-07-05 13:32:15 +00:00
|
|
|
nestedProperty.set(res, p, values);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2021-03-18 02:17:05 +00:00
|
|
|
compact(chart[0]);
|
2019-04-07 12:50:36 +00:00
|
|
|
|
|
|
|
return res;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export function convertLog(logSchema: Schema): Schema {
|
|
|
|
const v: Schema = JSON.parse(JSON.stringify(logSchema)); // copy
|
|
|
|
if (v.type === 'number') {
|
|
|
|
v.type = 'array';
|
|
|
|
v.items = {
|
2019-06-27 09:04:09 +00:00
|
|
|
type: 'number' as const,
|
|
|
|
optional: false as const, nullable: false as const,
|
2019-04-07 12:50:36 +00:00
|
|
|
};
|
|
|
|
} else if (v.type === 'object') {
|
2019-04-12 16:43:22 +00:00
|
|
|
for (const k of Object.keys(v.properties!)) {
|
|
|
|
v.properties![k] = convertLog(v.properties![k]);
|
2019-04-07 12:50:36 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
return v;
|
|
|
|
}
|