-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathserver.js
544 lines (426 loc) · 14.4 KB
/
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
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
// Alright.
//
// So this will have 3 APIs:
//
// - Write API - POST JSON edits to /edit or something
// - Fetch image API - this will only be hit by nginx. It returns the current place image and its version
// - Event stream API - This is a server-sent event stream which will just forward events from kafka.
process.title = 'sephplace'
// lmdb will be used to store the local image cache.
const lmdb = require('node-lmdb')
// Messages in kafka will be encoded using msgpack.
const msgpack = require('msgpack-lite')
const assert = require('assert')
const PNG = require('pngjs').PNG
const kafka = require('kafka-node')
const fresh = require('fresh')
const url = require('url')
const WSS = require('ws').Server;
const express = require('express')
const fs = require('fs')
const kclient = new kafka.Client()
const app = express()
const server = require('http').createServer(app)
const wss = new WSS({server, perfMessageDeflate: false})
app.use('/sp', express.static(__dirname + '/public'))
// This is important so we can hot-resume when the server starts without
// needing to read the entire kafka log. A file would almost be good enough,
// but we need to atomically write to it. So, this is easier.
const dbenv = new lmdb.Env()
if (!fs.existsSync('snapshot')) fs.mkdirSync('snapshot')
dbenv.open({ path: 'snapshot', mapSize: 100*1024*1024 })
const snapshotdb = dbenv.openDbi({create: true})
const randInt = max => (Math.random() * max) | 0
const loadSnapshot = () => {
// Read a snapshot from the database if we can.
const txn = dbenv.beginTxn({readOnly: true})
const _version = txn.getNumber(snapshotdb, 'version')
if (_version != null) {
const data = txn.getBinary(snapshotdb, 'current')
assert(data)
console.log('loaded snapshot at version', _version)
return [data, _version]
} else {
console.log('snapshot database empty. Replaying entire log')
// Technically I only need half this much space - its only 4 bit color after all.
const data = new Buffer(1000 * 1000)
data.fill(0)
return [data, -1]
}
txn.commit()
}
let [imgData, version] = loadSnapshot()
const palette = [
[255, 255, 255], // white
[228, 228, 228], // light grey
[136, 136, 136], // grey
[34, 34, 34], //black
[255,167,209], // pink
[229, 0, 9], // red
[229, 149, 0], // orange
[160, 106, 66], // brown
[229, 217, 0], // yellow
[148, 224, 68], // light green
[2, 190, 1], // green
[0, 211, 221], // cyan
[0, 131, 199], // medium blue
[0, 0, 234], // dark blue
[207, 110, 228], // light purple
[130, 0, 128], // dark Purple
]
/*
const palettePacked = palette.map(arr =>
(arr[2] << 16) | (arr[1] << 8) | (arr[0])
)*/
// This is an RGB buffer kept up to date with each edit to the indexed buffer.
// Maintaining this makes encoding the png a bit faster (320ms -> 250ms),
// although I'm not sure if the complexity is really worth it.
const imgBuffer = new Buffer(1000 * 1000 * 3)
{
for (let y = 0; y < 1000; y++) {
for (let x = 0; x < 1000; x++) {
const px = y * 1000 + x
//const color = palette[randInt(16)]//palette[imgData[px]]
const color = palette[imgData[px]]
imgBuffer[px*3] = color[0]
imgBuffer[px*3+1] = color[1]
imgBuffer[px*3+2] = color[2]
}
}
}
const setRaw = (x, y, index) => {
const px = y * 1000 + x
imgData[px] = index
const color = palette[index]
imgBuffer[px*3] = color[0]
imgBuffer[px*3+1] = color[1]
imgBuffer[px*3+2] = color[2]
}
app.get('/', (req, res) => res.redirect('/sp/'))
app.get('/sp/current', (req, res) => {
const resHeaders = {
// Weirdly, setting this to a lower value is sort of good because it means
// we won't have to keep as many clients up to date.
//
// Using expires instead of cache-control because nginx isn't decrementing
// the max-age parameter as the document gets older.
//'cache-control': 'public; max-age=300',
'expires': new Date(Date.now() + 10 * 1000).toUTCString(), // 10 seconds.
//'age': '0',
}
if (fresh(req.headers, resHeaders)) {
//console.log('cached!')
res.statusCode = 304
return res.end()
}
// This takes about 300ms to load.
res.setHeader('content-type', 'image/png')
res.setHeader('x-content-version', version)
for (const k in resHeaders) res.setHeader(k, resHeaders[k])
// TODO: Find a PNG encoder which supports indexed pngs. It'll be way faster that way.
const img = new PNG({
width: 1000, height: 1000,
colorType: 2, // color but no alpha
bitDepth: 8,
inputHasAlpha: false,
})
img.data = imgBuffer
img.pack().pipe(res)
})
// This is a buffer containing a bunch of recent operations.
let opbase = 0
const opbuffer = []
let lasthead = 0
setInterval(() => {
// Trim the op buffer down to size. The buffer only needs to store ops for
// the amount of cache time + expected latency time.
//console.log('opbase', opbase, 'opbuffer', opbuffer.length)
const newhead = opbase + opbuffer.length
if (lasthead === 0) {
// First time through.
lasthead = newhead
return
}
// Trim everything from opbase -> lasthead
opbuffer.splice(0, lasthead - opbase)
opbase = lasthead
lasthead = newhead
//console.log('-> opbase', opbase, 'opbuffer', opbuffer.length, 'lasthead', lasthead)
}, 20000)
// Each edit is 3 bytes (10 bits x, 10 bits y, 4 bits for color).
const encodeEditTo = (buffer, offset, x, y, color) => {
// Writes in buffer[offset], buffer[offset+1] and buffer[offset+2].
assert(x >= 0 && x < 1000 && y >= 0 && y < 1000 & color >= 0 && color < 16)
// Encoding:
// byte 1 is just the lower 8 bits of x
// byte 2 is the upper 2 bits of x and the lower 6 bits of y
// byte 3 is the upper 4 bits of y then the color.
buffer[offset] = x & 0xff
buffer[offset + 1] = (x >>> 8) | ((y & 0x3f) << 2)
buffer[offset + 2] = ((y & 0x3c0) >> 6) | color << 4
}
const decodeEdit = (buffer, offset) => { // returns x, y, color.
const xx = buffer[offset]
const yx = buffer[offset + 1]
const cy = buffer[offset + 2]
const x = xx | ((yx & 0x3) << 8)
const y = (yx >>> 2) | ((cy & 0xf) << 6)
const c = cy >> 4
return [x, y, c]
}
{
// Lets just check.
const b = new Buffer(3)
encodeEditTo(b, 0, 333, 666, 15)
assert.deepEqual(decodeEdit(b, 0), [333, 666, 15])
}
//const buffer = new Buffer(1000 * 1000) // 1MB should be plenty.
// This is sort of gross. I'm using it to send a fast-start to clients. It
// could be optimized to only send one message instead of one per read.
function pack(v, data) {
if (Array.isArray(data)) {
const [x, y, color] = data
const b = new Buffer(4 + 3)
b.writeUInt32LE(v, 0)
encodeEditTo(b, 4, x, y, color)
return b
} else {
const b = new Buffer(4 + data.length)
b.writeUInt32LE(v, 0)
data.copy(b, 4)
return b
}
}
// WS feed
wss.on('connection', client => {
const fromstr = url.parse(client.upgradeReq.url, true).query.from
const err = (message) => {
client.send("error: " + message)
client.close()
console.error('WS Error', message)
}
// from of 'latest' will bypass from checking and bypass the catchup. This is
// used for load testing.
if (fromstr == null || (fromstr !== 'latest' && isNaN(+fromstr))) return err('Invalid from= parameter')
const from = fromstr === 'latest' ? (opbase + opbuffer.length) : ((fromstr|0) + 1)
if (from < opbase) {
client.send('reload')
client.close()
return
}
//console.log('client connected at version', from, 'and were at', opbase + opbuffer.length)
for (let i = from - opbase; i < opbuffer.length; i++) client.send(pack(i + opbase, opbuffer[i]))
client.on('message', msg => {
// TODO: Allow edits here via WS instead of HTTP.
console.log('got message', msg.length)
})
})
// Server-sent events feed.
app.get('/sp/changes', (req, res, next) => {
// TODO: Add a local buffer and serve recent operations out of that.
res.setHeader('content-type', 'text/event-stream')
res.setHeader('cache-control', 'no-cache')
// Make the client refresh their browser so they pick up the new WS code.
res.write('\n')
res.write('data: refresh\n\n')
res.end()
})
const kproducer = new kafka.Producer(kclient)
const inRange = (x, min, max) => (x >= min && x < max)
function doNothing() {}
// An aggregator is basically a reduce function thats called over time. It will
// call the dispatch function at most once per timeout period, and messages
// sent to the aggregator will be delayed by no more than the timeout.
function makeAggregator(timeout, aggregate, dispatch) {
let pending = false
return (...args) => {
aggregate(...args)
if (!pending) {
pending = true
setTimeout(() => {
pending = false
dispatch()
}, timeout)
}
}
}
// This is a buffer of the incoming writes.
const processEdit = (() => {
const buffer = new Buffer(1000 * 100 * 3) // 100k edits per 200ms. Proooobably fine.
let pos = 0
let callbacks = []
// Hold messages for up to 200ms. Maximum roundtrip time will be this delay +
// equivalent delay for sending.
const ag = makeAggregator(200, (x, y, c) => {
encodeEditTo(buffer, pos, x, y, c)
pos += 3
}, () => {
const cbs = callbacks
callbacks = []
kproducer.send([{
topic: 'sephsplace',
// message type 0, x, y, color.
messages: [msgpack.encode([1, buffer.slice(0, pos), Date.now()])],
}], err => {
if (err) console.error('error publishing to producer', err)
for (let i = 0; i < cbs.length; i++) cbs[i](err)
})
pos = 0
})
return (x, y, c, callback) => {
if (callback) callbacks.push(callback)
ag(x, y, c)
}
})()
const banlist = new Set
try {
const entries = JSON.parse(fs.readFileSync('banlist.json', 'utf-8'))
entries.forEach(e => banlist.add(e))
} catch (e) { console.log('could not load banlist', e) }
const ban = (address) => {
if (!banlist.has(address)) {
console.log('banning', address)
banlist.add(address)
fs.writeFileSync('banlist.json', JSON.stringify(Array.from(banlist)))
}
}
const byUserAgent = new Map
const editsByAddress = new Map
const getDef = (map, key, deffn) => {
let val = map.get(key)
if (val == null) {
val = deffn()
map.set(key, val)
}
return val
}
setInterval(() => {
//console.log(editsByAddress)
editsByAddress.clear()
//console.log(byUserAgent) // for ban detection
byUserAgent.clear()
}, 10000)
app.post('/sp/edit', (req, res, next) => {
if (req.query.x == null || req.query.y == null || req.query.c == null) return next(Error('Invalid query'))
const x = req.query.x|0, y = req.query.y|0, c = req.query.c|0
if (!inRange(x, 0, 1000) || !inRange(y, 0, 1000) || !inRange(c, 0, 16)) return next(Error('Invalid value'))
// Simple rate limiting. Only allow 10 edits per 10 second window.
const ua = req.headers['user-agent']
const address = req.headers['x-forwarded-for'] || req.connection.remoteAddress
// I don't have anything against python. This was just added to stop a
// particular user drawing crap with a botnet. Details here:
// https://news.ycombinator.com/item?id=14125518
//if (ua === 'python-requests/2.10.0') ban(address)
if (banlist.has(address)) return res.end()
const edits = getDef(editsByAddress, address, () => 0)
// Rate limited.
//
// 50 points per 10 seconds. Drawing in white space costs 2 point. Everything else costs 5 for now.
if (edits > 50) return res.sendStatus(403)
const px = y * 1000 + x
editsByAddress.set(address, edits + (imgData[px] === 0 ? 2 : 5))
const m = getDef(byUserAgent, ua, () => new Set()).add(address)
processEdit(x, y, c, err => {
if (err) next(err)
else res.end()
})
})
const stats = {sentPackets:0, sentBytes:0, editMessages:0, edits:0}
const broadcastPack = (() => {
let version = -1
const buffer = new Buffer(1000 * 100 * 3) // Way bigger than we need.
let pos = 4
return makeAggregator(500, (pack, v) => {
version = v
pack.copy(buffer, pos)
pos += pack.length
}, () => {
buffer.writeUInt32LE(version, 0)
const slice = buffer.slice(0, pos)
// OPEN
for (const c of wss.clients) if (c.readyState === 1) {
stats.sentPackets++
stats.sentBytes += slice.length
c.send(slice)
}
pos = 4
})
})()
setInterval(() => {
stats.numClients = wss.clients.size
console.log((new Date()).toISOString(), 'stats', JSON.stringify(stats))
for (const k in stats) stats[k] = 0
}, 10000)
// Buffer up 1000 operations from the server.
opbase = Math.max(version - 1000, 0)
const kconsumer = new kafka.Consumer(kclient, [{topic: 'sephsplace', offset: opbase}], {
encoding: 'buffer',
fromOffset: true,
})
kconsumer.on('message', _msg => {
stats.editMessages++
const offset = _msg.offset
if (offset !== opbase + opbuffer.length) {
console.error('ERROR DOES NOT MATCH', offset, opbase, opbuffer.length, opbase + opbuffer.length)
return
}
const msg = msgpack.decode(_msg.value)
const type = msg[0]
switch(type) {
case 0: {
// Single edit.
const [_, x, y, color] = msgpack.decode(_msg.value)
const msgout = [x, y, color]
opbuffer[offset - opbase] = msgout
//console.log('got normal message', x, y, color)
if (offset > version) {
stats.edits++
setRaw(x, y, color)
const b = new Buffer(3)
encodeEditTo(b, 0, x, y, color)
broadcastPack(b, offset)
}
break
}
case 1: {
// Pack of many encoded xyc values.
const buf = msg[1]
opbuffer[offset - opbase] = buf
//console.log('got pack', buf.length / 3)
for (let off = 0; off < buf.length; off += 3) {
stats.edits++
const [x,y,c] = decodeEdit(buf, off)
setRaw(x, y, c)
}
broadcastPack(buf, offset)
break
}
default:
throw Error('Cannot decode kafka message of type ' + type)
}
if (offset > version) {
assert(offset === version + 1)
version = offset
if (version % 50 === 0) {
// Commit the updated data.
console.log((new Date()).toISOString(), 'committing version', offset)
const txn = dbenv.beginTxn()
txn.putBinary(snapshotdb, 'current', imgData)
txn.putNumber(snapshotdb, 'version', offset)
txn.commit()
}
}
})
const pmid = process.env.pm_id
const port = process.env.PORT || (3211 + (pmid ? (pmid|0) : 0))
kproducer.once('ready', () => {
kproducer.createTopics(['sephsplace'], false, (err) => {
if (err) {
console.error('Could not create topic')
throw err
}
server.listen(port, () => {
console.log('listening on port', port)
})
})
})