anote-server-libs 0.12.2 → 0.12.4
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/.vscode/settings.json +2 -2
- package/models/ApiCall.ts +40 -40
- package/models/Migration.ts +43 -43
- package/models/repository/CryptModelDao.js +82 -0
- package/models/repository/MemoryCache.ts +87 -87
- package/models/repository/ModelDao.ts +268 -268
- package/package.json +35 -35
- package/services/WithBody.ts +65 -65
- package/services/WithTransaction.js +7 -7
- package/services/WithTransaction.ts +271 -271
- package/services/utils.js +24 -24
- package/services/utils.ts +289 -289
- package/tsconfig.json +29 -29
|
@@ -1,271 +1,271 @@
|
|
|
1
|
-
import {NextFunction, Request, Response} from 'express';
|
|
2
|
-
import {Logger} from 'winston';
|
|
3
|
-
import {BaseModelRepository} from '../models/repository/BaseModelRepository';
|
|
4
|
-
import {jsonStringify, utils} from './utils';
|
|
5
|
-
|
|
6
|
-
export const enum SystemLock {
|
|
7
|
-
CHECK_CROSSING = 1,
|
|
8
|
-
FLUSH_CALLS = 2,
|
|
9
|
-
TX_CHECK = 3
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
export const withTransactionConfig = {
|
|
13
|
-
logQueries: false,
|
|
14
|
-
timeoutMillis: 15000,
|
|
15
|
-
// Number of currently active transactions tracked for gating.
|
|
16
|
-
activeCount: 0,
|
|
17
|
-
// Whether a gate has been requested (waiting for activeCount to reach 0).
|
|
18
|
-
gateRequested: false,
|
|
19
|
-
// Whether the gate is active (new transactions are queued).
|
|
20
|
-
gateActive: false,
|
|
21
|
-
// Queue of pending transactions waiting for the gate to release.
|
|
22
|
-
gateQueue: [] as Array<{resolve: () => void; reject: (err: Error) => void}>,
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Request a transaction gate. Returns a Promise that resolves when all currently
|
|
27
|
-
* active transactions have completed (drained). While waiting and after resolution,
|
|
28
|
-
* new withTransaction calls will be queued until releaseTransactionGate() is called.
|
|
29
|
-
*
|
|
30
|
-
* Use this before starting a long-running operation to ensure no other transactions
|
|
31
|
-
* are killed by PostgreSQL's idle_in_transaction_session_timeout while the long
|
|
32
|
-
* operation holds locks or occupies the connection pool.
|
|
33
|
-
*
|
|
34
|
-
* @returns A Promise that resolves when the gate is acquired.
|
|
35
|
-
*/
|
|
36
|
-
export function requestTransactionGate(): Promise<void> {
|
|
37
|
-
if(withTransactionConfig.gateActive || withTransactionConfig.gateRequested) {
|
|
38
|
-
return Promise.reject(new Error('Transaction gate already active or requested'));
|
|
39
|
-
}
|
|
40
|
-
withTransactionConfig.gateRequested = true;
|
|
41
|
-
return new Promise<void>((resolve, _reject) => {
|
|
42
|
-
const check = () => {
|
|
43
|
-
// Allow the calling transaction to remain active (activeCount <= 1).
|
|
44
|
-
// When called from inside a withTransaction handler, the current
|
|
45
|
-
// transaction counts as 1. When called from outside (e.g. cron),
|
|
46
|
-
// activeCount may be 0.
|
|
47
|
-
if(withTransactionConfig.activeCount <= 1) {
|
|
48
|
-
withTransactionConfig.gateActive = true;
|
|
49
|
-
withTransactionConfig.gateRequested = false;
|
|
50
|
-
resolve();
|
|
51
|
-
} else {
|
|
52
|
-
// Poll every 100ms until other transactions drain
|
|
53
|
-
setTimeout(check, 100);
|
|
54
|
-
}
|
|
55
|
-
};
|
|
56
|
-
// Small initial delay to let in-flight transactions settle
|
|
57
|
-
setTimeout(check, 50);
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Release the transaction gate, allowing all queued transactions to proceed.
|
|
63
|
-
* Must be called after the long-running operation completes, in both success
|
|
64
|
-
* and error paths.
|
|
65
|
-
*/
|
|
66
|
-
export function releaseTransactionGate(): void {
|
|
67
|
-
withTransactionConfig.gateActive = false;
|
|
68
|
-
withTransactionConfig.gateRequested = false;
|
|
69
|
-
// Drain the queue — resolve all pending waiters
|
|
70
|
-
const queue = withTransactionConfig.gateQueue.splice(0);
|
|
71
|
-
for(const entry of queue) {
|
|
72
|
-
entry.resolve();
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function releaseAndDecrement(repo: BaseModelRepository, dbClient: any) {
|
|
77
|
-
if(repo.db && dbClient) {
|
|
78
|
-
try { dbClient.release(); } catch (err) {
|
|
79
|
-
const log = utils.logger;
|
|
80
|
-
if(log) log.error('Error releasing dbClient: %j', {err, stack: new Error().stack});
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
withTransactionConfig.activeCount = Math.max(0, withTransactionConfig.activeCount - 1);
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export function withTransaction(repo: BaseModelRepository, logger: Logger, previousMethod: (req: Request, res: Response, next: NextFunction) => void,
|
|
87
|
-
lock?: SystemLock, commitIfLost = true, idleInTransactionTimeout?: number): (req: Request, res: Response, next: NextFunction) => any {
|
|
88
|
-
return function(this: any, req: Request, res: Response, next: NextFunction): any {
|
|
89
|
-
// If gate is active, queue this request and retry when gate is released
|
|
90
|
-
if(withTransactionConfig.gateActive) {
|
|
91
|
-
return new Promise<void>((resolve, reject) => {
|
|
92
|
-
withTransactionConfig.gateQueue.push({resolve, reject});
|
|
93
|
-
}).then(() => {
|
|
94
|
-
// Re-enter with gate now released
|
|
95
|
-
return withTransaction(repo, logger, previousMethod, lock, commitIfLost)(req, res, next);
|
|
96
|
-
});
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
let commit = true;
|
|
100
|
-
if(!commitIfLost) {
|
|
101
|
-
res.once('close', () => commit = false);
|
|
102
|
-
}
|
|
103
|
-
const endTerminator = res.end.bind(res);
|
|
104
|
-
const jsonTerminator = (obj: any) => {
|
|
105
|
-
try { res.set('Content-Type', 'application/json'); } catch(_) {}
|
|
106
|
-
res.write(jsonStringify(obj) || '{}');
|
|
107
|
-
endTerminator();
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
// Increment activeCount before attempting to connect to the database
|
|
111
|
-
withTransactionConfig.activeCount++;
|
|
112
|
-
|
|
113
|
-
const connectTimeoutHandler = setTimeout(() => {
|
|
114
|
-
// Timed out getting a client, restart worker or process...
|
|
115
|
-
logger.error('Error timed out getting a client, exiting... stack: %s', new Error().stack);
|
|
116
|
-
process.exit(22);
|
|
117
|
-
}, withTransactionConfig.timeoutMillis);
|
|
118
|
-
Promise.all([
|
|
119
|
-
repo.db ? repo.db.connect() : Promise.resolve(undefined),
|
|
120
|
-
repo.dbMssql ? Promise.resolve(repo.dbMssql.transaction()) : Promise.resolve(undefined)
|
|
121
|
-
]).then(([c1, c2]) => {
|
|
122
|
-
const dbClient = c1 || c2;
|
|
123
|
-
clearTimeout(connectTimeoutHandler);
|
|
124
|
-
// On error, will rollback...
|
|
125
|
-
utils.logger = logger;
|
|
126
|
-
if(withTransactionConfig.logQueries && !dbClient.queryPatched) {
|
|
127
|
-
const originalQuery = dbClient.query.bind(dbClient);
|
|
128
|
-
dbClient.query = (...args: any[]) => {
|
|
129
|
-
logger.debug('SQL [Client %d] QUERY: %s', dbClient.processID, args[0]);
|
|
130
|
-
return originalQuery(...args);
|
|
131
|
-
};
|
|
132
|
-
dbClient.queryPatched = true;
|
|
133
|
-
}
|
|
134
|
-
dbClient.removeAllListeners('error');
|
|
135
|
-
dbClient.on('error', (err: any) => {
|
|
136
|
-
if(utils.clientErrorHandler) {
|
|
137
|
-
utils.clientErrorHandler(err, dbClient);
|
|
138
|
-
} else {
|
|
139
|
-
logger.error('SQL [Client %d] ERROR (no handler): %j', dbClient?.processID, {err, stack: new Error().stack});
|
|
140
|
-
}
|
|
141
|
-
});
|
|
142
|
-
|
|
143
|
-
res.locals.dbClient = dbClient;
|
|
144
|
-
res.locals.dbClientCommited = false;
|
|
145
|
-
res.locals.dbClientCommit = (cb: (err: any) => any) => {
|
|
146
|
-
if(!res.locals.dbClientCommited) {
|
|
147
|
-
res.locals.dbClientCommited = true;
|
|
148
|
-
(commit ? (repo.db ? dbClient.query('COMMIT') : dbClient.commit()) : Promise.reject(new Error('Client lost'))).catch((err: any) => err).then((err: any) => {
|
|
149
|
-
releaseAndDecrement(repo, dbClient);
|
|
150
|
-
if(!(err instanceof Error)) {
|
|
151
|
-
for(let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
|
|
152
|
-
res.locals.dbClientOnCommit[i]();
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
cb(err instanceof Error ? err : undefined);
|
|
156
|
-
});
|
|
157
|
-
} else {
|
|
158
|
-
cb(undefined);
|
|
159
|
-
}
|
|
160
|
-
};
|
|
161
|
-
res.locals.dbClientOnCommit = [];
|
|
162
|
-
|
|
163
|
-
// Build the BEGIN + idle_in_transaction_session_timeout setup
|
|
164
|
-
const beginPromise = repo.db ? dbClient.query('BEGIN') : dbClient.begin();
|
|
165
|
-
const idleTimeoutMs = Math.max(idleInTransactionTimeout, withTransactionConfig.timeoutMillis);
|
|
166
|
-
let setupPromise: Promise<any> = beginPromise;
|
|
167
|
-
if(idleInTransactionTimeout && idleTimeoutMs > 0 && repo.db) {
|
|
168
|
-
setupPromise = setupPromise.then(() => {
|
|
169
|
-
return dbClient.query(`SET LOCAL idle_in_transaction_session_timeout TO ${idleTimeoutMs}`);
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
return setupPromise.then(() => {
|
|
174
|
-
const finish = () => {
|
|
175
|
-
res.send = () => {
|
|
176
|
-
throw new Error('res.send() should not be used within transactions. Use res.json() instead.');
|
|
177
|
-
};
|
|
178
|
-
res.json = (obj: any) => {
|
|
179
|
-
if(res.statusCode > 303 && res.statusCode !== 412) {
|
|
180
|
-
if(logger) {
|
|
181
|
-
if(res.statusCode > 499) {
|
|
182
|
-
logger.error('Uncaught 500 at %s %s: %j', req
|
|
183
|
-
} else {
|
|
184
|
-
logger.warn('Client error 4XX at %s %s: %j', req
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
(repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((err: any) => obj && obj.error && (obj.error.additionalInfo2 = {message: err.message})).then(() => {
|
|
188
|
-
releaseAndDecrement(repo, dbClient);
|
|
189
|
-
jsonTerminator(obj);
|
|
190
|
-
});
|
|
191
|
-
} else {
|
|
192
|
-
res.locals.dbClientCommit((err: any) => {
|
|
193
|
-
if(err && commitIfLost) {
|
|
194
|
-
res.status(500);
|
|
195
|
-
jsonTerminator({
|
|
196
|
-
error: {
|
|
197
|
-
errorKey: 'internal.db',
|
|
198
|
-
additionalInfo: {message: err.message}
|
|
199
|
-
}
|
|
200
|
-
});
|
|
201
|
-
} else jsonTerminator(obj);
|
|
202
|
-
});
|
|
203
|
-
}
|
|
204
|
-
return res;
|
|
205
|
-
};
|
|
206
|
-
res.end = () => {
|
|
207
|
-
if(res.statusCode > 303 && res.statusCode !== 412) {
|
|
208
|
-
if(logger && res.statusCode > 499) {
|
|
209
|
-
logger.error('Uncaught 500 with no details at %s %s: %j', req
|
|
210
|
-
}
|
|
211
|
-
(repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((): any => undefined).then(() => {
|
|
212
|
-
releaseAndDecrement(repo, dbClient);
|
|
213
|
-
endTerminator();
|
|
214
|
-
});
|
|
215
|
-
} else {
|
|
216
|
-
res.locals.dbClientCommit((err: any) => {
|
|
217
|
-
if(err && commitIfLost) {
|
|
218
|
-
res.status(500);
|
|
219
|
-
jsonTerminator({
|
|
220
|
-
error: {
|
|
221
|
-
errorKey: 'internal.db',
|
|
222
|
-
additionalInfo: {message: err.message}
|
|
223
|
-
}
|
|
224
|
-
});
|
|
225
|
-
} else endTerminator();
|
|
226
|
-
});
|
|
227
|
-
}
|
|
228
|
-
return res;
|
|
229
|
-
};
|
|
230
|
-
return previousMethod.call(this, req, res, next);
|
|
231
|
-
};
|
|
232
|
-
|
|
233
|
-
if(lock) {
|
|
234
|
-
dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch((err: any) => {
|
|
235
|
-
logger.error('Error acquiring advisory lock %d at %s %s: %j', lock, req
|
|
236
|
-
res.status(500).json({
|
|
237
|
-
error: {
|
|
238
|
-
errorKey: 'internal.db',
|
|
239
|
-
additionalInfo: {message: err.message}
|
|
240
|
-
}
|
|
241
|
-
});
|
|
242
|
-
releaseAndDecrement(repo, dbClient); // Lock acquisition failed, release will also rollback
|
|
243
|
-
});
|
|
244
|
-
} else {
|
|
245
|
-
finish();
|
|
246
|
-
}
|
|
247
|
-
}).catch((err: any) => {
|
|
248
|
-
// Error beginning transaction
|
|
249
|
-
releaseAndDecrement(repo, dbClient);
|
|
250
|
-
logger.error('Error beginning transaction at %s %s: %j', req
|
|
251
|
-
res.status(500).json({
|
|
252
|
-
error: {
|
|
253
|
-
errorKey: 'internal.db',
|
|
254
|
-
additionalInfo: {message: err.message}
|
|
255
|
-
}
|
|
256
|
-
});
|
|
257
|
-
});
|
|
258
|
-
}).catch(err => {
|
|
259
|
-
// Error connecting to database for other reason than timeout or beginning transaction
|
|
260
|
-
clearTimeout(connectTimeoutHandler);
|
|
261
|
-
logger.error('Error connecting to database at %s %s: %j', req
|
|
262
|
-
withTransactionConfig.activeCount = Math.max(0, withTransactionConfig.activeCount - 1);
|
|
263
|
-
res.status(500).json({
|
|
264
|
-
error: {
|
|
265
|
-
errorKey: 'internal.db',
|
|
266
|
-
additionalInfo: {message: err.message}
|
|
267
|
-
}
|
|
268
|
-
});
|
|
269
|
-
});
|
|
270
|
-
};
|
|
271
|
-
}
|
|
1
|
+
import {NextFunction, Request, Response} from 'express';
|
|
2
|
+
import {Logger} from 'winston';
|
|
3
|
+
import {BaseModelRepository} from '../models/repository/BaseModelRepository';
|
|
4
|
+
import {jsonStringify, utils} from './utils';
|
|
5
|
+
|
|
6
|
+
export const enum SystemLock {
|
|
7
|
+
CHECK_CROSSING = 1,
|
|
8
|
+
FLUSH_CALLS = 2,
|
|
9
|
+
TX_CHECK = 3
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export const withTransactionConfig = {
|
|
13
|
+
logQueries: false,
|
|
14
|
+
timeoutMillis: 15000,
|
|
15
|
+
// Number of currently active transactions tracked for gating.
|
|
16
|
+
activeCount: 0,
|
|
17
|
+
// Whether a gate has been requested (waiting for activeCount to reach 0).
|
|
18
|
+
gateRequested: false,
|
|
19
|
+
// Whether the gate is active (new transactions are queued).
|
|
20
|
+
gateActive: false,
|
|
21
|
+
// Queue of pending transactions waiting for the gate to release.
|
|
22
|
+
gateQueue: [] as Array<{resolve: () => void; reject: (err: Error) => void}>,
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Request a transaction gate. Returns a Promise that resolves when all currently
|
|
27
|
+
* active transactions have completed (drained). While waiting and after resolution,
|
|
28
|
+
* new withTransaction calls will be queued until releaseTransactionGate() is called.
|
|
29
|
+
*
|
|
30
|
+
* Use this before starting a long-running operation to ensure no other transactions
|
|
31
|
+
* are killed by PostgreSQL's idle_in_transaction_session_timeout while the long
|
|
32
|
+
* operation holds locks or occupies the connection pool.
|
|
33
|
+
*
|
|
34
|
+
* @returns A Promise that resolves when the gate is acquired.
|
|
35
|
+
*/
|
|
36
|
+
export function requestTransactionGate(): Promise<void> {
|
|
37
|
+
if(withTransactionConfig.gateActive || withTransactionConfig.gateRequested) {
|
|
38
|
+
return Promise.reject(new Error('Transaction gate already active or requested'));
|
|
39
|
+
}
|
|
40
|
+
withTransactionConfig.gateRequested = true;
|
|
41
|
+
return new Promise<void>((resolve, _reject) => {
|
|
42
|
+
const check = () => {
|
|
43
|
+
// Allow the calling transaction to remain active (activeCount <= 1).
|
|
44
|
+
// When called from inside a withTransaction handler, the current
|
|
45
|
+
// transaction counts as 1. When called from outside (e.g. cron),
|
|
46
|
+
// activeCount may be 0.
|
|
47
|
+
if(withTransactionConfig.activeCount <= 1) {
|
|
48
|
+
withTransactionConfig.gateActive = true;
|
|
49
|
+
withTransactionConfig.gateRequested = false;
|
|
50
|
+
resolve();
|
|
51
|
+
} else {
|
|
52
|
+
// Poll every 100ms until other transactions drain
|
|
53
|
+
setTimeout(check, 100);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
// Small initial delay to let in-flight transactions settle
|
|
57
|
+
setTimeout(check, 50);
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Release the transaction gate, allowing all queued transactions to proceed.
|
|
63
|
+
* Must be called after the long-running operation completes, in both success
|
|
64
|
+
* and error paths.
|
|
65
|
+
*/
|
|
66
|
+
export function releaseTransactionGate(): void {
|
|
67
|
+
withTransactionConfig.gateActive = false;
|
|
68
|
+
withTransactionConfig.gateRequested = false;
|
|
69
|
+
// Drain the queue — resolve all pending waiters
|
|
70
|
+
const queue = withTransactionConfig.gateQueue.splice(0);
|
|
71
|
+
for(const entry of queue) {
|
|
72
|
+
entry.resolve();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function releaseAndDecrement(repo: BaseModelRepository, dbClient: any) {
|
|
77
|
+
if(repo.db && dbClient) {
|
|
78
|
+
try { dbClient.release(); } catch (err) {
|
|
79
|
+
const log = utils.logger;
|
|
80
|
+
if(log) log.error('Error releasing dbClient: %j', {err, stack: new Error().stack});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
withTransactionConfig.activeCount = Math.max(0, withTransactionConfig.activeCount - 1);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function withTransaction(repo: BaseModelRepository, logger: Logger, previousMethod: (req: Request, res: Response, next: NextFunction) => void,
|
|
87
|
+
lock?: SystemLock, commitIfLost = true, idleInTransactionTimeout?: number): (req: Request, res: Response, next: NextFunction) => any {
|
|
88
|
+
return function(this: any, req: Request, res: Response, next: NextFunction): any {
|
|
89
|
+
// If gate is active, queue this request and retry when gate is released
|
|
90
|
+
if(withTransactionConfig.gateActive) {
|
|
91
|
+
return new Promise<void>((resolve, reject) => {
|
|
92
|
+
withTransactionConfig.gateQueue.push({resolve, reject});
|
|
93
|
+
}).then(() => {
|
|
94
|
+
// Re-enter with gate now released
|
|
95
|
+
return withTransaction(repo, logger, previousMethod, lock, commitIfLost, idleInTransactionTimeout).call(this, req, res, next);
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
let commit = true;
|
|
100
|
+
if(!commitIfLost) {
|
|
101
|
+
res.once('close', () => commit = false);
|
|
102
|
+
}
|
|
103
|
+
const endTerminator = res.end.bind(res);
|
|
104
|
+
const jsonTerminator = (obj: any) => {
|
|
105
|
+
try { res.set('Content-Type', 'application/json'); } catch(_) {}
|
|
106
|
+
res.write(jsonStringify(obj) || '{}');
|
|
107
|
+
endTerminator();
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
// Increment activeCount before attempting to connect to the database
|
|
111
|
+
withTransactionConfig.activeCount++;
|
|
112
|
+
|
|
113
|
+
const connectTimeoutHandler = setTimeout(() => {
|
|
114
|
+
// Timed out getting a client, restart worker or process...
|
|
115
|
+
logger.error('Error timed out getting a client, exiting... stack: %s', new Error().stack);
|
|
116
|
+
process.exit(22);
|
|
117
|
+
}, withTransactionConfig.timeoutMillis);
|
|
118
|
+
Promise.all([
|
|
119
|
+
repo.db ? repo.db.connect() : Promise.resolve(undefined),
|
|
120
|
+
repo.dbMssql ? Promise.resolve(repo.dbMssql.transaction()) : Promise.resolve(undefined)
|
|
121
|
+
]).then(([c1, c2]) => {
|
|
122
|
+
const dbClient = c1 || c2;
|
|
123
|
+
clearTimeout(connectTimeoutHandler);
|
|
124
|
+
// On error, will rollback...
|
|
125
|
+
utils.logger = logger;
|
|
126
|
+
if(withTransactionConfig.logQueries && !dbClient.queryPatched) {
|
|
127
|
+
const originalQuery = dbClient.query.bind(dbClient);
|
|
128
|
+
dbClient.query = (...args: any[]) => {
|
|
129
|
+
logger.debug('SQL [Client %d] QUERY: %s', dbClient.processID, args[0]);
|
|
130
|
+
return originalQuery(...args);
|
|
131
|
+
};
|
|
132
|
+
dbClient.queryPatched = true;
|
|
133
|
+
}
|
|
134
|
+
dbClient.removeAllListeners('error');
|
|
135
|
+
dbClient.on('error', (err: any) => {
|
|
136
|
+
if(utils.clientErrorHandler) {
|
|
137
|
+
utils.clientErrorHandler(err, dbClient);
|
|
138
|
+
} else {
|
|
139
|
+
logger.error('SQL [Client %d] ERROR (no handler): %j', dbClient?.processID, {err, stack: new Error().stack});
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
res.locals.dbClient = dbClient;
|
|
144
|
+
res.locals.dbClientCommited = false;
|
|
145
|
+
res.locals.dbClientCommit = (cb: (err: any) => any) => {
|
|
146
|
+
if(!res.locals.dbClientCommited) {
|
|
147
|
+
res.locals.dbClientCommited = true;
|
|
148
|
+
(commit ? (repo.db ? dbClient.query('COMMIT') : dbClient.commit()) : Promise.reject(new Error('Client lost'))).catch((err: any) => err).then((err: any) => {
|
|
149
|
+
releaseAndDecrement(repo, dbClient);
|
|
150
|
+
if(!(err instanceof Error)) {
|
|
151
|
+
for(let i = 0; i < res.locals.dbClientOnCommit.length; i++) {
|
|
152
|
+
res.locals.dbClientOnCommit[i]();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
cb(err instanceof Error ? err : undefined);
|
|
156
|
+
});
|
|
157
|
+
} else {
|
|
158
|
+
cb(undefined);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
res.locals.dbClientOnCommit = [];
|
|
162
|
+
|
|
163
|
+
// Build the BEGIN + idle_in_transaction_session_timeout setup
|
|
164
|
+
const beginPromise = repo.db ? dbClient.query('BEGIN') : dbClient.begin();
|
|
165
|
+
const idleTimeoutMs = Math.max(idleInTransactionTimeout, withTransactionConfig.timeoutMillis);
|
|
166
|
+
let setupPromise: Promise<any> = beginPromise;
|
|
167
|
+
if(idleInTransactionTimeout && idleTimeoutMs > 0 && repo.db) {
|
|
168
|
+
setupPromise = setupPromise.then(() => {
|
|
169
|
+
return dbClient.query(`SET LOCAL idle_in_transaction_session_timeout TO ${idleTimeoutMs}`);
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return setupPromise.then(() => {
|
|
174
|
+
const finish = () => {
|
|
175
|
+
res.send = () => {
|
|
176
|
+
throw new Error('res.send() should not be used within transactions. Use res.json() instead.');
|
|
177
|
+
};
|
|
178
|
+
res.json = (obj: any) => {
|
|
179
|
+
if(res.statusCode > 303 && res.statusCode !== 412) {
|
|
180
|
+
if(logger) {
|
|
181
|
+
if(res.statusCode > 499) {
|
|
182
|
+
logger.error('Uncaught 500 at %s %s: %j', req?.method, req?.originalUrl, {body: obj, stack: new Error().stack});
|
|
183
|
+
} else {
|
|
184
|
+
logger.warn('Client error 4XX at %s %s: %j', req?.method, req?.originalUrl, {body: obj, stack: new Error().stack});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
(repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((err: any) => obj && obj.error && (obj.error.additionalInfo2 = {message: err.message})).then(() => {
|
|
188
|
+
releaseAndDecrement(repo, dbClient);
|
|
189
|
+
jsonTerminator(obj);
|
|
190
|
+
});
|
|
191
|
+
} else {
|
|
192
|
+
res.locals.dbClientCommit((err: any) => {
|
|
193
|
+
if(err && commitIfLost) {
|
|
194
|
+
res.status(500);
|
|
195
|
+
jsonTerminator({
|
|
196
|
+
error: {
|
|
197
|
+
errorKey: 'internal.db',
|
|
198
|
+
additionalInfo: {message: err.message}
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
} else jsonTerminator(obj);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
return res;
|
|
205
|
+
};
|
|
206
|
+
res.end = () => {
|
|
207
|
+
if(res.statusCode > 303 && res.statusCode !== 412) {
|
|
208
|
+
if(logger && res.statusCode > 499) {
|
|
209
|
+
logger.error('Uncaught 500 with no details at %s %s: %j', req?.method, req?.originalUrl, {stack: new Error().stack});
|
|
210
|
+
}
|
|
211
|
+
(repo.db ? dbClient.query('ROLLBACK') : dbClient.rollback()).catch((): any => undefined).then(() => {
|
|
212
|
+
releaseAndDecrement(repo, dbClient);
|
|
213
|
+
endTerminator();
|
|
214
|
+
});
|
|
215
|
+
} else {
|
|
216
|
+
res.locals.dbClientCommit((err: any) => {
|
|
217
|
+
if(err && commitIfLost) {
|
|
218
|
+
res.status(500);
|
|
219
|
+
jsonTerminator({
|
|
220
|
+
error: {
|
|
221
|
+
errorKey: 'internal.db',
|
|
222
|
+
additionalInfo: {message: err.message}
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
} else endTerminator();
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
return res;
|
|
229
|
+
};
|
|
230
|
+
return previousMethod.call(this, req, res, next);
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
if(lock) {
|
|
234
|
+
dbClient.query('SELECT pg_advisory_xact_lock(' + lock + ')').then(() => finish()).catch((err: any) => {
|
|
235
|
+
logger.error('Error acquiring advisory lock %d at %s %s: %j', lock, req?.method, req?.originalUrl, {err, stack: new Error().stack});
|
|
236
|
+
res.status(500).json({
|
|
237
|
+
error: {
|
|
238
|
+
errorKey: 'internal.db',
|
|
239
|
+
additionalInfo: {message: err.message}
|
|
240
|
+
}
|
|
241
|
+
});
|
|
242
|
+
releaseAndDecrement(repo, dbClient); // Lock acquisition failed, release will also rollback
|
|
243
|
+
});
|
|
244
|
+
} else {
|
|
245
|
+
finish();
|
|
246
|
+
}
|
|
247
|
+
}).catch((err: any) => {
|
|
248
|
+
// Error beginning transaction
|
|
249
|
+
releaseAndDecrement(repo, dbClient);
|
|
250
|
+
logger.error('Error beginning transaction at %s %s: %j', req?.method, req?.originalUrl, {err, stack: new Error().stack});
|
|
251
|
+
res.status(500).json({
|
|
252
|
+
error: {
|
|
253
|
+
errorKey: 'internal.db',
|
|
254
|
+
additionalInfo: {message: err.message}
|
|
255
|
+
}
|
|
256
|
+
});
|
|
257
|
+
});
|
|
258
|
+
}).catch(err => {
|
|
259
|
+
// Error connecting to database for other reason than timeout or beginning transaction
|
|
260
|
+
clearTimeout(connectTimeoutHandler);
|
|
261
|
+
logger.error('Error connecting to database at %s %s: %j', req?.method, req?.originalUrl, {err, stack: new Error().stack});
|
|
262
|
+
withTransactionConfig.activeCount = Math.max(0, withTransactionConfig.activeCount - 1);
|
|
263
|
+
res.status(500).json({
|
|
264
|
+
error: {
|
|
265
|
+
errorKey: 'internal.db',
|
|
266
|
+
additionalInfo: {message: err.message}
|
|
267
|
+
}
|
|
268
|
+
});
|
|
269
|
+
});
|
|
270
|
+
};
|
|
271
|
+
}
|
package/services/utils.js
CHANGED
|
@@ -147,22 +147,22 @@ function idempotent(repo, debug, logger) {
|
|
|
147
147
|
};
|
|
148
148
|
}
|
|
149
149
|
function sendSelfPostableMessage(res, code, messageType, err) {
|
|
150
|
-
res.type('text/html').status(code).write(`
|
|
151
|
-
<!DOCTYPE HTML>
|
|
152
|
-
<html>
|
|
153
|
-
<head>
|
|
154
|
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
|
|
155
|
-
</head>
|
|
156
|
-
<body>
|
|
157
|
-
<script type="text/javascript">
|
|
158
|
-
window.parent.postMessage({
|
|
159
|
-
type: '${messageType}',
|
|
160
|
-
confirm: ${!err},
|
|
161
|
-
error: JSON.parse('${JSON.stringify(err) || 'null'}')
|
|
162
|
-
}, '*');
|
|
163
|
-
</script>
|
|
164
|
-
</body>
|
|
165
|
-
</html>
|
|
150
|
+
res.type('text/html').status(code).write(`
|
|
151
|
+
<!DOCTYPE HTML>
|
|
152
|
+
<html>
|
|
153
|
+
<head>
|
|
154
|
+
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
|
|
155
|
+
</head>
|
|
156
|
+
<body>
|
|
157
|
+
<script type="text/javascript">
|
|
158
|
+
window.parent.postMessage({
|
|
159
|
+
type: '${messageType}',
|
|
160
|
+
confirm: ${!err},
|
|
161
|
+
error: JSON.parse('${JSON.stringify(err) || 'null'}')
|
|
162
|
+
}, '*');
|
|
163
|
+
</script>
|
|
164
|
+
</body>
|
|
165
|
+
</html>
|
|
166
166
|
`);
|
|
167
167
|
res.end();
|
|
168
168
|
}
|
|
@@ -262,15 +262,15 @@ function getHtmlReplaced(config, templates, key, lang, translations, data = {},
|
|
|
262
262
|
};
|
|
263
263
|
let html = getHtml(templates[key], merged);
|
|
264
264
|
if (newPage) {
|
|
265
|
-
html = html.replace('</head>', `<style>
|
|
266
|
-
@media print {
|
|
267
|
-
.new-page {
|
|
268
|
-
page-break-before: always;
|
|
269
|
-
}
|
|
270
|
-
}
|
|
271
|
-
</style>
|
|
265
|
+
html = html.replace('</head>', `<style>
|
|
266
|
+
@media print {
|
|
267
|
+
.new-page {
|
|
268
|
+
page-break-before: always;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
</style>
|
|
272
272
|
</head>`);
|
|
273
|
-
html = html.replace('</body>', `<p class="new-page">Provided by Satoris</p>
|
|
273
|
+
html = html.replace('</body>', `<p class="new-page">Provided by Satoris</p>
|
|
274
274
|
</body>`);
|
|
275
275
|
}
|
|
276
276
|
return html;
|