fix(core): update

This commit is contained in:
Philipp Kunz 2022-08-05 13:31:11 +02:00
parent d03f086c92
commit 7d867ea6ab
10 changed files with 85 additions and 88 deletions

View File

@ -18,17 +18,6 @@ before_script:
# ==================== # ====================
# security stage # security stage
# ==================== # ====================
mirror:
stage: security
script:
- npmci git mirror
only:
- tags
tags:
- lossless
- docker
- notpriv
auditProductionDependencies: auditProductionDependencies:
image: registry.gitlab.com/hosttoday/ht-docker-node:npmci image: registry.gitlab.com/hosttoday/ht-docker-node:npmci
stage: security stage: security
@ -100,10 +89,9 @@ codequality:
only: only:
- tags - tags
script: script:
- npmci command npm install -g tslint typescript - npmci command npm install -g typescript
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command "tslint -c tslint.json ./ts/**/*.ts"
tags: tags:
- lossless - lossless
- docker - docker
@ -123,11 +111,10 @@ trigger:
pages: pages:
stage: metadata stage: metadata
script: script:
- npmci node install lts - npmci node install stable
- npmci command npm install -g @gitzone/tsdoc
- npmci npm prepare - npmci npm prepare
- npmci npm install - npmci npm install
- npmci command tsdoc - npmci command npm run buildDocs
tags: tags:
- lossless - lossless
- docker - docker

View File

@ -22,6 +22,5 @@
} }
} }
} }
], ]
"typescript.tsdk": "node_modules/typescript/lib"
} }

View File

