-
Notifications
You must be signed in to change notification settings - Fork 30
/
Channel.coffee
259 lines (189 loc) · 7.79 KB
/
Channel.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
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
# Channel
{EventEmitter} = require('events')
debug = require('./config').debug('amqp:Channel')
async = require('async')
_ = require('underscore')
defaults = require('./defaults')
{ methodTable, classes, methods } = require('./config').protocol
# we track this to avoid node's max stack size with a saturated async queue
OVERFLOW_PROTECTION = 0
class Channel extends EventEmitter
constructor: (connection, channel)->
@channel = channel
@connection = connection
@state = 'closed'
@waitingCallbacks = {} # channel operations
@queue = async.queue(@_taskWorker, 1)
@open()
@transactional = false
temporaryChannel: ()->
@transactional = true # THIS IS NOT AMQP TRANSACTIONS
@lastChannelAccess = Date.now()
if process.env.AMQP_TEST?
@connection.connectionOptions.temporaryChannelTimeout = 200
@connection.connectionOptions.temporaryChannelTimeoutCheck = 100
if !@channelTracker?
@channelTracker = setInterval ()=>
if @lastChannelAccess < (Date.now() - @connection.connectionOptions.temporaryChannelTimeout)
debug 4, ()->return "Closing channel due to inactivity"
@close(true)
, @connection.connectionOptions.temporaryChannelTimeoutCheck
open: (cb)->
if @state is "closed"
@state = 'opening'
@waitForMethod(methods.channelOpenOk, cb) if cb?
@connection._sendMethod(@channel, methods.channelOpen, {})
@connection.channelCount++
if @transactional then @temporaryChannel()
else
cb("state isn't closed. not opening channel") if cb?
reset: (cb)=>
@_callOutstandingCallbacks("Channel Opening or Reseting") if @state isnt 'open'
# if our state is closed and either we arn't a transactional channel (queue, exchange declare etc..)
# or we're within our acceptable time window for this queue
if @state is 'closed' and (!@transactional or @listeners('open').length > 0 or (@transactional and @lastChannelAccess > (Date.now() - @connection.connectionOptions.temporaryChannelTimeout)))
debug 1, ()->return "State is closed... reconnecting"
async.series [
(next)=>
@open(next)
(next)=>
@_onChannelReconnect(next)
], cb
else
cb() if cb?
crash: (cb)=>
if !process.env.AMQP_TEST?
cb?()
return true
# this will crash a channel forcing a channelOpen from the server
# this is really only for testing
debug "Trying to crash channel"
@connection._sendMethod @channel, methods.queuePurge, {queue:"idontexist"}
@waitForMethod(methods.channelClose, cb) if cb?
close: (auto)=>
if !auto? or !auto then debug 1, ()->return "User requested channel close"
clearInterval(@channelTracker)
@channelTracker = null
if @state is 'open'
@connection.channelCount--
@state = 'closed'
@connection._sendMethod @channel, methods.channelClose, {
replyText : 'Goodbye'
replyCode : 200
classId : 0
methodId : 0
}
waitForMethod: (method, cb)->
@waitingCallbacks[method.name] = [] if !@waitingCallbacks[method]?
@waitingCallbacks[method.name].push cb
callbackForMethod: (method)->
if !method? or !@waitingCallbacks[method.name]?
return ()-> return true
cb = @waitingCallbacks[method.name].shift()
if @waitingCallbacks[method.name].length is 0
delete @waitingCallbacks[method.name]
return cb
# Functions to overwrite
_channelOpen: ()->
debug 4, ()->return "channel open called and should be overwritten"
_channelClosed: ()->
debug 4, ()->return "channel closed called and should be overwritten"
_onChannelReconnect: (cb)->
debug 4, ()->return "channel reconnect called and should be overwritten"
cb()
_onMethod: (method, args)->
debug 3, ()->return "_onMethod MUST be overwritten by whoever extends Channel"
# TASK QUEUEING ---------------------------------------------------------
taskPush: ( method, args, okMethod, cb)=> # same as queueSendMethod
@queue.push {type: 'method', method, args, okMethod, cb}
taskPushPreflight: ( method, args, okMethod, preflight, cb)=>
@queue.push {type: 'method', method, args, okMethod, preflight, cb}
taskQueuePushRaw: (task, cb)=>
task.cb = cb if cb? and task?
@queue.push task
queueSendMethod: (method, args, okMethod, cb)=>
@queue.push {type: 'method', method, args, okMethod, cb}
queuePublish: (method, data, options)=>
@queue.push {type: 'publish', method, data, options}
_taskWorker: (task, done)=>
if @transactional then @lastChannelAccess = Date.now()
{type, method, okMethod, args, cb, data, options, preflight} = task
doneFn = (err, res)->
cb(err, res) if cb?
if OVERFLOW_PROTECTION > 100
OVERFLOW_PROTECTION = 0
_.defer done
else
OVERFLOW_PROTECTION++
done()
# if preflight is false do not proceed
if preflight? and !preflight()
return doneFn('preflight check failed')
if @state is 'closed' and @connection.state is 'open'
debug 1, ()->return "Channel reassign"
@connection.channelManager.channelReassign(@)
@open (e, r)=>
@_taskWorker(task, done)
else if @state isnt 'open'
# if our connection is closed that ok, but if its destroyed it will not reopen
if @connection.state is 'destroyed'
doneFn("Connection is destroyed")
else
if @connection.channelManager.isChannelClosed(@channel)
@connection.channelManager.channelReassign(@)
@once 'open', ()=>
@_taskWorker(task, done)
else
@waitForMethod(okMethod, doneFn) if okMethod?
if type is 'method'
@connection._sendMethod(@channel, method, args)
doneFn() if !okMethod?
else if type is 'publish'
@connection._sendMethod(@channel, method, options)
@connection._sendBody @channel, data, options, (err, res)->
doneFn() if !okMethod?
else
throw new Error("a task was queue with an unknown type of #{type}")
_callOutstandingCallbacks: (message)=>
outStandingCallbacks = @waitingCallbacks
@waitingCallbacks = {}
if !message? then message = "Channel Unavaliable"
for key, cbs of outStandingCallbacks
for cb in cbs
cb?(message)
# incomming channel messages for us
_onChannelMethod: (channel, method, args )->
if @transactional then @lastChannelAccess = Date.now()
if channel isnt @channel
return debug 1, ()->return ["channel was sent to the wrong channel object", channel, @channel]
@callbackForMethod(method)(null, args)
switch method
when methods.channelCloseOk
@connection.channelManager.channelClosed(@channel)
@state = 'closed'
@_channelClosed("Channel closed")
@_callOutstandingCallbacks({msg: "Channel closed"})
when methods.channelClose
@connection.channelManager.channelClosed(channel)
debug 1, ()->return "Channel closed by server #{JSON.stringify args}"
@state = 'closed'
if args.classId? and args.methodId?
closingMethod = methodTable[args.classId][args.methodId].name
@callbackForMethod(methods["#{closingMethod}Ok"])(args) #this would be the error
@_channelClosed({msg: "Server closed channel", error: args})
@_callOutstandingCallbacks("Channel closed by server #{JSON.stringify args}")
when methods.channelOpenOk
@state = 'open'
@_channelOpen()
@emit 'open'
else
@_onMethod( channel, method, args )
_connectionClosed: ()->
# if the connection closes, make sure we reflect that because that channel is also closed
if @state isnt 'closed'
@state = 'closed'
@_channelClosed()
if @channelTracker?
clearInterval(@channelTracker)
@channelTracker = null
module.exports = Channel