-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathswarmserver.js
75 lines (67 loc) · 2.17 KB
/
swarmserver.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
import SwarmBase from 'swarm/lib/NodeServer'
import swarmFactory from './swarmfactory'
import Spec from 'swarm/lib/Spec'
import redis from 'redis'
import RedisStorage from '../vendor/swarm/RedisStorage'
export default class SwarmServer {
constructor(redisConfig) {
let Swarm = swarmFactory(SwarmBase)
this.Swarm = Swarm
//let storage = new Swarm.FileStorage('.swarm')
let storage = new RedisStorage({
redis: redis,
redisConnectParams: redisConfig,
debug: false
})
storage.open()
Swarm.host = new Swarm.Host('swarm~nodejs', 0, storage)
Swarm.env.localhost = Swarm.host
setInterval(() => {
this.cleanCursorSets()
}, 5000)
}
cleanCursorSet(cursorSet) {
let online = {}
let Swarm = this.Swarm
for (let src in Swarm.host.sources) {
if(!Swarm.host.sources.hasOwnProperty(src)) continue
let m = src.match(/([A-Za-z0-9_\~]+)(\~[A-Za-z0-9_\~]+)/)
if (!m) {
console.error('Unknown Swarm source', src)
continue
}
online[m[1]] = true
}
if (!cursorSet._version) {
return
}
let cursorSetMoribund = {}
let cursors = cursorSet.list()
//console.log('cursors', cursors.reduce((arr, c) => { arr.push({_id: c._id, name: c.name, state: c.state, ms: c.ms}); return arr }, []))
for (let s of cursors) {
let spec = s.spec()
if (spec.type() !== 'Cursor') {
continue
}
let id = spec.id()
cursorSetMoribund[id] = s.ms
}
//console.log('cursorSet:', cursorSet._id, 'cursors:', cursorSetMoribund)
// cursors live for 10 minutes after last use and then disappear (recreated by client if user resumes editing)
let ancient = Date.now() - 10 * 60 * 1000
for (let id in cursorSetMoribund) {
if(!cursorSetMoribund.hasOwnProperty(id)) continue
let ts = cursorSetMoribund[id]
if (ts < ancient) {
cursorSet.removeObject('/Cursor#' + id)
delete cursorSetMoribund[id]
}
}
}
cleanCursorSets() {
let Swarm = this.Swarm
Object.keys(Swarm.host.objects).map(s => new Spec(s)).filter(s => s.type() === 'CursorSet').forEach(s => {
this.cleanCursorSet(Swarm.host.get(s))
})
}
}