@ -12,7 +12,8 @@
"test": "(tstest test/ --web)", "test": "(tstest test/ --web)",
"build": "(tsbuild --web --allowimplicitany)", "build": "(tsbuild --web --allowimplicitany)",
"createGrafana": "docker run --name grafana -d -p 4000:3000 grafana/grafana-oss", "createGrafana": "docker run --name grafana -d -p 4000:3000 grafana/grafana-oss",
"createClickhouse": "docker run --name some-clickhouse-server --ulimit nofile=262144:262144 -p 8123:8123 -p 9000:9000 --volume=$PWD/.nogit/testdatabase:/var/lib/clickhouse yandex/clickhouse-server" "createClickhouse": "docker run --name some-clickhouse-server --ulimit nofile=262144:262144 -p 8123:8123 -p 9000:9000 --volume=$PWD/.nogit/testdatabase:/var/lib/clickhouse yandex/clickhouse-server",
"buildDocs": "tsdoc"
}, },
"devDependencies": { "devDependencies": {
"@gitzone/tsbuild": "^2.1.65", "@gitzone/tsbuild": "^2.1.65",

View File

@ -18,15 +18,15 @@ tap.test('should start the clickhouse db', async () => {
tap.test('should create a timedatatable', async (toolsArg) => { tap.test('should create a timedatatable', async (toolsArg) => {
const table = await testClickhouseDb.getTable('analytics'); const table = await testClickhouseDb.getTable('analytics');
let i = 0; let i = 0;
while(i < 5000) { while (i < 5000) {
await table.addData({ await table.addData({
timestamp: Date.now(), timestamp: Date.now(),
message: `hello this is a message ${i}`, message: `hello this is a message ${i}`,
wow: 'hey', wow: 'hey',
deep: { deep: {
so: 'hello', so: 'hello',
myArray: ['array1', 'array2'] myArray: ['array1', 'array2'],
} },
}); });
i++; i++;
console.log(`logged ${i} of 5000 lines.`); console.log(`logged ${i} of 5000 lines.`);

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@pushrocks/smartclickhouse', name: '@pushrocks/smartclickhouse',
version: '2.0.13', version: '2.0.14',
description: 'an odm for talking to clickhouse' description: 'an odm for talking to clickhouse'
} }

View File

@ -1,5 +1,3 @@
import * as plugins from './smartclickhouse.plugins.js'; import * as plugins from './smartclickhouse.plugins.js';
export class ClickhouseDb { export class ClickhouseDb {}
}

View File

@ -17,7 +17,7 @@ export class ClickhouseHttpClient {
// INSTANCE // INSTANCE
public options: IClickhouseHttpClientOptions; public options: IClickhouseHttpClientOptions;
public webrequestInstance = new plugins.webrequest.WebRequest({ public webrequestInstance = new plugins.webrequest.WebRequest({
logging: false logging: false,
}); });
public computedProperties: { public computedProperties: {
connectionUrl: string; connectionUrl: string;
@ -37,20 +37,25 @@ export class ClickhouseHttpClient {
} }
public async ping() { public async ping() {
const ping = await this.webrequestInstance.request(
const ping = await this.webrequestInstance.request(this.computedProperties.connectionUrl.toString(), { this.computedProperties.connectionUrl.toString(),
method: 'GET', {
timeoutMs: 1000, method: 'GET',
}); timeoutMs: 1000,
}
);
return ping.status === 200 ? true : false; return ping.status === 200 ? true : false;
} }
public async queryPromise(queryArg: string) { public async queryPromise(queryArg: string) {
const returnArray = []; const returnArray = [];
const response = await this.webrequestInstance.request(`${this.computedProperties.connectionUrl}?query=${encodeURIComponent(queryArg)}`, { const response = await this.webrequestInstance.request(
method: 'POST', `${this.computedProperties.connectionUrl}?query=${encodeURIComponent(queryArg)}`,
headers: this.getHeaders(), {
}); method: 'POST',
headers: this.getHeaders(),
}
);
// console.log('==================='); // console.log('===================');
// console.log(this.computedProperties.connectionUrl); // console.log(this.computedProperties.connectionUrl);
// console.log(queryArg); // console.log(queryArg);
@ -66,22 +71,24 @@ export class ClickhouseHttpClient {
} }
} else { } else {
} }
return returnArray return returnArray;
} }
public async insertPromise(databaseArg: string, tableArg: string, documents: any[]) { public async insertPromise(databaseArg: string, tableArg: string, documents: any[]) {
const queryArg = `INSERT INTO ${databaseArg}.${tableArg} FORMAT JSONEachRow`; const queryArg = `INSERT INTO ${databaseArg}.${tableArg} FORMAT JSONEachRow`;
const response = await this.webrequestInstance.request(`${this.computedProperties.connectionUrl}?query=${encodeURIComponent(queryArg)}`, { const response = await this.webrequestInstance.request(
method: 'POST', `${this.computedProperties.connectionUrl}?query=${encodeURIComponent(queryArg)}`,
body: documents.map(docArg => JSON.stringify(docArg)).join('\n'), {
headers: this.getHeaders() method: 'POST',
}); body: documents.map((docArg) => JSON.stringify(docArg)).join('\n'),
headers: this.getHeaders(),
}
);
return response; return response;
} }
private getHeaders() { private getHeaders() {
const headers: {[key: string]: string} = {} const headers: { [key: string]: string } = {};
if (this.options.username) { if (this.options.username) {
headers['X-ClickHouse-User'] = this.options.username; headers['X-ClickHouse-User'] = this.options.username;
} }

View File

@ -39,13 +39,15 @@ export class SmartClickHouseDb {
if (dropOld) { if (dropOld) {
await this.clickhouseClient.queryPromise(`DROP DATABASE IF EXISTS ${this.options.database}`); await this.clickhouseClient.queryPromise(`DROP DATABASE IF EXISTS ${this.options.database}`);
} }
await this.clickhouseClient.queryPromise(`CREATE DATABASE IF NOT EXISTS ${this.options.database}`); await this.clickhouseClient.queryPromise(
`CREATE DATABASE IF NOT EXISTS ${this.options.database}`
);
} }
public async pingDatabaseUntilAvailable() { public async pingDatabaseUntilAvailable() {
let available = false; let available = false;
while(!available) { while (!available) {
available = await this.clickhouseClient.ping().catch(err => { available = await this.clickhouseClient.ping().catch((err) => {
return false; return false;
}); });
if (!available) { if (!available) {

View File

@ -1,7 +1,12 @@
import * as plugins from './smartclickhouse.plugins.js'; import * as plugins from './smartclickhouse.plugins.js';
import { SmartClickHouseDb } from './smartclickhouse.classes.smartclickhouse.js'; import { SmartClickHouseDb } from './smartclickhouse.classes.smartclickhouse.js';
export type TClickhouseColumnDataType = 'String' | "DateTime64(3, 'Europe/Berlin')" | 'Float64' | 'Array(String)' | 'Array(Float64)'; export type TClickhouseColumnDataType =
| 'String'
| "DateTime64(3, 'Europe/Berlin')"
| 'Float64'
| 'Array(String)'
| 'Array(Float64)';
export interface IColumnInfo { export interface IColumnInfo {
database: string; database: string;
table: string; table: string;
@ -35,7 +40,7 @@ export class TimeDataTable {
public static async getTable(smartClickHouseDbRefArg: SmartClickHouseDb, tableNameArg: string) { public static async getTable(smartClickHouseDbRefArg: SmartClickHouseDb, tableNameArg: string) {
const newTable = new TimeDataTable(smartClickHouseDbRefArg, { const newTable = new TimeDataTable(smartClickHouseDbRefArg, {
tableName: tableNameArg, tableName: tableNameArg,
retainDataForDays: 30 retainDataForDays: 30,
}); });
await newTable.setup(); await newTable.setup();
@ -55,21 +60,19 @@ export class TimeDataTable {
public async setup() { public async setup() {
// create table in clickhouse // create table in clickhouse
await this.smartClickHouseDbRef.clickhouseClient await this.smartClickHouseDbRef.clickhouseClient.queryPromise(`
.queryPromise(`
CREATE TABLE IF NOT EXISTS ${this.smartClickHouseDbRef.options.database}.${this.options.tableName} ( CREATE TABLE IF NOT EXISTS ${this.smartClickHouseDbRef.options.database}.${this.options.tableName} (
timestamp DateTime64(3, 'Europe/Berlin'), timestamp DateTime64(3, 'Europe/Berlin'),
message String message String
) ENGINE=MergeTree() ORDER BY timestamp`); ) ENGINE=MergeTree() ORDER BY timestamp`);
// lets adjust the TTL // lets adjust the TTL
await this.smartClickHouseDbRef.clickhouseClient await this.smartClickHouseDbRef.clickhouseClient.queryPromise(`
.queryPromise(`
ALTER TABLE ${this.smartClickHouseDbRef.options.database}.${this.options.tableName} MODIFY TTL toDateTime(timestamp) + INTERVAL ${this.options.retainDataForDays} DAY ALTER TABLE ${this.smartClickHouseDbRef.options.database}.${this.options.tableName} MODIFY TTL toDateTime(timestamp) + INTERVAL ${this.options.retainDataForDays} DAY
`); `);
await this.updateColumns(); await this.updateColumns();
console.log(`=======================`) console.log(`=======================`);
console.log( console.log(
`table with name "${this.options.tableName}" in database ${this.smartClickHouseDbRef.options.database} has the following columns:` `table with name "${this.options.tableName}" in database ${this.smartClickHouseDbRef.options.database} has the following columns:`
); );
@ -107,23 +110,27 @@ export class TimeDataTable {
// helper stuff // helper stuff
const getClickhouseTypeForValue = (valueArg: any): TClickhouseColumnDataType => { const getClickhouseTypeForValue = (valueArg: any): TClickhouseColumnDataType => {
const typeConversion: {[key: string]: TClickhouseColumnDataType} = { const typeConversion: { [key: string]: TClickhouseColumnDataType } = {
string: 'String', string: 'String',
number: 'Float64', number: 'Float64',
undefined: null, undefined: null,
null: null null: null,
}; };
if (valueArg instanceof Array) { if (valueArg instanceof Array) {
const arrayType = typeConversion[(typeof valueArg[0]) as string]; const arrayType = typeConversion[typeof valueArg[0] as string];
if (!arrayType) { if (!arrayType) {
return null; return null;
} else { } else {
return `Array(${arrayType})` as TClickhouseColumnDataType; return `Array(${arrayType})` as TClickhouseColumnDataType;
} }
} }
return typeConversion[(typeof valueArg) as string]; return typeConversion[typeof valueArg as string];
} };
const checkPath = async (pathArg: string, typeArg: TClickhouseColumnDataType, prechecked = false) => { const checkPath = async (
pathArg: string,
typeArg: TClickhouseColumnDataType,
prechecked = false
) => {
let columnFound = false; let columnFound = false;
for (const column of this.columns) { for (const column of this.columns) {
if (pathArg === column.name) { if (pathArg === column.name) {
@ -137,12 +144,12 @@ export class TimeDataTable {
await checkPath(pathArg, typeArg, true); await checkPath(pathArg, typeArg, true);
return; return;
} }
const alterString = `ALTER TABLE ${this.smartClickHouseDbRef.options.database}.${this.options.tableName} ADD COLUMN ${pathArg} ${typeArg} FIRST` const alterString = `ALTER TABLE ${this.smartClickHouseDbRef.options.database}.${this.options.tableName} ADD COLUMN ${pathArg} ${typeArg} FIRST`;
try { try {
await this.smartClickHouseDbRef.clickhouseClient.queryPromise(` await this.smartClickHouseDbRef.clickhouseClient.queryPromise(`
${alterString} ${alterString}
`); `);
} catch(err) { } catch (err) {
console.log(alterString); console.log(alterString);
for (const column of this.columns) { for (const column of this.columns) {
console.log(column.name); console.log(column.name);
@ -171,21 +178,23 @@ export class TimeDataTable {
storageJson[key] = value; storageJson[key] = value;
} }
const result = await this.smartClickHouseDbRef.clickhouseClient.insertPromise(this.smartClickHouseDbRef.options.database, this.options.tableName, [ const result = await this.smartClickHouseDbRef.clickhouseClient
storageJson, .insertPromise(this.smartClickHouseDbRef.options.database, this.options.tableName, [
]).catch(async () => { storageJson,
if (this.healingDeferred) { ])
return; .catch(async () => {
} if (this.healingDeferred) {
this.healingDeferred = plugins.smartpromise.defer(); return;
console.log(`Ran into an error. Trying to set up things properly again.`); }
await this.smartClickHouseDbRef.pingDatabaseUntilAvailable(); this.healingDeferred = plugins.smartpromise.defer();
await this.smartClickHouseDbRef.createDatabase(); console.log(`Ran into an error. Trying to set up things properly again.`);
await this.setup(); await this.smartClickHouseDbRef.pingDatabaseUntilAvailable();
this.columns = []; await this.smartClickHouseDbRef.createDatabase();
this.healingDeferred.resolve(); await this.setup();
this.healingDeferred = null; this.columns = [];
}); this.healingDeferred.resolve();
this.healingDeferred = null;
});
return result; return result;
} }
} }

View File

@ -5,10 +5,4 @@ import * as smartpromise from '@pushrocks/smartpromise';
import * as smarturl from '@pushrocks/smarturl'; import * as smarturl from '@pushrocks/smarturl';
import * as webrequest from '@pushrocks/webrequest'; import * as webrequest from '@pushrocks/webrequest';
export { export { smartdelay, smartobject, smartpromise, smarturl, webrequest };
smartdelay,
smartobject,
smartpromise,
smarturl,
webrequest,
}