-
Notifications
You must be signed in to change notification settings - Fork 0
/
Postgres.js
488 lines (399 loc) · 11.5 KB
/
Postgres.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
'use strict';
/**
* Configuration options for {@link Postgres}.
* @typedef {Object} Postgres~Config
* @property {String} [bin=postgres]
* @property {String} [conf]
* @property {(Number|String)} [port=5432]
* @property {String} datadir
* @property {String} shutdown
*/
/**
* Invoked when an operation (i.e. {@link Postgres#open}) completes.
* @callback Postgres~callback
* @argument {Error} err
*/
/**
* Emitted when a PostgreSQL server prints to stdout.
* @event Postgres#stdout
*/
/**
* Emitted when attempting to start a PostgreSQL server.
* @event Postgres#opening
*/
/**
* Emitted when a PostgreSQL server becomes ready to service requests.
* @event Postgres#open
*/
/**
* Emitted when attempting to stop a PostgreSQL server.
* @event Postgres#closing
*/
/**
* Emitted once a PostgreSQL server has stopped.
* @event Postgres#close
*/
const childprocess = require('child_process');
const events = require('events');
const PromiseQueue = require('promise-queue');
/**
* A collection of regualar expressions used by {@link Postgres.parseData} to
* parse stdout and stderr messages.
* @see Postgres.parseData
* @readonly
* @private
* @type {Object.<String,RegExp>}
*/
const regExp = {
terminalMessage: /ready\sto\saccept|already\sin\suse|denied|fatal|postgres(?::|\s)/i,
errorMessage: /^(?:fatal|postgres):\s+(.*)/i,
multipleWhiteSpace: /\s\s+/g,
nonAlpha: /[^a-z]/ig,
newline: /\r?\n/
};
/**
* Start and stop a local PostgreSQL server like a boss.
* @class
*/
class Postgres extends events.EventEmitter {
/**
* Get a function that takes chunks of stdin data, aggregates it, and passes
* it in complete lines, one by one, to a given {@link Postgres~callback}.
* @argument {Postgres~callback} callback
* @return {Function}
*/
static getTextLineAggregator(callback) {
let buffer = '';
return (data) => {
const fragments = data.toString().split(regExp.newline);
const lines = fragments.slice(0, fragments.length - 1);
// If there was an unended line in the previous dump, complete it by
// the first section.
lines[0] = buffer + lines[0];
// If there is an unended line in this dump, store it to be completed by
// the next. This assumes there will be a terminating newline character
// at some point. Generally, this is a safe assumption.
buffer = fragments[fragments.length - 1];
for (let line of lines) {
callback(line);
}
};
}
/**
* Populate a given {@link Postgres~Config} with values from a
* given {@link Postgres~Config}.
* @protected
* @argument {Postgres~Config} source
* @argument {Postgres~Config} target
* @return {Postgres~Config}
*/
static parseConfig(source, target) {
if (target == null) {
target = Object.create(null);
}
if (typeof source === 'string') {
target.datadir = source;
return target;
}
if (source == null || typeof source !== 'object') {
return target;
}
if (source.bin != null) {
target.bin = source.bin;
}
if (source.shutdown != null) {
target.shutdown = source.shutdown;
}
if (source.conf != null) {
target.conf = source.conf;
return target;
}
if (source.datadir != null) {
target.datadir = source.datadir;
}
if (source.port != null) {
target.port = source.port;
}
return target;
}
/**
* Parse process flags for PostgreSQL from a given {@link Postgres~Config}.
* @protected
* @argument {Postgres~Config} config
* @return {Array.<String>}
*/
static parseFlags(config) {
if (config.conf != null) {
return ['-c', `config_file=${config.conf}`];
}
const flags = [];
if (config.datadir != null) {
flags.push('-D', config.datadir);
}
if (config.port != null) {
flags.push('-p', config.port);
}
return flags;
}
/**
* Parse Redis server output for terminal messages.
* @protected
* @argument {String} string
* @return {Object}
*/
static parseData(string) {
const matches = regExp.terminalMessage.exec(string);
if (matches === null) {
return null;
}
const result = {
err: null,
key: matches
.pop()
.replace(regExp.nonAlpha, '')
.toLowerCase()
};
switch (result.key) {
case 'readytoaccept':
break;
case 'alreadyinuse':
result.err = new Error('Address already in use');
result.err.code = -1;
break;
case 'denied':
result.err = new Error('Permission denied');
result.err.code = -2;
break;
case 'postgres':
case 'fatal': {
const matches = regExp.errorMessage.exec(string);
result.err = new Error(
matches === null ? string : matches.pop()
);
result.err.code = -3;
break;
}
}
return result;
}
/**
* Start a given {@linkcode server}.
* @protected
* @fires Postgres#stdout
* @fires Postgres#opening
* @fires Postgres#open
* @fires Postgres#closing
* @fires Postgres#close
* @argument {Postgres} server
* @return {Promise}
*/
static open(server) {
if (server.isOpening) {
return server.openPromise;
}
server.isOpening = true;
server.isClosing = false;
server.openPromise = server.promiseQueue.add(() => {
if (server.isClosing || server.isRunning) {
server.isOpening = false;
return Promise.resolve(null);
}
return new Promise((resolve, reject) => {
/**
* A listener for the current server process' stdout that resolves or
* rejects the current {@link Promise} when done.
* @see Postgres.getTextLineAggregator
* @see Postgres.parseData
* @argument {Buffer} buffer
* @return {undefined}
*/
const dataListener = Postgres.getTextLineAggregator((string) => {
const result = Postgres.parseData(string);
if (result === null) {
return;
}
server.process.stdout.removeListener('data', dataListener);
server.process.stderr.removeListener('data', dataListener);
server.isOpening = false;
if (result.err === null) {
server.isRunning = true;
server.emit('open');
resolve(null);
}
else {
server.isClosing = true;
server.emit('closing');
server.process.once('close', () => reject(result.err));
}
});
/**
* A listener to close the server when the current process exits.
* @return {undefined}
*/
const exitListener = () => {
// istanbul ignore next
server.close();
};
/**
* Get a text line aggregator that emits a given {@linkcode event}
* for the current server.
* @see Postgres.getTextLineAggregator
* @argument {String} event
* @return {Function}
*/
const getDataPropagator = (event) =>
Postgres.getTextLineAggregator((line) => server.emit(event, line));
server.emit('opening');
const flags = Postgres.parseFlags(server.config);
flags.push('-c', `unix_socket_directories=${__dirname}`);
server.process = childprocess.spawn(server.config.bin, flags);
server.process.stderr.on('data', dataListener);
server.process.stderr.on('data', getDataPropagator('stdout'));
server.process.stdout.on('data', dataListener);
server.process.stdout.on('data', getDataPropagator('stdout'));
server.process.on('close', () => {
server.process = null;
server.isRunning = false;
server.isClosing = false;
process.removeListener('exit', exitListener);
server.emit('close');
});
process.on('exit', exitListener);
});
});
return server.openPromise;
}
/**
* Stop a given {@linkcode server}.
* @protected
* @fires Postgres#closing
* @argument {Postgres} server
* @return {Promise}
*/
static close(server) {
if (server.isClosing) {
return server.closePromise;
}
server.isClosing = true;
server.isOpening = false;
server.closePromise = server.promiseQueue.add(() => {
if (server.isOpening || !server.isRunning) {
server.isClosing = false;
return Promise.resolve(null);
}
return new Promise((resolve) => {
server.emit('closing');
server.process.once('close', () => resolve(null));
let signal = server.config.shutdown;
switch (server.config.shutdown) {
case 'smart':
signal = 'SIGTERM';
break;
case 'fast':
signal = 'SIGINT';
break;
case 'immediate':
signal = 'SIGQUIT';
break;
}
server.process.kill(signal);
});
});
return server.closePromise;
}
/**
* Construct a new {@link Postgres}.
* @argument {(Number|String|Postgres~Config)} [configOrDataDir]
* A number or string that is a port or an object for configuration.
*/
constructor(configOrDataDir) {
super();
/**
* Configuration options.
* @protected
* @type {Postgres~Config}
*/
this.config = Postgres.parseConfig(configOrDataDir, {
bin: 'postgres',
conf: null,
port: 5432,
datadir: null,
shutdown: 'fast'
});
/**
* The current process.
* @protected
* @type {ChildProcess}
*/
this.process = null;
/**
* The last {@link Promise} returned by {@link Postgres#open}.
* @protected
* @type {Promise}
*/
this.openPromise = Promise.resolve(null);
/**
* The last {@link Promise} returned by {@link Postgres#close}.
* @protected
* @type {Promise}
*/
this.closePromise = Promise.resolve(null);
/**
* A serial queue of open and close promises.
* @protected
* @type {PromiseQueue}
*/
this.promiseQueue = new PromiseQueue(1);
/**
* Determine if the instance is closing a PostgreSQL server; {@linkcode true}
* while a process is being, or about to be, killed until the
* contained PostgreSQL server either closes or errs.
* @readonly
* @type {Boolean}
*/
this.isClosing = false;
/**
* Determine if the instance is starting a PostgreSQL server; {@linkcode true}
* while a process is spawning, or about tobe spawned, until the
* contained PostgreSQL server either starts or errs.
* @readonly
* @type {Boolean}
*/
this.isRunning = false;
/**
* Determine if the instance is running a PostgreSQL server; {@linkcode true}
* once a process has spawned and the contained PostgreSQL server is ready
* to service requests.
* @readonly
* @type {Boolean}
*/
this.isOpening = false;
}
/**
* Open the server.
* @argument {Postgres~callback} [callback]
* @return {Promise}
*/
open(callback) {
const promise = Postgres.open(this);
return typeof callback === 'function'
? promise
.then((v) => callback(null, v))
.catch((e) => callback(e, null))
: promise;
}
/**
* Close the server.
* @argument {Postgres~callback} [callback]
* @return {Promise}
*/
close(callback) {
const promise = Postgres.close(this);
return typeof callback === 'function'
? promise
.then((v) => callback(null, v))
.catch((e) => callback(e, null))
: promise;
}
}
module.exports = exports = Postgres;