@bmfk/api 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/LICENSE +21 -0
- package/README.md +1293 -2
- package/dist/apiServer/APIService.d.ts +125 -0
- package/dist/apiServer/APIService.js +769 -0
- package/dist/apiServer/BaseEndpoint.d.ts +90 -0
- package/dist/apiServer/BaseEndpoint.js +314 -0
- package/dist/apiServer/BaseService.d.ts +17 -0
- package/dist/apiServer/BaseService.js +39 -0
- package/dist/apiServer/DBService.d.ts +131 -0
- package/dist/apiServer/DBService.js +290 -0
- package/dist/apiServer/DocumentService.d.ts +9 -0
- package/dist/apiServer/DocumentService.js +65 -0
- package/dist/apiServer/LocalRequest.d.ts +3 -0
- package/dist/apiServer/LocalRequest.js +6 -0
- package/dist/apiServer/LogService.d.ts +78 -0
- package/dist/apiServer/LogService.js +349 -0
- package/dist/apiServer/MonitorService.d.ts +102 -0
- package/dist/apiServer/MonitorService.js +615 -0
- package/dist/apiServer/StatService.d.ts +4 -0
- package/dist/apiServer/StatService.js +10 -0
- package/dist/apiServer/TimeframeService.d.ts +28 -0
- package/dist/apiServer/TimeframeService.js +97 -0
- package/dist/apiServer/WebSocketServer.d.ts +39 -0
- package/dist/apiServer/WebSocketServer.js +173 -0
- package/dist/apiServer/db/IDBAdapter.d.ts +14 -0
- package/dist/apiServer/db/IDBAdapter.js +2 -0
- package/dist/apiServer/db/MysqlAdapter.d.ts +72 -0
- package/dist/apiServer/db/MysqlAdapter.js +869 -0
- package/dist/apiServer/db/PostgresAdapter.d.ts +41 -0
- package/dist/apiServer/db/PostgresAdapter.js +73 -0
- package/dist/apiServer/deployment/AccessConfigWizard.d.ts +5 -0
- package/dist/apiServer/deployment/AccessConfigWizard.js +254 -0
- package/dist/apiServer/deployment/Activate.d.ts +4 -0
- package/dist/apiServer/deployment/Activate.js +124 -0
- package/dist/apiServer/deployment/BackupManager.d.ts +33 -0
- package/dist/apiServer/deployment/BackupManager.js +174 -0
- package/dist/apiServer/deployment/Backups.d.ts +2 -0
- package/dist/apiServer/deployment/Backups.js +44 -0
- package/dist/apiServer/deployment/BlueGreenState.d.ts +31 -0
- package/dist/apiServer/deployment/BlueGreenState.js +150 -0
- package/dist/apiServer/deployment/Bundler.d.ts +12 -0
- package/dist/apiServer/deployment/Bundler.js +178 -0
- package/dist/apiServer/deployment/ConfigService.d.ts +203 -0
- package/dist/apiServer/deployment/ConfigService.js +195 -0
- package/dist/apiServer/deployment/Deploy.d.ts +4 -0
- package/dist/apiServer/deployment/Deploy.js +404 -0
- package/dist/apiServer/deployment/DeployKeyWizard.d.ts +2 -0
- package/dist/apiServer/deployment/DeployKeyWizard.js +84 -0
- package/dist/apiServer/deployment/Deployer.d.ts +13 -0
- package/dist/apiServer/deployment/Deployer.js +96 -0
- package/dist/apiServer/deployment/DeployerInit.d.ts +25 -0
- package/dist/apiServer/deployment/DeployerInit.js +214 -0
- package/dist/apiServer/deployment/DeployerService.d.ts +378 -0
- package/dist/apiServer/deployment/DeployerService.js +1553 -0
- package/dist/apiServer/deployment/HashPassword.d.ts +3 -0
- package/dist/apiServer/deployment/HashPassword.js +126 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.d.ts +1 -0
- package/dist/apiServer/deployment/MigrateConfigsWizard.js +202 -0
- package/dist/apiServer/deployment/MigrateProject.d.ts +31 -0
- package/dist/apiServer/deployment/MigrateProject.js +335 -0
- package/dist/apiServer/deployment/NginxHelper.d.ts +10 -0
- package/dist/apiServer/deployment/NginxHelper.js +111 -0
- package/dist/apiServer/deployment/Notifier.d.ts +30 -0
- package/dist/apiServer/deployment/Notifier.js +82 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/ProjectConfigWizard.js +148 -0
- package/dist/apiServer/deployment/Restore.d.ts +2 -0
- package/dist/apiServer/deployment/Restore.js +89 -0
- package/dist/apiServer/deployment/ReviewStore.d.ts +62 -0
- package/dist/apiServer/deployment/ReviewStore.js +186 -0
- package/dist/apiServer/deployment/SecretsInjector.d.ts +21 -0
- package/dist/apiServer/deployment/SecretsInjector.js +189 -0
- package/dist/apiServer/deployment/SetupConfigWizard.d.ts +1 -0
- package/dist/apiServer/deployment/SetupConfigWizard.js +238 -0
- package/dist/apiServer/deployment/Status.d.ts +2 -0
- package/dist/apiServer/deployment/Status.js +83 -0
- package/dist/apiServer/deployment/TelegramNotifier.d.ts +8 -0
- package/dist/apiServer/deployment/TelegramNotifier.js +23 -0
- package/dist/apiServer/deployment/Watchdog.d.ts +15 -0
- package/dist/apiServer/deployment/Watchdog.js +65 -0
- package/dist/apiServer/deployment/Wizards.d.ts +1 -0
- package/dist/apiServer/deployment/Wizards.js +83 -0
- package/dist/apiServer/deployment/cli.d.ts +2 -0
- package/dist/apiServer/deployment/cli.js +224 -0
- package/dist/apiServer/deployment/cliCommon.d.ts +27 -0
- package/dist/apiServer/deployment/cliCommon.js +110 -0
- package/dist/apiServer/deployment/cliPrompt.d.ts +5 -0
- package/dist/apiServer/deployment/cliPrompt.js +38 -0
- package/dist/apiServer/deployment/resolveConfig.d.ts +19 -0
- package/dist/apiServer/deployment/resolveConfig.js +139 -0
- package/dist/apiServer/documentation/Documentation.d.ts +18 -0
- package/dist/apiServer/documentation/Documentation.js +143 -0
- package/dist/apiServer/documentation/index.html +460 -0
- package/dist/apiServer/external/MicroserviceClient.d.ts +28 -0
- package/dist/apiServer/external/MicroserviceClient.js +144 -0
- package/dist/apiServer/external/MicroserviceHost.d.ts +52 -0
- package/dist/apiServer/external/MicroserviceHost.js +183 -0
- package/dist/apiServer/external/MicroserviceHostController.d.ts +6 -0
- package/dist/apiServer/external/MicroserviceHostController.js +65 -0
- package/dist/apiServer/helper/AppDataPath.d.ts +9 -0
- package/dist/apiServer/helper/AppDataPath.js +81 -0
- package/dist/apiServer/helper/ClientIp.d.ts +3 -0
- package/dist/apiServer/helper/ClientIp.js +33 -0
- package/dist/apiServer/helper/DataProvider.d.ts +18 -0
- package/dist/apiServer/helper/DataProvider.js +57 -0
- package/dist/apiServer/helper/IpAllowList.d.ts +8 -0
- package/dist/apiServer/helper/IpAllowList.js +40 -0
- package/dist/apiServer/helper/JSONStableStringify.d.ts +1 -0
- package/dist/apiServer/helper/JSONStableStringify.js +15 -0
- package/dist/apiServer/helper/PasswordHash.d.ts +5 -0
- package/dist/apiServer/helper/PasswordHash.js +52 -0
- package/dist/apiServer/helper/Sleep.d.ts +1 -0
- package/dist/apiServer/helper/Sleep.js +5 -0
- package/dist/apiServer/helper/Trace.d.ts +8 -0
- package/dist/apiServer/helper/Trace.js +30 -0
- package/dist/apiServer/helper/UID.d.ts +16 -0
- package/dist/apiServer/helper/UID.js +98 -0
- package/dist/apiServer/helper/Validator.d.ts +86 -0
- package/dist/apiServer/helper/Validator.js +560 -0
- package/dist/apiServer/helper/YYYYMMDDHH.d.ts +2 -0
- package/dist/apiServer/helper/YYYYMMDDHH.js +31 -0
- package/dist/apiServer/helper/ZipUtils.d.ts +6 -0
- package/dist/apiServer/helper/ZipUtils.js +28 -0
- package/dist/apiServer/http/Http.d.ts +183 -0
- package/dist/apiServer/http/Http.js +627 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.d.ts +19 -0
- package/dist/apiServer/interceptors/InterceptorPayAuth.js +124 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.d.ts +40 -0
- package/dist/apiServer/interceptors/InterceptorSignedAuth.js +150 -0
- package/dist/apiServer/monitor/AccessStore.d.ts +27 -0
- package/dist/apiServer/monitor/AccessStore.js +163 -0
- package/dist/apiServer/monitor/LogFiles.d.ts +34 -0
- package/dist/apiServer/monitor/LogFiles.js +109 -0
- package/dist/apiServer/monitor/Monitor.d.ts +54 -0
- package/dist/apiServer/monitor/Monitor.js +447 -0
- package/dist/apiServer/monitor/MonitorAuth.d.ts +87 -0
- package/dist/apiServer/monitor/MonitorAuth.js +474 -0
- package/dist/apiServer/monitor/ProcessMonitor.d.ts +177 -0
- package/dist/apiServer/monitor/ProcessMonitor.js +468 -0
- package/dist/apiServer/monitor/SystemInfo.d.ts +70 -0
- package/dist/apiServer/monitor/SystemInfo.js +217 -0
- package/dist/apiServer/monitor/ThreatMonitor.d.ts +73 -0
- package/dist/apiServer/monitor/ThreatMonitor.js +239 -0
- package/dist/apiServer/monitor/index.html +591 -0
- package/dist/apiServer/review/Review.d.ts +23 -0
- package/dist/apiServer/review/Review.js +149 -0
- package/dist/apiServer/review/ReviewAuth.d.ts +56 -0
- package/dist/apiServer/review/ReviewAuth.js +147 -0
- package/dist/apiServer/review/ReviewDiff.d.ts +43 -0
- package/dist/apiServer/review/ReviewDiff.js +175 -0
- package/dist/apiServer/review/index.html +501 -0
- package/dist/apiServer/routes/Liveness.d.ts +7 -0
- package/dist/apiServer/routes/Liveness.js +27 -0
- package/dist/apiServer/routes/Readiness.d.ts +13 -0
- package/dist/apiServer/routes/Readiness.js +20 -0
- package/dist/apiServer/security/BlockedIps.d.ts +46 -0
- package/dist/apiServer/security/BlockedIps.js +185 -0
- package/dist/apiServer/structures/DefaultErrors.d.ts +36 -0
- package/dist/apiServer/structures/DefaultErrors.js +52 -0
- package/dist/apiServer/structures/HTTPStatus.d.ts +7 -0
- package/dist/apiServer/structures/HTTPStatus.js +11 -0
- package/dist/apiServer/structures/Interfaces.d.ts +55 -0
- package/dist/apiServer/structures/Interfaces.js +2 -0
- package/dist/index.d.ts +45 -0
- package/dist/index.js +110 -0
- package/dist/signal/Signal.d.ts +23 -0
- package/dist/signal/Signal.js +85 -0
- package/package.json +88 -4
|
@@ -0,0 +1,869 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.MysqlAdapter = void 0;
|
|
7
|
+
exports.isError = isError;
|
|
8
|
+
const promise_1 = __importDefault(require("mysql2/promise"));
|
|
9
|
+
const fs_1 = __importDefault(require("fs"));
|
|
10
|
+
const LogService_1 = require("../LogService");
|
|
11
|
+
const DefaultErrors_1 = __importDefault(require("../structures/DefaultErrors"));
|
|
12
|
+
const path_1 = __importDefault(require("path"));
|
|
13
|
+
const MonitorService_1 = require("../MonitorService");
|
|
14
|
+
const YYYYMMDDHH_1 = require("../helper/YYYYMMDDHH");
|
|
15
|
+
class MysqlAdapter {
|
|
16
|
+
options;
|
|
17
|
+
serviceStarted = false;
|
|
18
|
+
reconnectionTimeout = 1000 * 3;
|
|
19
|
+
reconnecting = false;
|
|
20
|
+
pool = null;
|
|
21
|
+
timeoutID;
|
|
22
|
+
queries = [];
|
|
23
|
+
static nextTransactionID = 1;
|
|
24
|
+
transactions = [];
|
|
25
|
+
maxTransactionWaitTime = 1000 * 60 * 2;
|
|
26
|
+
lastSuccessQueryTime = 0;
|
|
27
|
+
pingInterval = 1000 * 60 * 5;
|
|
28
|
+
failReportFileStream = null;
|
|
29
|
+
failReportFileStreamName = null;
|
|
30
|
+
failReportLastAccessTime = 0;
|
|
31
|
+
poolConnections = 0;
|
|
32
|
+
acquiredPoolConnections = 0;
|
|
33
|
+
statFrames = new Map();
|
|
34
|
+
constructor(options) {
|
|
35
|
+
this.options = options;
|
|
36
|
+
}
|
|
37
|
+
escape(value) {
|
|
38
|
+
return promise_1.default.escape(value);
|
|
39
|
+
}
|
|
40
|
+
stat() {
|
|
41
|
+
return this.statFrames;
|
|
42
|
+
}
|
|
43
|
+
statRetentionMs = 5 * 24 * 60 * 60 * 1000;
|
|
44
|
+
getOrCreateStatSlot(date = new Date()) {
|
|
45
|
+
const key = parseInt((0, YYYYMMDDHH_1.YYYYMMDDHH)(date, "yyyymmddhhmm"));
|
|
46
|
+
let slot = this.statFrames.get(key);
|
|
47
|
+
if (slot)
|
|
48
|
+
return slot;
|
|
49
|
+
slot = {
|
|
50
|
+
transactionsCount: 0,
|
|
51
|
+
averageQueryTime: 0,
|
|
52
|
+
totalQueries: 0,
|
|
53
|
+
maxQueryTime: 0,
|
|
54
|
+
minQueryTime: 0,
|
|
55
|
+
failedQueries: 0,
|
|
56
|
+
longestQueries: []
|
|
57
|
+
};
|
|
58
|
+
this.statFrames.set(key, slot);
|
|
59
|
+
const cutoff = parseInt((0, YYYYMMDDHH_1.YYYYMMDDHH)(new Date(date.getTime() - this.statRetentionMs), "yyyymmddhhmm"));
|
|
60
|
+
for (const k of this.statFrames.keys()) {
|
|
61
|
+
if (k < cutoff)
|
|
62
|
+
this.statFrames.delete(k);
|
|
63
|
+
}
|
|
64
|
+
return slot;
|
|
65
|
+
}
|
|
66
|
+
collectStat(query, execTime, failed) {
|
|
67
|
+
const slot = this.getOrCreateStatSlot();
|
|
68
|
+
slot.totalQueries++;
|
|
69
|
+
if (failed)
|
|
70
|
+
slot.failedQueries++;
|
|
71
|
+
slot.averageQueryTime += (execTime - slot.averageQueryTime) / slot.totalQueries;
|
|
72
|
+
if (slot.totalQueries === 1) {
|
|
73
|
+
slot.maxQueryTime = execTime;
|
|
74
|
+
slot.minQueryTime = execTime;
|
|
75
|
+
}
|
|
76
|
+
else {
|
|
77
|
+
if (execTime > slot.maxQueryTime)
|
|
78
|
+
slot.maxQueryTime = execTime;
|
|
79
|
+
if (execTime < slot.minQueryTime)
|
|
80
|
+
slot.minQueryTime = execTime;
|
|
81
|
+
}
|
|
82
|
+
const truncated = query.length > 100 ? query.substring(0, 100) : query;
|
|
83
|
+
if (slot.longestQueries.length < 5 || execTime > slot.longestQueries[slot.longestQueries.length - 1].execution) {
|
|
84
|
+
slot.longestQueries.push({ query: truncated, execution: execTime });
|
|
85
|
+
slot.longestQueries.sort((a, b) => b.execution - a.execution);
|
|
86
|
+
if (slot.longestQueries.length > 5)
|
|
87
|
+
slot.longestQueries.length = 5;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
collectTransactionStat() {
|
|
91
|
+
this.getOrCreateStatSlot().transactionsCount++;
|
|
92
|
+
}
|
|
93
|
+
async init() {
|
|
94
|
+
if (this.options.transactionFailReportDir) {
|
|
95
|
+
try {
|
|
96
|
+
if (!fs_1.default.existsSync(this.options.transactionFailReportDir))
|
|
97
|
+
fs_1.default.mkdirSync(this.options.transactionFailReportDir);
|
|
98
|
+
}
|
|
99
|
+
catch (e) {
|
|
100
|
+
this.options.transactionFailReportDir = undefined;
|
|
101
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't create transaction fail report dir");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
this.serviceStarted = false;
|
|
105
|
+
let poolCreated = false;
|
|
106
|
+
while (!poolCreated) {
|
|
107
|
+
poolCreated = await this.recreatePool();
|
|
108
|
+
if (!poolCreated) {
|
|
109
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't connect to MYSQL! Retrying in 3 seconds...");
|
|
110
|
+
await new Promise((resolve) => setTimeout(resolve, 3000));
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
this.setupTimers();
|
|
114
|
+
}
|
|
115
|
+
poolStatus() {
|
|
116
|
+
return {
|
|
117
|
+
lastSuccessQueryTime: new Date(this.lastSuccessQueryTime).toISOString(),
|
|
118
|
+
poolConnections: this.poolConnections,
|
|
119
|
+
acquiredPoolConnections: this.acquiredPoolConnections
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
isCleanupRunning = false;
|
|
123
|
+
setupTimers() {
|
|
124
|
+
setInterval(async () => {
|
|
125
|
+
if (this.isCleanupRunning) {
|
|
126
|
+
(0, LogService_1.logError)("MysqlAdapter", "Cleanup already running, skipping this iteration");
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
this.isCleanupRunning = true;
|
|
130
|
+
try {
|
|
131
|
+
const now = Date.now();
|
|
132
|
+
const count = this.transactions.length;
|
|
133
|
+
const removedIDs = [];
|
|
134
|
+
for (let i of this.transactions) {
|
|
135
|
+
if (now - i.timestamp > this.maxTransactionWaitTime) {
|
|
136
|
+
(0, LogService_1.logError)("Release transaction connection due to timeout");
|
|
137
|
+
await this.rollbackTransaction(i, true);
|
|
138
|
+
removedIDs.push(i.id);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
this.transactions = this.transactions.filter(i => !removedIDs.includes(i.id));
|
|
142
|
+
if (this.options.debug && count - this.transactions.length > 0)
|
|
143
|
+
(0, LogService_1.logDB)("Removed: ", count - this.transactions.length);
|
|
144
|
+
if (this.pool && Date.now() - this.lastSuccessQueryTime > this.pingInterval) {
|
|
145
|
+
for (let i = 0; i < this.options.connectionLimit; i++) {
|
|
146
|
+
this.query({ query: "SELECT 1 @NOLIMIT" });
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
finally {
|
|
151
|
+
this.isCleanupRunning = false;
|
|
152
|
+
}
|
|
153
|
+
}, 1000 * 30);
|
|
154
|
+
setInterval(() => {
|
|
155
|
+
if (!this.failReportFileStream)
|
|
156
|
+
return;
|
|
157
|
+
if (Date.now() - this.failReportLastAccessTime > 1000 * 60 * 15) {
|
|
158
|
+
this.failReportFileStream.end();
|
|
159
|
+
this.failReportFileStream = null;
|
|
160
|
+
}
|
|
161
|
+
}, 1000 * 60 * 5);
|
|
162
|
+
}
|
|
163
|
+
async recreatePool() {
|
|
164
|
+
const opt = {
|
|
165
|
+
host: this.options.host,
|
|
166
|
+
user: this.options.user,
|
|
167
|
+
password: this.options.password,
|
|
168
|
+
database: this.options.database,
|
|
169
|
+
port: this.options.port,
|
|
170
|
+
connectionLimit: this.options.connectionLimit,
|
|
171
|
+
queueLimit: this.options.queueLimit ?? 50,
|
|
172
|
+
multipleStatements: true,
|
|
173
|
+
enableKeepAlive: true,
|
|
174
|
+
keepAliveInitialDelay: 3 * 1000,
|
|
175
|
+
idleTimeout: 1000 * 60 * 5
|
|
176
|
+
};
|
|
177
|
+
(0, LogService_1.logDB)("${MysqlAdapter.js}", "Connecting to mysql: \n " + JSON.stringify({ ...opt, password: "****" }, null, "\t"));
|
|
178
|
+
if (this.pool) {
|
|
179
|
+
this.pool.removeAllListeners();
|
|
180
|
+
try {
|
|
181
|
+
await this.pool.end();
|
|
182
|
+
}
|
|
183
|
+
catch (e) {
|
|
184
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't close MYSQL pool! " + e);
|
|
185
|
+
}
|
|
186
|
+
this.pool = null;
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
this.pool = promise_1.default.createPool(opt);
|
|
190
|
+
}
|
|
191
|
+
catch (e) {
|
|
192
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't connect to MYSQL! " + e);
|
|
193
|
+
return false;
|
|
194
|
+
}
|
|
195
|
+
this.poolConnections = 0;
|
|
196
|
+
this.acquiredPoolConnections = 0;
|
|
197
|
+
this.pool?.on('connection', (connection) => {
|
|
198
|
+
(0, LogService_1.logDB)("MysqlAdapter", "pool -> connection created, total:" + this.poolConnections++);
|
|
199
|
+
});
|
|
200
|
+
this.pool?.on('acquire', (connection) => {
|
|
201
|
+
this.acquiredPoolConnections++;
|
|
202
|
+
});
|
|
203
|
+
this.pool?.on('release', (connection) => {
|
|
204
|
+
this.acquiredPoolConnections--;
|
|
205
|
+
});
|
|
206
|
+
this.pool?.on('enqueue', () => {
|
|
207
|
+
(0, LogService_1.logDB)("MysqlAdapter", "pool -> waiting for available connection");
|
|
208
|
+
});
|
|
209
|
+
const res = await this.query({ query: "SELECT 1 @NOLIMIT" });
|
|
210
|
+
if (res.error) {
|
|
211
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "pool -> check connection livenes was failed: " + res.error.message);
|
|
212
|
+
return false;
|
|
213
|
+
}
|
|
214
|
+
return true;
|
|
215
|
+
}
|
|
216
|
+
async tBegin() {
|
|
217
|
+
const executionStartTime = Date.now();
|
|
218
|
+
const conn = await this.getConnection();
|
|
219
|
+
if (isError(conn))
|
|
220
|
+
return {
|
|
221
|
+
error: conn,
|
|
222
|
+
execution: {
|
|
223
|
+
started_at: executionStartTime,
|
|
224
|
+
finished_at: Date.now()
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
for (let i of this.transactions) {
|
|
228
|
+
if (i.conn === conn) {
|
|
229
|
+
(0, LogService_1.logError)("Selected connection is in transaction");
|
|
230
|
+
return {
|
|
231
|
+
error: {
|
|
232
|
+
errno: 100005,
|
|
233
|
+
code: "CONN_IN_TRX",
|
|
234
|
+
fatal: true,
|
|
235
|
+
sql: "START TRANSACTION",
|
|
236
|
+
name: "CONN_IN_TRX",
|
|
237
|
+
message: "Selected connection already in transaction",
|
|
238
|
+
isDuplicateError: false
|
|
239
|
+
},
|
|
240
|
+
execution: {
|
|
241
|
+
started_at: executionStartTime,
|
|
242
|
+
finished_at: Date.now()
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const trxid = MysqlAdapter.nextTransactionID++;
|
|
248
|
+
if (this.options.debug)
|
|
249
|
+
(0, LogService_1.logDB)("Begin transaction with id ", trxid);
|
|
250
|
+
const result = await this.query({ query: "START TRANSACTION" }, conn);
|
|
251
|
+
const trxRequest = {
|
|
252
|
+
id: trxid,
|
|
253
|
+
timestamp: Date.now(),
|
|
254
|
+
conn: conn,
|
|
255
|
+
queries: []
|
|
256
|
+
};
|
|
257
|
+
if (result.error) {
|
|
258
|
+
(0, LogService_1.logCrit)("Can't start transaction! " + result.error.message);
|
|
259
|
+
trxRequest.queries.push({ sql: "START TRANSACTION", status: "error" });
|
|
260
|
+
await this.rollbackTransaction(trxRequest);
|
|
261
|
+
return result;
|
|
262
|
+
}
|
|
263
|
+
trxRequest.queries.push({ sql: "START TRANSACTION", status: "ok" });
|
|
264
|
+
this.transactions.push(trxRequest);
|
|
265
|
+
this.collectTransactionStat();
|
|
266
|
+
if (this.options.debug)
|
|
267
|
+
(0, LogService_1.logDB)("Transactions pool: ", this.transactions.map(t => "id:" + t.id + ", queries: " + t.queries.length));
|
|
268
|
+
return {
|
|
269
|
+
data: { transactionId: trxid },
|
|
270
|
+
execution: {
|
|
271
|
+
started_at: executionStartTime,
|
|
272
|
+
finished_at: Date.now()
|
|
273
|
+
}
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
async tCommit(trxid) {
|
|
277
|
+
const executionStartTime = Date.now();
|
|
278
|
+
const trx = this.transactions.find(i => i.id === trxid);
|
|
279
|
+
if (!trx) {
|
|
280
|
+
return {
|
|
281
|
+
error: {
|
|
282
|
+
code: "NO_TRX",
|
|
283
|
+
errno: 100004,
|
|
284
|
+
fatal: true,
|
|
285
|
+
sql: "",
|
|
286
|
+
name: "NO_TRX",
|
|
287
|
+
message: "Transaction not found",
|
|
288
|
+
isDuplicateError: false
|
|
289
|
+
},
|
|
290
|
+
execution: {
|
|
291
|
+
started_at: executionStartTime,
|
|
292
|
+
finished_at: Date.now()
|
|
293
|
+
}
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
if (this.options.debug)
|
|
297
|
+
(0, LogService_1.logDB)("Commit transaction:", trx.id);
|
|
298
|
+
if (this.options.debug)
|
|
299
|
+
(0, LogService_1.logDB)("Transaction pool:", this.transactions);
|
|
300
|
+
const err = await this.commit(trx);
|
|
301
|
+
if (err)
|
|
302
|
+
return {
|
|
303
|
+
error: err,
|
|
304
|
+
execution: {
|
|
305
|
+
started_at: executionStartTime,
|
|
306
|
+
finished_at: Date.now()
|
|
307
|
+
}
|
|
308
|
+
};
|
|
309
|
+
return {
|
|
310
|
+
data: true,
|
|
311
|
+
execution: {
|
|
312
|
+
started_at: executionStartTime,
|
|
313
|
+
finished_at: Date.now()
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
async tRollback(trxid) {
|
|
318
|
+
const executionStartTime = Date.now();
|
|
319
|
+
const trx = this.transactions.find(i => i.id === trxid);
|
|
320
|
+
if (!trx) {
|
|
321
|
+
return {
|
|
322
|
+
error: {
|
|
323
|
+
code: "NO_TRX",
|
|
324
|
+
errno: 100004,
|
|
325
|
+
fatal: true,
|
|
326
|
+
sql: "",
|
|
327
|
+
name: "NO_TRX",
|
|
328
|
+
message: "Transaction not found",
|
|
329
|
+
isDuplicateError: false
|
|
330
|
+
},
|
|
331
|
+
execution: {
|
|
332
|
+
started_at: executionStartTime,
|
|
333
|
+
finished_at: Date.now()
|
|
334
|
+
}
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
const err = await this.rollbackTransaction(trx);
|
|
338
|
+
if (err) {
|
|
339
|
+
return {
|
|
340
|
+
error: err,
|
|
341
|
+
execution: {
|
|
342
|
+
started_at: executionStartTime,
|
|
343
|
+
finished_at: Date.now()
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
return {
|
|
348
|
+
data: true,
|
|
349
|
+
execution: {
|
|
350
|
+
started_at: executionStartTime,
|
|
351
|
+
finished_at: Date.now()
|
|
352
|
+
}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
async bulk(request) {
|
|
356
|
+
const executionStartTime = Date.now();
|
|
357
|
+
const results = [];
|
|
358
|
+
let queries = [];
|
|
359
|
+
let conn = null;
|
|
360
|
+
if (request.queued) {
|
|
361
|
+
conn = await this.getConnection();
|
|
362
|
+
if (isError(conn)) {
|
|
363
|
+
for (let i of request.bulk)
|
|
364
|
+
results.push({
|
|
365
|
+
data: null, error: conn,
|
|
366
|
+
execution: {
|
|
367
|
+
started_at: executionStartTime,
|
|
368
|
+
finished_at: Date.now()
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
return results;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
for (let i of request.bulk) {
|
|
375
|
+
if (request.queued && conn) {
|
|
376
|
+
const response = await this.query({
|
|
377
|
+
query: i.query,
|
|
378
|
+
fields: i.fields,
|
|
379
|
+
throwable: i.throwable,
|
|
380
|
+
}, conn);
|
|
381
|
+
results.push(response);
|
|
382
|
+
continue;
|
|
383
|
+
}
|
|
384
|
+
queries.push(this.query({
|
|
385
|
+
query: i.query,
|
|
386
|
+
fields: i.fields,
|
|
387
|
+
throwable: i.throwable,
|
|
388
|
+
}));
|
|
389
|
+
}
|
|
390
|
+
if (queries && queries.length > 0) {
|
|
391
|
+
const responses = await Promise.all(queries);
|
|
392
|
+
for (let i of responses)
|
|
393
|
+
results.push(i);
|
|
394
|
+
}
|
|
395
|
+
if (conn) {
|
|
396
|
+
this.finalizeConnection(conn);
|
|
397
|
+
conn = null;
|
|
398
|
+
}
|
|
399
|
+
return results;
|
|
400
|
+
}
|
|
401
|
+
async getConnection(transactionId) {
|
|
402
|
+
if (!this.pool) {
|
|
403
|
+
(0, LogService_1.logError)("${MysqlAdapter.js}", "No pool created, can't execute query");
|
|
404
|
+
return {
|
|
405
|
+
code: "NO_POOL",
|
|
406
|
+
errno: 100000,
|
|
407
|
+
fatal: true,
|
|
408
|
+
sql: "",
|
|
409
|
+
name: "NO_POOL",
|
|
410
|
+
message: "Mysql pool not created",
|
|
411
|
+
isDuplicateError: false
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
try {
|
|
415
|
+
let conn = null;
|
|
416
|
+
if (transactionId && transactionId > 0) {
|
|
417
|
+
conn = this.transactions.find(i => i.id === transactionId)?.conn ?? null;
|
|
418
|
+
if (this.options.debug)
|
|
419
|
+
(0, LogService_1.logDB)("Execute query on transaction: ", conn?.threadId);
|
|
420
|
+
}
|
|
421
|
+
else
|
|
422
|
+
conn = await this.pool.getConnection();
|
|
423
|
+
if (conn)
|
|
424
|
+
return conn;
|
|
425
|
+
}
|
|
426
|
+
catch (e) {
|
|
427
|
+
if (`${e}`.indexOf('ECONNREFUSED') !== -1 || `${e}`.indexOf("PROTOCOL_") !== -1 || `${e}`.includes("closed state")) {
|
|
428
|
+
(0, LogService_1.logError)("Connection looks dead, recreating pool 2");
|
|
429
|
+
this.recreatePool();
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
(0, LogService_1.logCrit)("${MysqlAdapter.js}", `No connection created!`);
|
|
433
|
+
return {
|
|
434
|
+
code: "NO_CONN",
|
|
435
|
+
errno: 100001,
|
|
436
|
+
fatal: true,
|
|
437
|
+
sql: "",
|
|
438
|
+
name: "NO_CONN",
|
|
439
|
+
message: "Mysql pool cant get connection",
|
|
440
|
+
isDuplicateError: false
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
withTimeout(promise, ms, query) {
|
|
444
|
+
return new Promise((resolve, reject) => {
|
|
445
|
+
const timeout = setTimeout(() => {
|
|
446
|
+
reject({
|
|
447
|
+
code: "TIME_OUT",
|
|
448
|
+
errno: 100013,
|
|
449
|
+
sql: query,
|
|
450
|
+
name: "TIME_OUT",
|
|
451
|
+
fatal: true,
|
|
452
|
+
message: "Query timeout reached " + ms
|
|
453
|
+
});
|
|
454
|
+
}, ms);
|
|
455
|
+
promise.then((res) => {
|
|
456
|
+
clearTimeout(timeout);
|
|
457
|
+
resolve(res);
|
|
458
|
+
}).catch((err) => {
|
|
459
|
+
clearTimeout(timeout);
|
|
460
|
+
reject(err);
|
|
461
|
+
});
|
|
462
|
+
});
|
|
463
|
+
}
|
|
464
|
+
async query(request, conn) {
|
|
465
|
+
let executionStartTime = Date.now();
|
|
466
|
+
const query = this.prepareQuery(request);
|
|
467
|
+
const isPing = query.trim().toLowerCase() === "select 1";
|
|
468
|
+
if (this.options.debug || request.debug) {
|
|
469
|
+
if (!isPing)
|
|
470
|
+
(0, LogService_1.logDB)(query);
|
|
471
|
+
}
|
|
472
|
+
if (request.parseQueryOnly) {
|
|
473
|
+
if (conn && !request.transactionID)
|
|
474
|
+
this.finalizeConnection(conn);
|
|
475
|
+
return {
|
|
476
|
+
data: [{ query }],
|
|
477
|
+
error: null,
|
|
478
|
+
execution: {
|
|
479
|
+
started_at: executionStartTime,
|
|
480
|
+
finished_at: Date.now()
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
let doCloseConnection = false;
|
|
485
|
+
if (!conn) {
|
|
486
|
+
doCloseConnection = true;
|
|
487
|
+
conn = await this.getConnection(request.transactionID ?? -1);
|
|
488
|
+
if (isError(conn)) {
|
|
489
|
+
return {
|
|
490
|
+
data: null,
|
|
491
|
+
error: conn,
|
|
492
|
+
execution: {
|
|
493
|
+
started_at: executionStartTime,
|
|
494
|
+
finished_at: Date.now()
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
let trx = null;
|
|
500
|
+
if (request.transactionID)
|
|
501
|
+
trx = this.transactions.find(i => i.id === request.transactionID);
|
|
502
|
+
try {
|
|
503
|
+
let result = null;
|
|
504
|
+
if (this.options.maxQueryTimeout && this.options.maxQueryTimeout > 0)
|
|
505
|
+
result = await this.withTimeout(conn.query(query), this.options.maxQueryTimeout, query);
|
|
506
|
+
else {
|
|
507
|
+
result = await conn.query(query);
|
|
508
|
+
}
|
|
509
|
+
let total = null;
|
|
510
|
+
;
|
|
511
|
+
if (request.calculateCount) {
|
|
512
|
+
const cres = await conn.query(this.prepareCountQuery(query));
|
|
513
|
+
if (cres && cres[0]) {
|
|
514
|
+
const res = cres[0];
|
|
515
|
+
if (Array.isArray(res) && res.length > 0 && "count" in res[0])
|
|
516
|
+
total = res[0].count;
|
|
517
|
+
else if ("count" in res)
|
|
518
|
+
total = res.count;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
this.lastSuccessQueryTime = +new Date();
|
|
522
|
+
if (!request.transactionID && doCloseConnection)
|
|
523
|
+
this.finalizeConnection(conn);
|
|
524
|
+
if (trx)
|
|
525
|
+
trx.queries.push({ sql: query, status: "ok" });
|
|
526
|
+
const finishedAt = Date.now();
|
|
527
|
+
if (!isPing) {
|
|
528
|
+
MonitorService_1.S_STAT_REGISTRATE_SQL_REQUEST.invoke({ success: true, query });
|
|
529
|
+
this.collectStat(query, finishedAt - executionStartTime, false);
|
|
530
|
+
}
|
|
531
|
+
return {
|
|
532
|
+
data: result[0],
|
|
533
|
+
error: null,
|
|
534
|
+
total: total ? total : undefined,
|
|
535
|
+
execution: {
|
|
536
|
+
started_at: executionStartTime,
|
|
537
|
+
finished_at: finishedAt
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
catch (e) {
|
|
542
|
+
if (!isPing) {
|
|
543
|
+
MonitorService_1.S_STAT_REGISTRATE_SQL_REQUEST.invoke({ success: false, query });
|
|
544
|
+
this.collectStat(query, Date.now() - executionStartTime, true);
|
|
545
|
+
}
|
|
546
|
+
const timedOut = e?.code === "TIME_OUT";
|
|
547
|
+
if (timedOut)
|
|
548
|
+
this.killQuery(conn);
|
|
549
|
+
if (!request.transactionID && doCloseConnection) {
|
|
550
|
+
if (timedOut)
|
|
551
|
+
this.destroyConnection(conn);
|
|
552
|
+
else
|
|
553
|
+
this.finalizeConnection(conn);
|
|
554
|
+
}
|
|
555
|
+
else if (request.transactionID && request.throwable) {
|
|
556
|
+
await this.rollbackTransaction(this.transactions.find(i => i.id === request.transactionID));
|
|
557
|
+
}
|
|
558
|
+
if (request.transactionID && request.rollbackOnFail && !request.throwable) {
|
|
559
|
+
await this.rollbackTransaction(this.transactions.find(i => i.id === request.transactionID));
|
|
560
|
+
}
|
|
561
|
+
const error = this.createMysqlQueryError(e);
|
|
562
|
+
if (trx)
|
|
563
|
+
trx.queries.push({ sql: query, status: error.code });
|
|
564
|
+
if (`${e}`.indexOf('ECONNREFUSED') !== -1 || `${e}`.indexOf("PROTOCOL_") !== -1 || error.message.includes("closed state")) {
|
|
565
|
+
(0, LogService_1.logError)("Connection looks dead, recreating pool 1");
|
|
566
|
+
this.recreatePool();
|
|
567
|
+
}
|
|
568
|
+
if (trx && !error.isDuplicateError)
|
|
569
|
+
this.storeTransactionAsProblem(trx, "error:" + error.errno);
|
|
570
|
+
if (request.throwable) {
|
|
571
|
+
const base = error.isDuplicateError ? DefaultErrors_1.default.DB_DUPLICATE_ERROR : DefaultErrors_1.default.DB_ERROR;
|
|
572
|
+
const customText = error.isDuplicateError ? request.onDuplicateErrorText : request.onErrorText;
|
|
573
|
+
if (customText) {
|
|
574
|
+
throw { ...base, message: customText, details: error.message };
|
|
575
|
+
}
|
|
576
|
+
throw { ...base, details: error.message, stack: error };
|
|
577
|
+
}
|
|
578
|
+
return {
|
|
579
|
+
data: null,
|
|
580
|
+
error: error,
|
|
581
|
+
execution: {
|
|
582
|
+
started_at: executionStartTime,
|
|
583
|
+
finished_at: Date.now()
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
killQuery(conn) {
|
|
589
|
+
const threadId = conn?.threadId;
|
|
590
|
+
if (!this.pool || !threadId)
|
|
591
|
+
return;
|
|
592
|
+
this.pool.query("KILL QUERY " + Number(threadId)).catch(e => (0, LogService_1.logError)("MysqlAdapter", `Can't kill timed-out query on thread ${threadId}: ${e?.message ?? e}`));
|
|
593
|
+
}
|
|
594
|
+
destroyConnection(conn) {
|
|
595
|
+
try {
|
|
596
|
+
conn.removeAllListeners();
|
|
597
|
+
conn.destroy();
|
|
598
|
+
}
|
|
599
|
+
catch (e) {
|
|
600
|
+
(0, LogService_1.logCrit)("MysqlAdapter", `Can't destroy connection: ${e}`);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
finalizeConnection(conn) {
|
|
604
|
+
try {
|
|
605
|
+
conn.removeAllListeners();
|
|
606
|
+
conn.release();
|
|
607
|
+
}
|
|
608
|
+
catch (e) {
|
|
609
|
+
(0, LogService_1.logCrit)("MysqlAdapter", `Can't release connection: ${e}`);
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
prepareQuery(request) {
|
|
613
|
+
const template = request.query;
|
|
614
|
+
const fields = request.fields;
|
|
615
|
+
const values = new Map();
|
|
616
|
+
const parsedFields = [];
|
|
617
|
+
if (fields) {
|
|
618
|
+
for (let i in fields) {
|
|
619
|
+
const name = i;
|
|
620
|
+
if (name.startsWith("$__"))
|
|
621
|
+
continue;
|
|
622
|
+
let queryField = fields[i];
|
|
623
|
+
if (queryField === undefined)
|
|
624
|
+
queryField = { value: null, system: true };
|
|
625
|
+
if (typeof queryField === "string" || typeof queryField === "number" || typeof queryField === "boolean")
|
|
626
|
+
queryField = { value: queryField, system: false };
|
|
627
|
+
if (queryField instanceof Date)
|
|
628
|
+
queryField = { value: queryField, system: false };
|
|
629
|
+
if (queryField === null)
|
|
630
|
+
queryField = { value: null, system: true };
|
|
631
|
+
if (queryField.value === undefined) {
|
|
632
|
+
queryField.value = null;
|
|
633
|
+
queryField.system = true;
|
|
634
|
+
}
|
|
635
|
+
if (!queryField.name)
|
|
636
|
+
queryField.name = name.replaceAll("`", '').replaceAll('\"', "").replaceAll('\'', "");
|
|
637
|
+
fields[i] = queryField;
|
|
638
|
+
const parsed = MysqlAdapter.prepareQueryFieldValue(queryField);
|
|
639
|
+
values.set(name, parsed + "");
|
|
640
|
+
if (!queryField.name.startsWith("$__"))
|
|
641
|
+
parsedFields.push(queryField);
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
const column = (f) => MysqlAdapter.quoteIdentifier(f.name ?? "");
|
|
645
|
+
const macro = (name, build) => {
|
|
646
|
+
if (!values.has(name) && template.indexOf("@" + name) !== -1)
|
|
647
|
+
values.set(name, build());
|
|
648
|
+
};
|
|
649
|
+
macro("fields", () => parsedFields.filter(f => !f.ignoreInInsert).map(column).join(","));
|
|
650
|
+
if (template.indexOf("@fields") !== -1)
|
|
651
|
+
macro("values", () => parsedFields.filter(f => !f.ignoreInInsert).map(f => f.__parsedValue).join(","));
|
|
652
|
+
macro("insert", () => {
|
|
653
|
+
const list = parsedFields.filter(f => !f.ignoreInInsert);
|
|
654
|
+
return `(${list.map(column).join(",")}) VALUES (${list.map(f => f.__parsedValue).join(",")})`;
|
|
655
|
+
});
|
|
656
|
+
macro("onupdate", () => parsedFields.filter(f => !f.ignoreInUpdate).map(f => column(f) + ' = ' + f.__parsedValue).join(" , "));
|
|
657
|
+
macro("onduplicate", () => parsedFields.filter(f => f.useInReplace).map(f => column(f) + ' = ' + f.__parsedValue).join(" , "));
|
|
658
|
+
let noLimit = false;
|
|
659
|
+
if (!values.has("NOLIMIT") && template.indexOf("@NOLIMIT") !== -1) {
|
|
660
|
+
values.set("NOLIMIT", "");
|
|
661
|
+
noLimit = true;
|
|
662
|
+
}
|
|
663
|
+
let query = MysqlAdapter.substitute(template, values);
|
|
664
|
+
const tmp = query.toLowerCase();
|
|
665
|
+
if (tmp.indexOf("select") === 0 && !noLimit && tmp.indexOf("limit") === -1)
|
|
666
|
+
query += " LIMIT 100";
|
|
667
|
+
return query;
|
|
668
|
+
}
|
|
669
|
+
static substitute(text, values) {
|
|
670
|
+
if (values.size === 0)
|
|
671
|
+
return text;
|
|
672
|
+
const names = [...values.keys()]
|
|
673
|
+
.sort((a, b) => b.length - a.length)
|
|
674
|
+
.map(n => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
|
|
675
|
+
const regex = new RegExp("@(" + names.join("|") + ")(?=\\b|\\s|,|\\)|$)", "g");
|
|
676
|
+
return text.replace(regex, (match, name) => values.get(name) ?? match);
|
|
677
|
+
}
|
|
678
|
+
static quoteIdentifier(name) {
|
|
679
|
+
return "`" + String(name).replaceAll("`", "") + "`";
|
|
680
|
+
}
|
|
681
|
+
static safeReplace(query, key, value) {
|
|
682
|
+
const name = key.startsWith("@") ? key.substring(1) : key;
|
|
683
|
+
return MysqlAdapter.substitute(query, new Map([[name, value]]));
|
|
684
|
+
}
|
|
685
|
+
static prepareQueryFieldValue(field) {
|
|
686
|
+
let value = field.value;
|
|
687
|
+
let system = field.system;
|
|
688
|
+
if (value === null || value === undefined) {
|
|
689
|
+
field.__parsedValue = "NULL";
|
|
690
|
+
return "NULL";
|
|
691
|
+
}
|
|
692
|
+
if (value instanceof Date) {
|
|
693
|
+
const utcString = value.toISOString().slice(0, 19).replace('T', ' ');
|
|
694
|
+
value = promise_1.default.escape(utcString);
|
|
695
|
+
}
|
|
696
|
+
else {
|
|
697
|
+
if (!system && typeof value === "object") {
|
|
698
|
+
try {
|
|
699
|
+
value = JSON.stringify(value);
|
|
700
|
+
}
|
|
701
|
+
catch (e) {
|
|
702
|
+
(0, LogService_1.logError)("Can't prepare JSON object", e);
|
|
703
|
+
value = "{}";
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
if (!system && typeof value === "string") {
|
|
707
|
+
value = promise_1.default.escape(value);
|
|
708
|
+
}
|
|
709
|
+
if (typeof value === "boolean")
|
|
710
|
+
value = value ? 1 : 0;
|
|
711
|
+
}
|
|
712
|
+
if (field.fields && typeof field.fields === "object" && value && typeof value === "string" && value.indexOf("@") !== -1) {
|
|
713
|
+
const nested = new Map();
|
|
714
|
+
for (let key in field.fields) {
|
|
715
|
+
if (!field.fields[key])
|
|
716
|
+
continue;
|
|
717
|
+
nested.set(key, promise_1.default.escape(field.fields[key]));
|
|
718
|
+
}
|
|
719
|
+
value = MysqlAdapter.substitute(value, nested);
|
|
720
|
+
}
|
|
721
|
+
field.__parsedValue = value;
|
|
722
|
+
if (field.__parsedValue === null || field.__parsedValue === undefined) {
|
|
723
|
+
field.__parsedValue = "NULL";
|
|
724
|
+
value = field.__parsedValue;
|
|
725
|
+
}
|
|
726
|
+
return value;
|
|
727
|
+
}
|
|
728
|
+
prepareCountQuery(query) {
|
|
729
|
+
let cleanQuery = query
|
|
730
|
+
.replace(/ORDER\s+BY\s+.*$/is, "")
|
|
731
|
+
.replace(/\bLIMIT\s+\d+(\s+OFFSET\s+\d+)?/is, "")
|
|
732
|
+
.trim();
|
|
733
|
+
return `SELECT COUNT(1) AS \`count\` FROM (${cleanQuery}) AS \`temp_count_table\``;
|
|
734
|
+
}
|
|
735
|
+
async commit(trx) {
|
|
736
|
+
try {
|
|
737
|
+
await trx.conn.commit();
|
|
738
|
+
trx.conn.removeAllListeners();
|
|
739
|
+
trx.conn.release();
|
|
740
|
+
const trxIndex = this.transactions.indexOf(trx);
|
|
741
|
+
this.transactions.splice(trxIndex, 1);
|
|
742
|
+
}
|
|
743
|
+
catch (e) {
|
|
744
|
+
const err = this.createMysqlQueryError(e);
|
|
745
|
+
trx.queries.push({ sql: "COMMIT", status: err.code });
|
|
746
|
+
await this.rollbackTransaction(trx);
|
|
747
|
+
return err;
|
|
748
|
+
}
|
|
749
|
+
return null;
|
|
750
|
+
}
|
|
751
|
+
async rollbackTransaction(trx, donNotRemove) {
|
|
752
|
+
let err = null;
|
|
753
|
+
if (!trx) {
|
|
754
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't rollback transaction, trx is null");
|
|
755
|
+
return this.createMysqlQueryError(new Error("Transaction is null"));
|
|
756
|
+
}
|
|
757
|
+
try {
|
|
758
|
+
(0, LogService_1.logDB)("Rollback started", trx.conn.threadId);
|
|
759
|
+
await trx.conn.rollback();
|
|
760
|
+
trx.conn.removeAllListeners();
|
|
761
|
+
trx.conn.release();
|
|
762
|
+
(0, LogService_1.logDB)("Rollback connection released", trx.conn.threadId);
|
|
763
|
+
if (!donNotRemove && this.transactions)
|
|
764
|
+
this.transactions = this.transactions.filter(i => trx && i && i.id !== trx.id);
|
|
765
|
+
if (this.options.debug)
|
|
766
|
+
(0, LogService_1.logDB)("Rollback complete", trx.conn.threadId);
|
|
767
|
+
trx.queries.push({ sql: "ROLLBACK", status: "ok" });
|
|
768
|
+
}
|
|
769
|
+
catch (e) {
|
|
770
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't rollback transaction", trx.queries);
|
|
771
|
+
err = this.createMysqlQueryError(e);
|
|
772
|
+
trx.queries.push({ sql: "ROLLBACK", status: "fail" });
|
|
773
|
+
try {
|
|
774
|
+
trx.conn.destroy();
|
|
775
|
+
}
|
|
776
|
+
catch (e) {
|
|
777
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't destroy broken connection", e);
|
|
778
|
+
}
|
|
779
|
+
this.transactions = this.transactions.filter(i => i.id !== trx.id);
|
|
780
|
+
}
|
|
781
|
+
return err;
|
|
782
|
+
}
|
|
783
|
+
async finish() {
|
|
784
|
+
(0, LogService_1.logInfo)("Finishing mysql service");
|
|
785
|
+
for (const trx of [...this.transactions])
|
|
786
|
+
await this.rollbackTransaction(trx);
|
|
787
|
+
if (this.pool) {
|
|
788
|
+
try {
|
|
789
|
+
await this.pool.end();
|
|
790
|
+
}
|
|
791
|
+
catch (e) {
|
|
792
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't close MYSQL pool!");
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
if (this.failReportFileStream)
|
|
796
|
+
this.failReportFileStream.end();
|
|
797
|
+
this.failReportFileStream = null;
|
|
798
|
+
}
|
|
799
|
+
createMysqlQueryError(err, throwable) {
|
|
800
|
+
if (err && typeof err === "object" && "code" in err && "errno" in err && "sql" in err && "name" in err && "message" in err) {
|
|
801
|
+
return {
|
|
802
|
+
code: err.code,
|
|
803
|
+
errno: err.errno,
|
|
804
|
+
sql: err.sql,
|
|
805
|
+
name: err.name,
|
|
806
|
+
message: err.message,
|
|
807
|
+
fatal: err.fatal && typeof err.fatal === "boolean" ? err.fatal : false,
|
|
808
|
+
isDuplicateError: err.code.toLowerCase().indexOf("dup_entry") !== -1
|
|
809
|
+
};
|
|
810
|
+
}
|
|
811
|
+
else {
|
|
812
|
+
return {
|
|
813
|
+
code: "QUERY_ERR",
|
|
814
|
+
errno: 100002,
|
|
815
|
+
fatal: true,
|
|
816
|
+
sql: "no query",
|
|
817
|
+
name: "QUERY_ERR",
|
|
818
|
+
message: "Error: " + (err instanceof Error ? err.message : String(err ?? "")),
|
|
819
|
+
isDuplicateError: false
|
|
820
|
+
};
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
async storeTransactionAsProblem(trx, message) {
|
|
824
|
+
if (!this.options.transactionFailReport && !this.options.transactionFailReportDir) {
|
|
825
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't report failed transaction, no report function: transactionFailReport in options, and transactionFailReportDir isnt set");
|
|
826
|
+
return;
|
|
827
|
+
}
|
|
828
|
+
if (this.options.transactionFailReportDir) {
|
|
829
|
+
const yyymmdd = new Date().toISOString().substring(0, 10).replaceAll("-", "");
|
|
830
|
+
const date = new Date();
|
|
831
|
+
const file = path_1.default.resolve(this.options.transactionFailReportDir, yyymmdd + ".json");
|
|
832
|
+
if (this.failReportFileStream && this.failReportFileStreamName !== file) {
|
|
833
|
+
try {
|
|
834
|
+
this.failReportFileStream.end();
|
|
835
|
+
}
|
|
836
|
+
catch { }
|
|
837
|
+
this.failReportFileStream = null;
|
|
838
|
+
this.failReportFileStreamName = null;
|
|
839
|
+
}
|
|
840
|
+
if (this.options.debug)
|
|
841
|
+
(0, LogService_1.logDB)("Store transaction fail report: ", file, trx.queries, message);
|
|
842
|
+
if (!this.failReportFileStream) {
|
|
843
|
+
const stream = fs_1.default.createWriteStream(file, { flags: 'a' });
|
|
844
|
+
stream.on('error', (err) => {
|
|
845
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Transaction fail report stream error: " + err.message);
|
|
846
|
+
if (this.failReportFileStream === stream) {
|
|
847
|
+
this.failReportFileStream = null;
|
|
848
|
+
this.failReportFileStreamName = null;
|
|
849
|
+
}
|
|
850
|
+
});
|
|
851
|
+
this.failReportFileStream = stream;
|
|
852
|
+
this.failReportFileStreamName = file;
|
|
853
|
+
}
|
|
854
|
+
this.failReportFileStream.write(JSON.stringify({ queries: trx.queries, time: trx.timestamp, date, message }) + "\n}EOB{\n", err => {
|
|
855
|
+
if (err)
|
|
856
|
+
(0, LogService_1.logCrit)("MysqlAdapter", "Can't write to transaction fail report file: " + err.message);
|
|
857
|
+
else
|
|
858
|
+
(0, LogService_1.logDB)("MysqlAdapter", "Transaction fail report stored");
|
|
859
|
+
});
|
|
860
|
+
this.failReportLastAccessTime = Date.now();
|
|
861
|
+
}
|
|
862
|
+
if (this.options.transactionFailReport)
|
|
863
|
+
this.options.transactionFailReport(trx, message);
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
exports.MysqlAdapter = MysqlAdapter;
|
|
867
|
+
function isError(obj) {
|
|
868
|
+
return obj && "code" in obj && "errno" in obj && "name" in obj && "message" in obj;
|
|
869
|
+
}
|