-
Notifications
You must be signed in to change notification settings - Fork 5
/
server-library.js
2644 lines (2319 loc) · 102 KB
/
server-library.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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var fs = require('fs'),
util = require('util')
var braidify = require('braid-http').http_server
function default_options (bus) { return {
port: 'auto',
backdoor: null,
client: (c) => {c.shadows(bus)},
file_store: {save_delay: 250, filename: 'db', backup_dir: 'backups', prefix: '*'},
sync_files: [{state_path: 'files', fs_path: null}],
serve: true,
certs: {private_key: 'certs/private-key',
certificate: 'certs/certificate',
certificate_bundle: 'certs/certificate-bundle'},
connections: {include_users: true, edit_others: true},
websocket_path: '_connect_to_statebus_',
__secure: false
}}
function set_options (bus, options) {
var defaults = bus.clone(bus.options)
options = options || {}
for (var k in (options || {}))
bus.options[k] = options[k]
// Fill in defaults of nested options too
for (var k in {file_store:1, certs:1})
if (bus.options[k]) {
if (typeof bus.options[k] !== 'object' || bus.options[k] === null)
bus.options[k] = {}
for (var k2 in defaults[k])
if (!bus.options[k].hasOwnProperty(k2))
bus.options[k][k2] = defaults[k][k2]
}
}
function import_server (bus, make_statebus, options)
{ var extra_methods = {
serve: function serve (options) {
var master = bus
bus.honk = 'statelog'
master.label = 'master'
// Initialize Options
set_options(bus, options)
var use_ssl = bus.options.certs && (
require('fs').existsSync(bus.options.certs.private_key)
|| require('fs').existsSync(bus.options.certs.certificate)
|| require('fs').existsSync(bus.options.certs.certificate_bundle))
function c (client, conn) {
client.honk = bus.honk
client.serves_auth(conn, master)
bus.options.client && bus.options.client(client, conn)
}
if (!bus.options.client) c = undefined // no client bus when programmer explicitly says so
if (bus.options.file_store)
bus.file_store()
// ******************************************
// ***** Create our own http server *********
bus.make_http_server({port: bus.options.port, use_ssl})
bus.sockjs_server(this.http_server, c) // Serve via sockjs on it
var express = require('express')
bus.express = express()
bus.http = express.Router()
bus.install_express(bus.express)
// use gzip compression if available
try { bus.http.use(require('compression')())
console.log('Enabled http compression!') } catch (e) {}
// Initialize file sync
; (bus.options.sync_files || []).forEach( x => {
if (require('fs').existsSync(x.fs_path || x.state_path))
bus.sync_files(x.state_path, x.fs_path)
})
// User will put his routes in here
bus.express.use(bus.http)
// Connect bus to the HTTP server
bus.express.use(bus.http_in)
// Serve Client Coffee
bus.serve_client_coffee()
// Custom router
bus.route = function server_route (key, method, arg, t) {
var handlers = bus.bindings(key, method)
var count = handlers.length
if (count)
bus.log('route:', bus+'("'+key+'").'+method+'['+handlers.length+'](key:"'+(arg.key||arg)+'")')
// Call all handlers!
for (var i=0; i<handlers.length; i++)
bus.run_handler(handlers[i].func, method, arg, {t: t, binding: handlers[i].key})
// Now handle backup handlers
if (count === 0) {
// A set to master without a setter defined should be
// automatically reflected to all clients.
if (method === 'setter') {
bus.set.fire(arg, t)
bus.route(arg.key, 'on_set_sync', arg, t)
count++
}
// A get to master without a getter defined should go to
// the database, if we have one.
if (method === 'getter') {
bus.db_get(key)
// This basically renders the count useless-- you probably
// don't want to wrap this route() with another route().
count++
}
}
return handlers.length
}
// Back door to the control room
if (bus.options.backdoor) {
bus.make_http_server({
port: bus.options.backdoor,
name: 'backdoor_http_server',
use_ssl: use_ssl
})
bus.sockjs_server(this.backdoor_http_server)
}
},
// Connect HTTP GET and PUT to our Get and Set
http_in: function (req, res, next) {
if (bus.honk)
console.log(req.method, req.url, req.headers.subscribe
? 'Subscribe: ' + req.headers.subscribe : '')
braidify(req, res)
// If this requests knows about Braid then we presume the programmer
// knows that any client might make this cross-origin request.
if (req.headers.version || req.headers.parents || req.headers.subscribe
|| req.headers.peer || req.headers['put-order']
|| req.method === 'OPTIONS')
free_the_cors(req, res)
if (req.method === 'OPTIONS')
return
// Initialize new clients with an id. We put the client id on
// req.client, and also in a cookie for the browser to see.
req.peer = //req.headers.peer ||
require('cookie').parse(req.headers.cookie || '').peer
if (!req.peer) {
req.peer = (Math.random().toString(36).substring(2)
+ Math.random().toString(36).substring(2)
+ Math.random().toString(36).substring(2))
res.setHeader('Set-Cookie', 'peer=' + req.peer
+ '; Expires=21 Oct 2055 00:0:00 GMT;')
}
// Handle the GET or PUT request!
if (req.method === 'GET') {
var key = req.url.substr(1)
// Make a temporary client bus
var cbus = bus.bus_for_http_client(req, res)
if (req.subscribe)
res.startSubscription({ onClose: end_subscription })
else
res.statusCode = 200
// We only return JSON
res.setHeader('Content-Type', 'application/json')
// console.log('http_in: doing cbus.get(', key, ')')
var send_to_client = (o, t) => {
console.log('http_in: Sending update of', {key, o, res})
var body = to_http_body(o)
// Note: if body === undefined, we need to send the
// equivalent of a 404. This is missing in braid spec:
// https://github.com/braid-org/braid-spec/issues/110
res.sendUpdate({body: body || 'null'})
// And shut down the connection if there's no subscription
if (!req.subscribe)
end_subscription()
}
function end_subscription () {
cbus.forget(key, send_to_client)
res.end()
cbus.http_unsubscribe(req)
let peer = req.headers.peer
if (cbus.http_callbacks)
delete cbus.http_callbacks[JSON.stringify({peer, key})]
}
// If we have a peer id, then register this callback at that peer,
// so it can avoid getting its own PUT versions echoed back to
// itself.
if (req.headers.peer) {
if (!cbus.http_callbacks)
cbus.http_callbacks = {}
let peer = req.headers.peer
cbus.http_callbacks[JSON.stringify({peer, key})]
= send_to_client
}
// And issue the get!
cbus.get(key, send_to_client)
}
else if (req.method === 'PUT') {
// Maybe the new state is expressed in patches
if (req.headers.patches || req.headers['content-range']) {
var patches = req.patches().then(patches => {
console.log("...and we see these patches:", patches)
var cbus = bus.bus_for_http_client(req, res)
var key = req.url.substr(1)
cbus.get_once(key, (obj) => {
cbus.set(key, {patches})
res.sendStatus(200)
console.log('We just processed a patch!')
})
})
} else {
// Otherwise, we assume the body is content-type: json
if (typeof req.headers['content-type'] !== 'string'
|| req.headers['content-type'].toLowerCase() !== 'application/json')
console.error('Error: PUT content-type is not application/json')
var body = ''
req.on('data', chunk => {body += chunk.toString()})
req.on('end', () => {
try {
var path = req.url.substr(1)
var obj = from_http_body(path, body)
} catch (e) {
console.error('Error: PUT body was not valid json', e)
res.statusCode = 500
res.end()
return
}
// Make a temporary client bus
var cbus = bus.bus_for_http_client(req, res)
var t = {
version: req.version || cbus.new_version(),
parents: req.parents
}
// If the peer declares itself, let's remember it so that
// we don't send it echoes
if (req.headers.peer) {
let peer = req.headers.peer,
key = obj.key
var cb = cbus.http_callbacks && cbus.http_callbacks[
JSON.stringify({peer, key})
]
if (cb) cb.has_seen(cbus, key, t.version)
}
// Now send the version to the bus!
cbus.set(obj, t)
res.statusCode = 200
res.end()
cbus.http_unsubscribe(req)
})
}
}
else
next()
},
bus_for_http_client: function (req, res) {
var bus = this
if (!bus.bus_for_http_client.counter) {
bus.bus_for_http_client.counter = 0
bus.bus_for_http_client.busses = {}
}
// If this client has a peer ID, and we've got a bus for that peer,
// then re-use it!
if (req.peer && bus.bus_for_http_client.busses[req.peer]) {
var cbus = bus.bus_for_http_client.busses[req.peer]
cbus.client_ip = req.connection.remoteAddress
cbus.num_subscriptions++
return cbus
}
// Otherwise, create a new bus
var cbus = make_statebus()
cbus.label = 'client_http' + bus.bus_for_http_client.counter++
cbus.master = bus
cbus.num_subscriptions = 1
cbus.http_unsubscribe = (req) => {
cbus.num_subscriptions--
if (cbus.num_subscriptions === 0) {
// log('Last subscription! Killing client bus!')
cbus.delete_bus()
delete bus.bus_for_http_client.busses[req.peer]
}
}
bus.bus_for_http_client.busses[req.peer] = cbus
// And log into it as the client
cbus.serves_auth({remoteAddress: req.connection.remoteAddress}, bus)
bus.options.client(cbus)
cbus.set({key: 'current_user', val: {client: req.peer}})
return cbus
},
make_http_server: function make_http_server (options) {
options = options || {}
var fs = require('fs')
if (options.use_ssl) {
// Load with TLS/SSL
console.log('Encryption ON')
// use http2 compatible library if available
try {
var http = require('spdy')
console.log('Found spdy library. HTTP/2 enabled!')
} catch (e) {
var http = require('https')
}
var protocol = 'https'
var ssl_options = {
ca: (fs.existsSync(this.options.certs.certificate_bundle)
&& require('split-ca')(this.options.certs.certificate_bundle)),
key: fs.readFileSync(this.options.certs.private_key),
cert: fs.readFileSync(this.options.certs.certificate),
ciphers: "ECDHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA384"
+ ":ECDHE-RSA-AES256-SHA256:DHE-RSA-AES256-SHA256"
+ ":ECDHE-RSA-AES128-SHA256:DHE-RSA-AES128-SHA256"
+ ":HIGH:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!SRP:!CAMELLIA",
honorCipherOrder: true}
}
else {
// Load unencrypted server
console.log('Encryption OFF')
var http = require('http')
var protocol = 'http'
var ssl_options = undefined
}
if (options.port === 'auto') {
var bind = require('./extras/tcp-bind')
function find_a_port () {
var next_port_attempt = 80
while (true)
try {
var result = bind(next_port_attempt)
bus.port = next_port_attempt
return result
} catch (e) {
if (next_port_attempt < 3007) next_port_attempt = 3007
else next_port_attempt++
}
}
var fd
if (options.use_ssl)
try {
fd = bind(443)
bus.port = 443
bus.redirect_port_80()
} catch (e) {fd = find_a_port()}
else fd = find_a_port()
var http_server = http.createServer(ssl_options)
http_server.listen({fd: fd}, () => {
console.log('Listening on '+protocol+'://<host>:'+bus.port)
})
}
else {
bus.port = bus.options.port
var http_server = http.createServer(ssl_options)
http_server.listen(bus.options.port, () => {
console.log('Listening on '+protocol+'://<host>:'+bus.port)
})
}
bus[options.name || 'http_server'] = http_server
},
redirect_port_80: function redirect_port_80 () {
var redirector = require('http')
redirector.createServer(function (req, res) {
res.writeHead(301, {"Location": "https://"+req.headers['host']+req.url})
res.end()
}).listen(80)
},
install_express: function install_express (express_app) {
this.http_server.on('request', // Install express
function (request, response) {
// But express should ignore all sockjs requests
if (!request.url.startsWith(
'/' + bus.options.websocket_path + '/'))
express_app(request, response)
})
},
sockjs_server: function sockjs_server(httpserver, client_bus_func) {
var master = this
var client_num = 0
// var client_busses = {} // XXX work in progress
var log = master.log
if (client_bus_func) {
master.set({key: 'connections', val: {}}) // Clean out old sessions
var connections = master.get('connections')
}
var s = require('sockjs').createServer({
sockjs_url: 'https://cdn.jsdelivr.net/sockjs/0.3.4/sockjs.min.js',
disconnect_delay: 600 * 1000,
heartbeat_delay: 6000 * 1000
})
s.on('connection', function(conn) {
if (client_bus_func) {
// To do for pooling client busses:
// - What do I do with connections? Do they pool at all?
// - Before creating a new bus here, check to see if there's
// an existing one in the pool, and re-use it if so.
// - Count the number of connections using a client.
// - When disconnecting, decrement the number, and if it gets
// to zero, delete the client bus.
connections.val[conn.id] = {client: conn.id, // client is deprecated
id: conn.id}
master.set(connections)
var client = make_statebus()
client.label = 'client' + client_num++
master.label = master.label || 'master'
client.master = master
client_bus_func(client, conn)
} else
var client = master
var our_gets_in = {} // Every key that this socket has got
log('sockjs_s: New connection from', conn.remoteAddress)
function sockjs_pubber (obj, t) {
// log('sockjs_pubber:', obj, t)
var msg = {set: obj}
if (t.version) msg.version = t.version
if (t.parents) msg.parents = t.parents
if (t.patches) msg.patches = t.patches
if (t.patches) msg.set = msg.set.key
msg = JSON.stringify(msg)
if (master.simulate_network_delay) {
console.log('>>>> DELAYING!!!', master.simulate_network_delay)
obj = bus.clone(obj)
setTimeout(() => {conn.write(msg)}, master.simulate_network_delay)
} else
conn.write(msg)
log('sockjs_s: SENT a', msg, 'to client')
}
conn.on('data', function(message) {
log('sockjs_s:', message)
try {
message = JSON.parse(message)
var method = bus.message_method(message)
// Validate the message
if (!((method === 'get'
&& master.validate(message, {get: 'string',
'?parent': 'string', '?version': 'string'}))
||
(method === 'set'
&& master.validate(message, {set: '*',
'?parents': 'array', '?version': 'string', '?patches': 'array'})
&& (typeof(message.set) === 'string'
|| (typeof(message.set) === 'object'
&& typeof(message.set.key === 'string'))))
||
(method === 'forget'
&& master.validate(message, {forget: 'string'}))
||
(method === 'delete'
&& master.validate(message, {'delete': 'string'}))))
throw 'validation error'
} catch (e) {
for (var i=0; i<4; i++) console.error('#######')
console.error('Received bad sockjs message from '
+ conn.remoteAddress +': ', message, e)
return
}
switch (method) {
case 'get':
our_gets_in[message.get] = true
client.get(message.get, sockjs_pubber)
break
case 'forget':
delete our_gets_in[message.forget]
client.forget(message.forget, sockjs_pubber)
break
case 'delete':
client.delete(message['delete'])
break
case 'set':
message.version = message.version || client.new_version()
if (message.patches) {
var o = bus.cache[message.set] || {key: message.set}
try {
message.set = bus.apply_patch(o.val, message.patches[0])
} catch (e) {
console.error('Received bad sockjs message from '
+ conn.remoteAddress +': ', message, e)
return
}
}
client.set(message.set,
{version: message.version,
parents: message.parents,
patches: message.patches})
if (our_gets_in[message.set.key]) { // Store what we've seen if we
// might have to publish it later
client.log('Adding', message.set.key+'#'+message.version,
'to pubber!')
sockjs_pubber.has_seen(client, message.set.key, message.version)
}
break
}
// validate that our gets_in are all in the bus
for (var key in our_gets_in)
if (!client.gets_in.has(key, master.funk_key(sockjs_pubber)))
console.trace("***\n****\nFound errant key", key,
'when receiving a sockjs', method, 'of', message)
//log('sockjs_s: done with message')
})
conn.on('close', function() {
log('sockjs_s: disconnected from', conn.remoteAddress, conn.id, client.id)
for (var key in our_gets_in)
client.forget(key, sockjs_pubber)
if (client_bus_func) {
delete connections.val[conn.id]; master.set(connections)
master.delete('connection/' + conn.id)
client.delete_bus()
}
})
// Define the /connection* state!
if (client_bus_func && !master.options.__secure) {
// A connection
client('connection/*').getter = function (key, star) {
var result = bus.clone(master.get(key))
if (master.options.connections.include_users && result.user)
result.user = client.get(result.user.key)
result.id = star
result.client = star // Deprecated. Delete this line in v7.
return result
}
client('connection/*').setter = function (o, star, t) {
// Check permissions before editing
if (star !== conn.id && !master.options.connections.edit_others) {
t.abort()
return
}
o.id = star
o.client = star // Deprecated. Delete this line in v7.
master.set(client.clone(o))
}
// Your connection
client('connection').getter = function () {
// subscribe to changes in authentication
client.get('current_user')
var result = client.clone(client.get('connection/' + conn.id))
delete result.key
return result
}
client('connection').setter = function (o) {
o = client.clone(o)
o.key = 'connection/' + conn.id
client.set(o)
}
// All connections
client('connections').setter = function noop (t) {t.abort()}
client('connections').getter = function () {
var result = []
var conns = master.get('connections').val
for (var connid in conns)
if (connid !== 'key')
result.push(client.get('connection/' + connid))
return {val: result}
}
}
})
// console.log('websocket listening on', '/' + bus.options.websocket_path)
s.installHandlers(httpserver, {prefix:'/' + bus.options.websocket_path})
},
make_websocket: function make_websocket (url) {
url = url.replace(/^state:\/\//, 'wss://')
url = url.replace(/^istate:\/\//, 'ws://')
url = url.replace(/^statei:\/\//, 'ws://')
WebSocket = require('websocket').w3cwebsocket
return new WebSocket(url + '/' + bus.options.websocket_path + '/websocket')
},
file_store: (function () {
// Make a database
var fs = require('fs')
var db = {}
var db_is_ok = false
var pending_save = null
var active
function file_store (prefix, delay_activate) {
prefix = prefix || bus.options.file_store.prefix
var filename = bus.options.file_store.filename,
backup_dir = bus.options.file_store.backup_dir
// Loading db
try {
if (fs.existsSync && !fs.existsSync(filename))
(fs.writeFileSync(filename, '{}'), bus.log('Made a new db file'))
db = JSON.parse(fs.readFileSync(filename))
db_is_ok = true
// If we set before anything else is connected, we'll get this
// into the cache but not affect anything else
bus.set.fire(global.pointerify ? inline_pointers(db) : db)
bus.log('Read db')
} catch (e) {
console.error(e)
console.error('bad db file')
}
// Saving db
function save_db() {
if (!db_is_ok) return
// console.time('saved db')
fs.writeFile(filename+'.tmp', JSON.stringify(db, null, 1), function(err) {
if (err) {
console.error('Crap! DB IS DYING!!!!', err)
db_is_ok = false
} else
fs.rename(filename+'.tmp', filename, function (err) {
if (err) {
console.error('Crap !! DB IS DYING !!!!', err)
db_is_ok = false
} else {
// console.timeEnd('saved db')
pending_save = null
}
})
})
}
function save_later() {
pending_save = pending_save || setTimeout(save_db, bus.options.file_store.save_delay)
}
active = !delay_activate
// Replaces every nested keyed object with {_key: <key>}
function abstract_pointers (o) {
o = bus.clone(o)
var result = {}
for (var k in o)
result[k] = bus.deep_map(o[k], (o) => {
if (o && o.key) return {_key: o.key}
else return o
})
return result
}
// ...and the inverse
function inline_pointers (db) {
return bus.deep_map(db, (o) => {
if (o && o._key)
return db[o._key]
else return o
})
}
function on_set (obj) {
db[obj.key] = global.pointerify ? abstract_pointers(obj) : obj
if (active) save_later()
}
on_set.priority = true
bus(prefix).on_set = on_set
bus(prefix).deleter = function (key) {
delete db[key]
if (active) save_later()
}
file_store.activate = function () {
active = true
save_later()
}
// Handling errors
function recover (e) {
if (e) {
process.stderr.write("Uncaught Exception:\n");
process.stderr.write(e.stack + "\n");
}
if (pending_save) {
console.log('Saving db after crash')
console.time()
fs.writeFileSync(filename, JSON.stringify(db, null, 1))
console.log('Saved db after crash')
}
process.exit(1)
}
process.on('SIGINT', recover)
process.on('SIGTERM', recover)
process.on('uncaughtException', recover)
// Rotating backups
setInterval(
// This copies the current db over backups/db.<curr_date> every minute
function backup_db() {
if (!db_is_ok || !backup_dir) return
if (fs.existsSync && !fs.existsSync(backup_dir))
fs.mkdirSync(backup_dir)
var d = new Date()
var y = d.getYear() + 1900
var m = d.getMonth() + 1
if (m < 10) m = '0' + m
var day = d.getDate()
if (day < 10) day = '0' + day
var date = y + '-' + m + '-' + day
//bus.log('Backing up db on', date)
require('child_process').execFile(
'/bin/cp', [filename, backup_dir+'/'+filename+'.'+date])
},
1000 * 60 // Every minute
)
}
return file_store
})(),
firebase_store: function (prefix, firebase_ref) {
prefix = prefix || '*'
function encode_firebase_key(k) {
return encodeURIComponent(k).replace(/\./g, '%2E')
}
function decode_firebase_key(k) {
return decodeURIComponent(k.replace('%2E', '.'))
}
bus(prefix).getter = function (key, t) {
firebase_ref.child(encode_firebase_key(key)).on('value', function (x) {
t.done(x.val() || {})
}, function (err) { t.abort() })
}
bus(prefix).on_set = function (o) {
firebase_ref.child(encode_firebase_key(o.key)).set(o)
}
// bus(prefix).setter = function (o, t) {
// firebase_ref.child(encode_firebase_key(o.key)).set(o, (err) => {
// err ? t.abort() : t.done()
// })
// }
bus(prefix).deleter = function (key, t) {
firebase_ref.child(encode_firebase_key(key)).set(null, (err) => {
err ? t.abort() : t.done()
})
}
bus(prefix).forgetter = function (key, t) {
firebase_ref.child(encode_firebase_key(key)).off()
}
},
db_get: function db_get (key) {/* does nothing unless overridden */},
lazy_sqlite_store: function lazy_sqlite_store (opts) {
if (!opts) opts = {}
opts.lazy = true
bus.sqlite_store(opts)
},
fast_load_sqlite_store: function sqlite_store (opts) {
if (!opts) opts = {}
opts.dont_fire = true
bus.sqlite_store(opts)
},
sqlite_store: function sqlite_store (opts) {
var prefix = '*'
var open_transaction = null
if (!opts) opts = {}
if (!opts.filename) opts.filename = 'db.sqlite'
if (!opts.hasOwnProperty('inline_pointers'))
opts.inline_pointers = global.pointerify
// Load the db on startup
try {
var db = bus.sqlite_store_db || new (require('better-sqlite3'))(opts.filename)
bus.sqlite_store_db = db
bus.sqlite_store.load_all = load_all
bus.sqlite_store.all_keys = all_keys
db.pragma('journal_mode = WAL')
db.prepare('create table if not exists cache (key text primary key, obj text)').run()
function all_keys () {
var result = []
for (var row of db.prepare('select key from cache').iterate())
result.push(row.key)
return result
}
function load_all (options) {
var temp_db = {}
for (var row of db.prepare('select * from cache').iterate()) {
var obj = JSON.parse(row.obj)
temp_db[obj.key] = obj
}
if (opts.inline_pointers)
temp_db = inline_pointers(temp_db)
for (var key in temp_db)
if (temp_db.hasOwnProperty(key)) {
if (options.dont_fire)
bus.cache[key] = temp_db[key]
else
bus.set.fire(temp_db[key])
temp_db[key] = undefined
}
}
if (!opts.lazy) load_all(opts)
bus.log('Read ' + opts.filename)
} catch (e) {
console.error(e)
console.error('Bad sqlite db')
}
function sqlite_get (key) {
// console.log('sqlite_get:', key)
var x = db.prepare('select * from cache where key = ?').get([key])
return x ? JSON.parse(x.obj) : {}
}
if (opts.lazy) {
var db_getted_keys = {}
bus.db_get = bus.reactive(function (key) {
if (db_getted_keys[key]) return
db_getted_keys[key] = true
// Get it from the database
var obj = sqlite_get(key)
// Inline pointers if enabled (does this still work?)
if (opts.inline_pointers) obj = inline_pointers_singleobj(obj)
// Ensure we have the latest version of everything nested
obj = bus.deep_map(obj, (o) => (o && o.key
? sqlite_get(o.key)
: o))
// Publish this to the bus
bus.set.fire(obj, {getter: true})
})
}
// Add set handlers
function on_set (obj) {
if (opts.inline_pointers)
obj = abstract_pointers(obj)
if (opts.use_transactions && !open_transaction){
console.time('save db')
db.prepare('BEGIN TRANSACTION').run()
}
db.prepare('replace into cache (key, obj) values (?, ?)').run(
[obj.key, JSON.stringify(obj)])
if (opts.use_transactions && !open_transaction) {
open_transaction = setTimeout(function(){
console.log('Committing transaction to database')
db.prepare('COMMIT').run()
open_transaction = false
console.timeEnd('save db')
})
}
}
if (opts.set_sync) {
var old_route = bus.route
bus.route = function (key, method, arg, t) {
if (method === 'setter') on_set(arg)
return old_route(key, method, arg, t)
}
} else
bus(prefix).on_set_sync = on_set
bus(prefix).deleter = function (key) {
if (opts.use_transactions && !open_transaction){
console.time('save db')
db.prepare('BEGIN TRANSACTION').run()
}
db.prepare('delete from cache where key = ?').run([key])
if (opts.use_transactions && !open_transaction)
open_transaction = setTimeout(function(){
console.log('committing')
db.prepare('COMMIT').run()
open_transaction = false
console.timeEnd('save db')
})
}
// Replaces every nested keyed object with {_key: <key>}
function abstract_pointers (o) {
o = bus.clone(o)
var result = {}
for (var k in o)
result[k] = bus.deep_map(o[k], (o) => {
if (o && o.key) return {_key: o.key}
else return o
})
return result
}
// ...and the inverse
function inline_pointers (db) {
return bus.deep_map(db, (o) => {
if (o && o._key)
return db[o._key]
else return o
})
}
function inline_pointers_singleobj (obj) {
return bus.deep_map(obj, (o) => (o && o._key)
? bus.cache[o._key] : o)
}
// Rotating backups
setInterval(
// Copy the current db over backups/db.<curr_date> every minute
//
// Note: in future we might want to use db.backup():
// https://github.com/JoshuaWise/better-sqlite3/blob/master/docs/api.md#backupdestination-options---promise
function backup_db() {
if (opts.backups === false) return
var backup_dir = opts.backup_dir || 'backups'
if (fs.existsSync && !fs.existsSync(backup_dir))
fs.mkdirSync(backup_dir)
var d = new Date()
var y = d.getYear() + 1900
var m = d.getMonth() + 1
if (m < 10) m = '0' + m
var day = d.getDate()
if (day < 10) day = '0' + day
var date = y + '-' + m + '-' + day
require('child_process').execFile(
'sqlite3',
[opts.filename, '.backup '+"'"+backup_dir+'/'+opts.filename+'.'+date+"'"])
},
1000 * 60 // Every minute
)
},
pg_store: function pg_store (opts) {
opts = opts || {}
opts.prefix = opts.prefix || '*'
// Load the db on startup
try {
var db = new require('pg-native')()
bus.pg_db = db
bus.pg_set = pg_set
db.connectSync(opts.url)
db.querySync('create table if not exists store (key text primary key, value jsonb)')