forked from logux/server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase-server.js
509 lines (459 loc) · 14.9 KB
/
base-server.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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
'use strict'
const ServerConnection = require('logux-sync').ServerConnection
const MemoryStore = require('logux-core').MemoryStore
const NanoEvents = require('nanoevents')
const WebSocket = require('ws')
const shortid = require('shortid')
const https = require('https')
const http = require('http')
const path = require('path')
const Log = require('logux-core').Log
const fs = require('fs')
const promisify = require('./promisify')
const Client = require('./client')
const PEM_PREAMBLE = '-----BEGIN'
function isPem (content) {
if (typeof content === 'object' && content.pem) {
return true
} else {
return content.toString().trim().indexOf(PEM_PREAMBLE) === 0
}
}
function readFile (root, file) {
file = file.toString()
if (!path.isAbsolute(file)) {
file = path.join(root, file)
}
return promisify(done => {
fs.readFile(file, done)
})
}
function forcePromise (callback) {
let result
try {
result = callback()
} catch (e) {
return Promise.reject(e)
}
if (typeof result !== 'object' || typeof result.then !== 'function') {
return Promise.resolve(result)
} else {
return result
}
}
/**
* Basic Logux Server API without good UI. Use it only if you need
* to create some special hacks on top of Logux Server.
*
* In most use cases you should use {@link Server}.
*
* @param {object} options Server options.
* @param {string} options.subprotocol Server current application
* subprotocol version in SemVer format.
* @param {string} options.supports npm’s version requirements for client
* subprotocol version.
* @param {string|number} [options.nodeId] Unique server ID. Be default,
* `server:` with compacted UUID.
* @param {string} [options.root=process.cwd()] Application root to load files
* and show errors.
* @param {number} [options.timeout=20000] Timeout in milliseconds
* to disconnect connection.
* @param {number} [options.ping=10000] Milliseconds since last message to test
* connection by sending ping.
* @param {Store} [options.store] Store to save log. Will be `MemoryStore`,
* by default.
* @param {"production"|"development"} [options.env] Development or production
* server mode. By default,
* it will be taken from
* `NODE_ENV` environment
* variable. On empty
* `NODE_ENV` it will
* be `"development"`.
* @param {number} [options.pid] Process ID, to display in reporter.
* @param {http.Server} [options.server] HTTP server to connect WebSocket
* server to it.
* Same as in ws.WebSocketServer.
* @param {number} [option.port=1337] Port to bind server. It will create
* HTTP server manually to connect
* WebSocket server to it.
* @param {string} [option.host="127.0.0.1"] IP-address to bind server.
* @param {string} [option.key] SSL key or path to it. Path could be relative
* from server root. It is required in production
* mode, because WSS is highly recommended.
* @param {string} [option.cert] SSL certificate or path to it. Path could
* be relative from server root. It is required
* in production mode, because WSS
* is highly recommended.
* @param {function} [reporter] Function to show current server status.
*
* @example
* import { BaseServer } from 'logux-server'
* class MyLoguxHack extends BaseServer {
* …
* }
*/
class BaseServer {
constructor (options, reporter) {
/**
* Server options.
* @type {object}
*
* @example
* console.log(app.options.nodeId + ' was started')
*/
this.options = options || { }
this.reporter = reporter || function () { }
if (typeof this.options.subprotocol === 'undefined') {
throw new Error('Missed subprotocol version')
}
if (typeof this.options.supports === 'undefined') {
throw new Error('Missed supported subprotocol major versions')
}
if (typeof this.options.nodeId === 'undefined') {
this.options.nodeId = `server:${ shortid.generate() }`
}
if (this.options.key && !this.options.cert) {
throw new Error('You must set cert option too if you use key option')
}
if (!this.options.key && this.options.cert) {
throw new Error('You must set key option too if you use cert option')
}
if (!this.options.server) {
if (!this.options.port) this.options.port = 1337
if (!this.options.host) this.options.host = '127.0.0.1'
}
/**
* Server unique ID.
* @type {string}
*
* @example
* console.log('Error was raised on ' + app.nodeId)
*/
this.nodeId = this.options.nodeId
this.options.root = this.options.root || process.cwd()
const store = this.options.store || new MemoryStore()
/**
* Server actions log.
* @type {Log}
*
* @example
* app.log.each(finder)
*/
this.log = new Log({ store, nodeId: this.nodeId })
this.log.on('preadd', (action, meta) => {
if (!meta.server) meta.server = this.nodeId
if (!meta.status) meta.status = 'waiting'
})
this.log.on('add', (action, meta) => {
this.reporter('add', this, action, meta)
if (this.destroing) return
if (meta.status !== 'waiting') return
if (!this.types[action.type]) {
this.unknownAction(action, meta)
} else {
this.process(action, meta)
}
})
this.log.on('clean', (action, meta) => {
this.reporter('clean', this, action, meta)
})
/**
* Production or development mode.
* @type {"production"|"development"}
*
* @example
* if (app.env === 'development') {
* logDebugData()
* }
*/
this.env = this.options.env || process.env.NODE_ENV || 'development'
this.emitter = new NanoEvents()
this.on('error', (e, action, meta) => {
this.reporter('runtimeError', this, e, action, meta)
if (this.env === 'development') this.debugError(e)
})
this.unbind = []
/**
* Connected clients.
* @type {Client[]}
*
* @example
* for (let nodeId in app.clients) {
* console.log(app.clients[nodeId].remoteAddress)
* }
*/
this.clients = { }
this.nodeIds = { }
this.types = { }
this.processing = 0
this.lastClient = 0
this.unbind.push(() => {
for (const i in this.clients) this.clients[i].destroy()
})
this.unbind.push(() => new Promise(resolve => {
if (this.processing === 0) {
resolve()
} else {
this.on('processed', () => {
if (this.processing === 0) resolve()
})
}
}))
}
/**
* Set authenticate function. It will receive client credentials
* and node ID. It should return a Promise with `true` or `false`.
*
* @param {authenticator} authenticator The authentication callback.
*
* @return {undefined}
*
* @example
* app.auth((userId, token) => {
* return findUserByToken(token).then(user => {
* return !!user && userId === user.id
* })
* })
*/
auth (authenticator) {
this.authenticator = function () {
return forcePromise(() => authenticator.apply(this, arguments))
}
}
/**
* Start WebSocket server and listen for clients.
*
* @return {Promise} When the server has been bound.
*/
listen () {
if (!this.authenticator) {
throw new Error('You must set authentication callback by app.auth()')
}
let promise = Promise.resolve()
if (this.options.server) {
this.ws = new WebSocket.Server({ server: this.options.server })
} else {
const before = []
if (this.options.key && !isPem(this.options.key)) {
before.push(readFile(this.options.root, this.options.key))
} else {
before.push(Promise.resolve(this.options.key))
}
if (this.options.cert && !isPem(this.options.cert)) {
before.push(readFile(this.options.root, this.options.cert))
} else {
before.push(Promise.resolve(this.options.cert))
}
promise = promise
.then(() => Promise.all(before))
.then(keys => new Promise((resolve, reject) => {
if (keys[0]) {
this.http = https.createServer({ key: keys[0], cert: keys[1] })
} else {
this.http = http.createServer()
}
this.ws = new WebSocket.Server({ server: this.http })
this.ws.on('error', reject)
this.http.listen(this.options.port, this.options.host, resolve)
}))
}
this.unbind.push(() => promisify(done => {
promise.then(() => {
this.ws.close(() => {
if (this.http) {
this.http.close(done)
} else {
done()
}
})
})
}))
return promise.then(() => {
this.ws.on('connection', ws => {
this.lastClient += 1
const connection = new ServerConnection(ws)
const client = new Client(this, connection, this.lastClient)
this.clients[this.lastClient] = client
})
}).then(() => {
this.reporter('listen', this)
})
}
/**
* Subscribe for synchronization events. It implements nanoevents API.
* Supported events:
*
* * `error`: server error.
* * `processed`: action processing was finished.
*
* @param {"error"|"processed"} event The event name.
* @param {listener} listener The listener function.
*
* @return {function} Unbind listener from event.
*
* @example
* sync.on('error', error => {
* trackError(error)
* })
*/
on (event, listener) {
return this.emitter.on(event, listener)
}
/**
* Add one-time listener for synchronization events.
* See {@link BaseServer#on} for supported events.
*
* @param {"error"|"processed"} event The event name.
* @param {listener} listener The listener function.
*
* @return {function} Unbind listener from event.
*
* @example
* sync.once('processed', () => {
* console.log('First work done')
* })
*/
once (event, listener) {
return this.emitter.once(event, listener)
}
/**
* Stop server and unbind all listeners.
*
* @return {Promise} Promise when all listeners will be removed.
*
* @example
* afterEach(() => {
* testApp.destroy()
* })
*/
destroy () {
this.destroing = true
this.reporter('destroy', this)
return Promise.all(this.unbind.map(i => i()))
}
/**
* Define action type’s callbacks.
*
* @param {string} name The action’s type.
* @param {object} callbacks Callbacks for actions with this type.
* @param {authorizer} callback.access Check does user can do this action.
* @param {processor} callback.process Action business logic.
*
* @return {undefined}
*
* @example
* app.type('CHANGE_NAME', {
* access (action, meta) {
* return action.user === meta.user
* },
* process (action, meta) {
* if (isFirstOlder(lastNameChange(action.user), meta)) {
* return db.changeUserName({ id: action.user, name: action.name })
* }
* }
* })
*/
type (name, callbacks) {
if (this.types[name]) {
throw new Error(`Action type ${ name } was already defined`)
}
if (!callbacks || !callbacks.access) {
throw new Error(`Action type ${ name } must have access callback`)
}
if (!callbacks.process) {
throw new Error(`Action type ${ name } must have process callback`)
}
this.types[name] = callbacks
}
/**
* Send runtime error stacktrace to all clients.
*
* @param {Error} error Runtime error instance.
*
* @return {undefined}
*
* @example
* process.on('uncaughtException', app.debugError)
*/
debugError (error) {
for (const i in this.clients) {
this.clients[i].connection.send(['debug', 'error', error.stack])
}
}
unknownAction (action, meta) {
if (meta.user) {
this.badAction(meta.id, 'error', 'unknowType')
} else {
this.log.changeMeta(meta.id, { status: 'processed' })
}
}
process (action, meta) {
const start = Date.now()
const type = this.types[action.type]
const user = this.getUser(meta.id[1])
forcePromise(() => type.access(action, meta, user)).then(result => {
if (!result) {
this.reporter('denied', this, action, meta)
this.badAction(meta.id, 'denied', 'denied')
return false
}
if (this.destroing) {
return false
}
this.processing += 1
return forcePromise(() => type.process(action, meta, user)).then(() => {
this.reporter('processed', this, action, meta, Date.now() - start)
this.processing -= 1
this.emitter.emit('processed', action, meta)
}).catch(e => {
this.badAction(meta.id, 'error', 'error')
this.emitter.emit('error', e, action, meta)
this.processing -= 1
this.emitter.emit('processed', action, meta)
})
}).catch(e => {
this.badAction(meta.id, 'error', 'error')
this.emitter.emit('error', e, action, meta)
})
}
badAction (id, status, reason) {
this.log.changeMeta(id, { status })
this.log.add(
{ type: 'logux/undo', reason, id },
{ reasons: ['error'], status: 'processed' })
}
getUser (nodeId) {
const pos = nodeId.indexOf(':')
if (pos !== -1) {
return nodeId.slice(0, pos)
} else {
return false
}
}
}
module.exports = BaseServer
/**
* @callback authenticator
* @param {string} id User ID.
* @param {any} credentials The client credentials.
* @param {Client} client Client object.
* @return {boolean|Promise} `true` or Promise with `true`
* if credentials was correct
*/
/**
* @callback authorizer
* @param {Action} action The action data.
* @param {Meta} meta The action metadata.
* @param {string|"server"} user User ID of action author. It will be `"server"`
* if user was created by server.
* @return {boolean|Promise} `true` or Promise with `true` if client are allowed
* to use this action.
*/
/**
* @callback processor
* @param {Action} action The action data.
* @param {Meta} meta The action metadata.
* @param {string|"server"} user User ID of action author. It will be `"server"`
* if user was created by server.
* @return {Promise|undefined} Promise when processing will be finished.
*/