-
Notifications
You must be signed in to change notification settings - Fork 0
/
weasel.coffee
88 lines (68 loc) · 2.78 KB
/
weasel.coffee
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
http = require('http')
faye = require('faye')
fs = require('fs')
events = require('events')
DrowsyPersistence = require('./drowsy_persistence').DrowsyPersistence
argv = require('optimist')
.usage('Usage:\n\t$0 [-c config.json]')
.argv
if argv.c?
CONFIG = argv.c
else
CONFIG = './config.json'
class Weasel extends events.EventEmitter
setupLogging: () ->
@bayeux.bind 'handshake', (cid) ->
console.log "#{Date.now()} [handshk] #{cid}"
@bayeux.bind 'subscribe', (cid, channel) ->
console.log "#{Date.now()} [sub ] #{cid} #{channel}"
@bayeux.bind 'unsubscribe', (cid, channel) ->
console.log "#{Date.now()} [unsub ] #{cid} #{channel}"
@bayeux.bind 'publish', (cid, channel, data) ->
console.log "#{Date.now()} [pub ] #{cid} #{channel}", data
@bayeux.bind 'disconnect', (cid, channel, data) ->
console.log "#{Date.now()} [disconn] #{cid}"
@on 'persist_success', (cid, channel, data, res) ->
console.log "#{Date.now()} [drwsy.save] #{cid} #{channel} (#{res.statusCode})"
@on 'persist_failure', (cid, channel, data, res) ->
console.warn "#{Date.now()} [drwsy.fail] #{cid} #{channel} (#{res.statusCode})"
setupPersistence: ->
if @config.drowsy
drowsy = new DrowsyPersistence @config.drowsy
else
console.warn "Drowsy persistence will be disabled because no 'drowsy' config was provided!"
return
drowsy.on 'persist_success', (cid, channel, data, res) =>
@emit 'persist_success', cid, channel, data, res
drowsy.on 'persist_failure', (cid, channel, data, res) =>
@emit 'persist_failure', cid, channel, data, res
@bayeux.addExtension(drowsy);
loadConfig: ->
defaults =
port: 7777
mount: '/faye'
timeout: 30
configPath = CONFIG
if fs.existsSync(configPath)
config = JSON.parse fs.readFileSync(configPath)
for key,val of defaults
config[key] ?= defaults[key]
console.log "Configuration loaded from '#{CONFIG}':", config
else
config = defaults
console.warn "Configuration file '#{CONFIG}' not found! Using defaults:", config
@config = config
setupFaye: ->
@bayeux = new faye.NodeAdapter(mount: @config.mount, timeout: @config.timeout)
start: ->
server = http.createServer()
@bayeux.attach(server)
server.listen(@config.port)
console.log "... awake and listening on http://localhost:#{@config.port}#{@config.mount}"
console.log "Waking the Weasel..."
weasel = new Weasel()
weasel.loadConfig()
weasel.setupFaye()
weasel.setupLogging()
weasel.setupPersistence()
weasel.start()