taskpace 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of taskpace might be problematic. Click here for more details.

Files changed (99) hide show
  1. package/.babelrc.es5 +5 -0
  2. package/.babelrc.lib +9 -0
  3. package/.env +2 -0
  4. package/.travis.yml +25 -0
  5. package/LICENSE +20 -0
  6. package/README.md +474 -2
  7. package/bower.json +30 -0
  8. package/es5.js +5064 -0
  9. package/lib/Batcher.js +1 -0
  10. package/lib/DLList.js +1 -0
  11. package/lib/Events.js +1 -0
  12. package/lib/Group.js +1 -0
  13. package/lib/IORedisConnection.js +1 -0
  14. package/lib/Job.js +1 -0
  15. package/lib/LocalDatastore.js +1 -0
  16. package/lib/Queues.js +1 -0
  17. package/lib/RedisConnection.js +1 -0
  18. package/lib/RedisDatastore.js +1 -0
  19. package/lib/Scripts.js +1 -0
  20. package/lib/States.js +1 -0
  21. package/lib/Sync.js +1 -0
  22. package/lib/Taskpace.js +1 -0
  23. package/lib/TaskpaceError.js +1 -0
  24. package/lib/common.js +1 -0
  25. package/lib/es5.js +1 -0
  26. package/lib/index.js +1 -0
  27. package/lib/limit.js +1 -0
  28. package/lib/lua.json +24 -0
  29. package/lib/parser.js +1 -0
  30. package/lib/redis.js +1 -0
  31. package/lib/validate.js +1 -0
  32. package/lib/version.json +1 -0
  33. package/light.js +1524 -0
  34. package/package.json +53 -4
  35. package/rollup.config.es5.js +34 -0
  36. package/rollup.config.light.js +44 -0
  37. package/scripts/assemble_lua.js +25 -0
  38. package/scripts/build.sh +81 -0
  39. package/scripts/test_all.sh +20 -0
  40. package/scripts/version.js +3 -0
  41. package/src/Batcher.coffee +39 -0
  42. package/src/DLList.coffee +38 -0
  43. package/src/Events.coffee +38 -0
  44. package/src/Group.coffee +80 -0
  45. package/src/IORedisConnection.coffee +84 -0
  46. package/src/Job.coffee +98 -0
  47. package/src/LocalDatastore.coffee +140 -0
  48. package/src/Queues.coffee +28 -0
  49. package/src/RedisConnection.coffee +91 -0
  50. package/src/RedisDatastore.coffee +158 -0
  51. package/src/Scripts.coffee +151 -0
  52. package/src/States.coffee +43 -0
  53. package/src/Sync.coffee +28 -0
  54. package/src/Taskpace.coffee +298 -0
  55. package/src/TaskpaceError.coffee +3 -0
  56. package/src/es5.coffee +3 -0
  57. package/src/index.coffee +1 -0
  58. package/src/parser.coffee +10 -0
  59. package/src/redis/blacklist_client.lua +8 -0
  60. package/src/redis/check.lua +6 -0
  61. package/src/redis/conditions_check.lua +3 -0
  62. package/src/redis/current_reservoir.lua +1 -0
  63. package/src/redis/done.lua +3 -0
  64. package/src/redis/free.lua +5 -0
  65. package/src/redis/get_time.lua +7 -0
  66. package/src/redis/group_check.lua +1 -0
  67. package/src/redis/heartbeat.lua +1 -0
  68. package/src/redis/increment_reservoir.lua +10 -0
  69. package/src/redis/init.lua +105 -0
  70. package/src/redis/process_tick.lua +214 -0
  71. package/src/redis/queued.lua +10 -0
  72. package/src/redis/refresh_expiration.lua +11 -0
  73. package/src/redis/refs.lua +13 -0
  74. package/src/redis/register.lua +51 -0
  75. package/src/redis/register_client.lua +12 -0
  76. package/src/redis/running.lua +1 -0
  77. package/src/redis/submit.lua +74 -0
  78. package/src/redis/update_settings.lua +14 -0
  79. package/src/redis/validate_client.lua +5 -0
  80. package/src/redis/validate_keys.lua +3 -0
  81. package/taskpace.d.ts +629 -0
  82. package/taskpace.d.ts.ejs +588 -0
  83. package/test/DLList.js +148 -0
  84. package/test/batcher.js +209 -0
  85. package/test/cluster.js +1549 -0
  86. package/test/context.js +142 -0
  87. package/test/general.js +867 -0
  88. package/test/group.js +255 -0
  89. package/test/ioredis.js +135 -0
  90. package/test/node_redis.js +100 -0
  91. package/test/priority.js +184 -0
  92. package/test/promises.js +202 -0
  93. package/test/retries.js +237 -0
  94. package/test/spawn/increaseKeepAlive.js +17 -0
  95. package/test/spawn/refreshKeepAlive.js +17 -0
  96. package/test/states.js +103 -0
  97. package/test/stop.js +208 -0
  98. package/test/taskpace.js +7 -0
  99. package/test.ts +335 -0
@@ -0,0 +1,140 @@
1
+ parser = require "./parser"
2
+ TaskpaceError = require "./TaskpaceError"
3
+
4
+ class LocalDatastore
5
+ constructor: (@instance, @storeOptions, storeInstanceOptions) ->
6
+ @clientId = @instance._randomIndex()
7
+ parser.load storeInstanceOptions, storeInstanceOptions, @
8
+ @_nextRequest = @_lastReservoirRefresh = @_lastReservoirIncrease = Date.now()
9
+ @_running = 0
10
+ @_done = 0
11
+ @_unblockTime = 0
12
+ @ready = @Promise.resolve()
13
+ @clients = {}
14
+ @_startHeartbeat()
15
+
16
+ _startHeartbeat: ->
17
+ if !@heartbeat? and ((
18
+ @storeOptions.reservoirRefreshInterval? and @storeOptions.reservoirRefreshAmount?
19
+ ) or (
20
+ @storeOptions.reservoirIncreaseInterval? and @storeOptions.reservoirIncreaseAmount?
21
+ ))
22
+ (@heartbeat = setInterval =>
23
+ now = Date.now()
24
+
25
+ if @storeOptions.reservoirRefreshInterval? and now >= @_lastReservoirRefresh + @storeOptions.reservoirRefreshInterval
26
+ @_lastReservoirRefresh = now
27
+ @storeOptions.reservoir = @storeOptions.reservoirRefreshAmount
28
+ @instance._drainAll @computeCapacity()
29
+
30
+ if @storeOptions.reservoirIncreaseInterval? and now >= @_lastReservoirIncrease + @storeOptions.reservoirIncreaseInterval
31
+ { reservoirIncreaseAmount: amount, reservoirIncreaseMaximum: maximum, reservoir } = @storeOptions
32
+ @_lastReservoirIncrease = now
33
+ incr = if maximum? then Math.min amount, maximum - reservoir else amount
34
+ if incr > 0
35
+ @storeOptions.reservoir += incr
36
+ @instance._drainAll @computeCapacity()
37
+
38
+ , @heartbeatInterval).unref?()
39
+ else clearInterval @heartbeat
40
+
41
+ __publish__: (message) ->
42
+ await @yieldLoop()
43
+ @instance.Events.trigger "message", message.toString()
44
+
45
+ __disconnect__: (flush) ->
46
+ await @yieldLoop()
47
+ clearInterval @heartbeat
48
+ @Promise.resolve()
49
+
50
+ yieldLoop: (t=0) -> new @Promise (resolve, reject) -> setTimeout resolve, t
51
+
52
+ computePenalty: -> @storeOptions.penalty ? ((15 * @storeOptions.minTime) or 5000)
53
+
54
+ __updateSettings__: (options) ->
55
+ await @yieldLoop()
56
+ parser.overwrite options, options, @storeOptions
57
+ @_startHeartbeat()
58
+ @instance._drainAll @computeCapacity()
59
+ true
60
+
61
+ __running__: ->
62
+ await @yieldLoop()
63
+ @_running
64
+
65
+ __queued__: ->
66
+ await @yieldLoop()
67
+ @instance.queued()
68
+
69
+ __done__: ->
70
+ await @yieldLoop()
71
+ @_done
72
+
73
+ __groupCheck__: (time) ->
74
+ await @yieldLoop()
75
+ (@_nextRequest + @timeout) < time
76
+
77
+ computeCapacity: ->
78
+ { maxConcurrent, reservoir } = @storeOptions
79
+ if maxConcurrent? and reservoir? then Math.min((maxConcurrent - @_running), reservoir)
80
+ else if maxConcurrent? then maxConcurrent - @_running
81
+ else if reservoir? then reservoir
82
+ else null
83
+
84
+ conditionsCheck: (weight) ->
85
+ capacity = @computeCapacity()
86
+ not capacity? or weight <= capacity
87
+
88
+ __incrementReservoir__: (incr) ->
89
+ await @yieldLoop()
90
+ reservoir = @storeOptions.reservoir += incr
91
+ @instance._drainAll @computeCapacity()
92
+ reservoir
93
+
94
+ __currentReservoir__: ->
95
+ await @yieldLoop()
96
+ @storeOptions.reservoir
97
+
98
+ isBlocked: (now) -> @_unblockTime >= now
99
+
100
+ check: (weight, now) -> @conditionsCheck(weight) and (@_nextRequest - now) <= 0
101
+
102
+ __check__: (weight) ->
103
+ await @yieldLoop()
104
+ now = Date.now()
105
+ @check weight, now
106
+
107
+ __register__: (index, weight, expiration) ->
108
+ await @yieldLoop()
109
+ now = Date.now()
110
+ if @conditionsCheck weight
111
+ @_running += weight
112
+ if @storeOptions.reservoir? then @storeOptions.reservoir -= weight
113
+ wait = Math.max @_nextRequest - now, 0
114
+ @_nextRequest = now + wait + @storeOptions.minTime
115
+ { success: true, wait, reservoir: @storeOptions.reservoir }
116
+ else { success: false }
117
+
118
+ strategyIsBlock: -> @storeOptions.strategy == 3
119
+
120
+ __submit__: (queueLength, weight) ->
121
+ await @yieldLoop()
122
+ if @storeOptions.maxConcurrent? and weight > @storeOptions.maxConcurrent
123
+ throw new TaskpaceError("Impossible to add a job having a weight of #{weight} to a limiter having a maxConcurrent setting of #{@storeOptions.maxConcurrent}")
124
+ now = Date.now()
125
+ reachedHWM = @storeOptions.highWater? and queueLength == @storeOptions.highWater and not @check(weight, now)
126
+ blocked = @strategyIsBlock() and (reachedHWM or @isBlocked now)
127
+ if blocked
128
+ @_unblockTime = now + @computePenalty()
129
+ @_nextRequest = @_unblockTime + @storeOptions.minTime
130
+ @instance._dropAllQueued()
131
+ { reachedHWM, blocked, strategy: @storeOptions.strategy }
132
+
133
+ __free__: (index, weight) ->
134
+ await @yieldLoop()
135
+ @_running -= weight
136
+ @_done += weight
137
+ @instance._drainAll @computeCapacity()
138
+ { running: @_running }
139
+
140
+ module.exports = LocalDatastore
@@ -0,0 +1,28 @@
1
+ DLList = require "./DLList"
2
+ Events = require "./Events"
3
+
4
+ class Queues
5
+
6
+ constructor: (num_priorities) ->
7
+ @Events = new Events @
8
+ @_length = 0
9
+ @_lists = for i in [1..num_priorities] then new DLList (=> @incr()), (=> @decr())
10
+
11
+ incr: -> if @_length++ == 0 then @Events.trigger "leftzero"
12
+
13
+ decr: -> if --@_length == 0 then @Events.trigger "zero"
14
+
15
+ push: (job) -> @_lists[job.options.priority].push job
16
+
17
+ queued: (priority) -> if priority? then @_lists[priority].length else @_length
18
+
19
+ shiftAll: (fn) -> @_lists.forEach (list) -> list.forEachShift fn
20
+
21
+ getFirst: (arr=@_lists) ->
22
+ for list in arr
23
+ return list if list.length > 0
24
+ []
25
+
26
+ shiftLastFrom: (priority) -> @getFirst(@_lists[priority..].reverse()).shift()
27
+
28
+ module.exports = Queues
@@ -0,0 +1,91 @@
1
+ parser = require "./parser"
2
+ Events = require "./Events"
3
+ Scripts = require "./Scripts"
4
+
5
+ class RedisConnection
6
+ datastore: "redis"
7
+ defaults:
8
+ Redis: null
9
+ clientOptions: {}
10
+ client: null
11
+ Promise: Promise
12
+ Events: null
13
+
14
+ constructor: (options={}) ->
15
+ parser.load options, @defaults, @
16
+ @Redis ?= eval("require")("redis") # Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Taskpace as the 'Redis' option.
17
+ @Events ?= new Events @
18
+ @terminated = false
19
+
20
+ @client ?= @Redis.createClient @clientOptions
21
+ @subscriber = @client.duplicate()
22
+ @limiters = {}
23
+ @shas = {}
24
+
25
+ @ready = @Promise.all [@_setup(@client, false), @_setup(@subscriber, true)]
26
+ .then => @_loadScripts()
27
+ .then => { @client, @subscriber }
28
+
29
+ _setup: (client, sub) ->
30
+ client.setMaxListeners 0
31
+ new @Promise (resolve, reject) =>
32
+ client.on "error", (e) => @Events.trigger "error", e
33
+ if sub
34
+ client.on "message", (channel, message) =>
35
+ @limiters[channel]?._store.onMessage channel, message
36
+ if client.ready then resolve()
37
+ else client.once "ready", resolve
38
+
39
+ _loadScript: (name) ->
40
+ new @Promise (resolve, reject) =>
41
+ payload = Scripts.payload name
42
+ @client.multi([["script", "load", payload]]).exec (err, replies) =>
43
+ if err? then return reject err
44
+ @shas[name] = replies[0]
45
+ resolve replies[0]
46
+
47
+ _loadScripts: -> @Promise.all(Scripts.names.map (k) => @_loadScript k)
48
+
49
+ __runCommand__: (cmd) ->
50
+ await @ready
51
+ new @Promise (resolve, reject) =>
52
+ @client.multi([cmd]).exec_atomic (err, replies) ->
53
+ if err? then reject(err) else resolve(replies[0])
54
+
55
+ __addLimiter__: (instance) ->
56
+ @Promise.all [instance.channel(), instance.channel_client()].map (channel) =>
57
+ new @Promise (resolve, reject) =>
58
+ handler = (chan) =>
59
+ if chan == channel
60
+ @subscriber.removeListener "subscribe", handler
61
+ @limiters[channel] = instance
62
+ resolve()
63
+ @subscriber.on "subscribe", handler
64
+ @subscriber.subscribe channel
65
+
66
+ __removeLimiter__: (instance) ->
67
+ @Promise.all [instance.channel(), instance.channel_client()].map (channel) =>
68
+ unless @terminated
69
+ await new @Promise (resolve, reject) =>
70
+ @subscriber.unsubscribe channel, (err, chan) ->
71
+ if err? then return reject err
72
+ if chan == channel then return resolve()
73
+ delete @limiters[channel]
74
+
75
+ __scriptArgs__: (name, id, args, cb) ->
76
+ keys = Scripts.keys name, id
77
+ [@shas[name], keys.length].concat keys, args, cb
78
+
79
+ __scriptFn__: (name) ->
80
+ @client.evalsha.bind(@client)
81
+
82
+ disconnect: (flush=true) ->
83
+ clearInterval(@limiters[k]._store.heartbeat) for k in Object.keys @limiters
84
+ @limiters = {}
85
+ @terminated = true
86
+
87
+ @client.end flush
88
+ @subscriber.end flush
89
+ @Promise.resolve()
90
+
91
+ module.exports = RedisConnection
@@ -0,0 +1,158 @@
1
+ parser = require "./parser"
2
+ TaskpaceError = require "./TaskpaceError"
3
+ RedisConnection = require "./RedisConnection"
4
+ IORedisConnection = require "./IORedisConnection"
5
+
6
+ class RedisDatastore
7
+ constructor: (@instance, @storeOptions, storeInstanceOptions) ->
8
+ @originalId = @instance.id
9
+ @clientId = @instance._randomIndex()
10
+ parser.load storeInstanceOptions, storeInstanceOptions, @
11
+ @clients = {}
12
+ @capacityPriorityCounters = {}
13
+ @sharedConnection = @connection?
14
+
15
+ @connection ?= if @instance.datastore == "redis" then new RedisConnection { @Redis, @clientOptions, @Promise, Events: @instance.Events }
16
+ else if @instance.datastore == "ioredis" then new IORedisConnection { @Redis, @clientOptions, @clusterNodes, @Promise, Events: @instance.Events }
17
+
18
+ @instance.connection = @connection
19
+ @instance.datastore = @connection.datastore
20
+
21
+ @ready = @connection.ready
22
+ .then (@clients) => @runScript "init", @prepareInitSettings @clearDatastore
23
+ .then => @connection.__addLimiter__ @instance
24
+ .then => @runScript "register_client", [@instance.queued()]
25
+ .then =>
26
+ (@heartbeat = setInterval =>
27
+ @runScript "heartbeat", []
28
+ .catch (e) => @instance.Events.trigger "error", e
29
+ , @heartbeatInterval).unref?()
30
+ @clients
31
+
32
+ __publish__: (message) ->
33
+ { client } = await @ready
34
+ client.publish(@instance.channel(), "message:#{message.toString()}")
35
+
36
+ onMessage: (channel, message) ->
37
+ try
38
+ pos = message.indexOf(":")
39
+ [type, data] = [message.slice(0, pos), message.slice(pos+1)]
40
+ if type == "capacity"
41
+ await @instance._drainAll(if data.length > 0 then ~~data)
42
+ else if type == "capacity-priority"
43
+ [rawCapacity, priorityClient, counter] = data.split(":")
44
+ capacity = if rawCapacity.length > 0 then ~~rawCapacity
45
+ if priorityClient == @clientId
46
+ drained = await @instance._drainAll(capacity)
47
+ newCapacity = if capacity? then capacity - (drained or 0) else ""
48
+ await @clients.client.publish(@instance.channel(), "capacity-priority:#{newCapacity}::#{counter}")
49
+ else if priorityClient == ""
50
+ clearTimeout @capacityPriorityCounters[counter]
51
+ delete @capacityPriorityCounters[counter]
52
+ @instance._drainAll(capacity)
53
+ else
54
+ @capacityPriorityCounters[counter] = setTimeout =>
55
+ try
56
+ delete @capacityPriorityCounters[counter]
57
+ await @runScript "blacklist_client", [priorityClient]
58
+ await @instance._drainAll(capacity)
59
+ catch e then @instance.Events.trigger "error", e
60
+ , 1000
61
+ else if type == "message"
62
+ @instance.Events.trigger "message", data
63
+ else if type == "blocked"
64
+ await @instance._dropAllQueued()
65
+ catch e then @instance.Events.trigger "error", e
66
+
67
+ __disconnect__: (flush) ->
68
+ clearInterval @heartbeat
69
+ if @sharedConnection
70
+ @connection.__removeLimiter__ @instance
71
+ else
72
+ @connection.disconnect flush
73
+
74
+ runScript: (name, args) ->
75
+ await @ready unless name == "init" or name == "register_client"
76
+ new @Promise (resolve, reject) =>
77
+ all_args = [Date.now(), @clientId].concat args
78
+ @instance.Events.trigger "debug", "Calling Redis script: #{name}.lua", all_args
79
+ arr = @connection.__scriptArgs__ name, @originalId, all_args, (err, replies) ->
80
+ if err? then return reject err
81
+ return resolve replies
82
+ @connection.__scriptFn__(name) arr...
83
+ .catch (e) =>
84
+ if e.message == "SETTINGS_KEY_NOT_FOUND"
85
+ if name == "heartbeat" then @Promise.resolve()
86
+ else
87
+ @runScript("init", @prepareInitSettings(false))
88
+ .then => @runScript(name, args)
89
+ else if e.message == "UNKNOWN_CLIENT"
90
+ @runScript("register_client", [@instance.queued()])
91
+ .then => @runScript(name, args)
92
+ else @Promise.reject e
93
+
94
+ prepareArray: (arr) -> (if x? then x.toString() else "") for x in arr
95
+
96
+ prepareObject: (obj) ->
97
+ arr = []
98
+ for k, v of obj then arr.push k, (if v? then v.toString() else "")
99
+ arr
100
+
101
+ prepareInitSettings: (clear) ->
102
+ args = @prepareObject Object.assign({}, @storeOptions, {
103
+ id: @originalId
104
+ version: @instance.version
105
+ groupTimeout: @timeout
106
+ @clientTimeout
107
+ })
108
+ args.unshift (if clear then 1 else 0), @instance.version
109
+ args
110
+
111
+ convertBool: (b) -> !!b
112
+
113
+ __updateSettings__: (options) ->
114
+ await @runScript "update_settings", @prepareObject options
115
+ parser.overwrite options, options, @storeOptions
116
+
117
+ __running__: -> @runScript "running", []
118
+
119
+ __queued__: -> @runScript "queued", []
120
+
121
+ __done__: -> @runScript "done", []
122
+
123
+ __groupCheck__: -> @convertBool await @runScript "group_check", []
124
+
125
+ __incrementReservoir__: (incr) -> @runScript "increment_reservoir", [incr]
126
+
127
+ __currentReservoir__: -> @runScript "current_reservoir", []
128
+
129
+ __check__: (weight) -> @convertBool await @runScript "check", @prepareArray [weight]
130
+
131
+ __register__: (index, weight, expiration) ->
132
+ [success, wait, reservoir] = await @runScript "register", @prepareArray [index, weight, expiration]
133
+ return {
134
+ success: @convertBool(success),
135
+ wait,
136
+ reservoir
137
+ }
138
+
139
+ __submit__: (queueLength, weight) ->
140
+ try
141
+ [reachedHWM, blocked, strategy] = await @runScript "submit", @prepareArray [queueLength, weight]
142
+ return {
143
+ reachedHWM: @convertBool(reachedHWM),
144
+ blocked: @convertBool(blocked),
145
+ strategy
146
+ }
147
+ catch e
148
+ if e.message.indexOf("OVERWEIGHT") == 0
149
+ [overweight, weight, maxConcurrent] = e.message.split ":"
150
+ throw new TaskpaceError("Impossible to add a job having a weight of #{weight} to a limiter having a maxConcurrent setting of #{maxConcurrent}")
151
+ else
152
+ throw e
153
+
154
+ __free__: (index, weight) ->
155
+ running = await @runScript "free", @prepareArray [index]
156
+ return { running }
157
+
158
+ module.exports = RedisDatastore
@@ -0,0 +1,151 @@
1
+ lua = require "./lua.json"
2
+
3
+ headers =
4
+ refs: lua["refs.lua"]
5
+ validate_keys: lua["validate_keys.lua"]
6
+ validate_client: lua["validate_client.lua"]
7
+ refresh_expiration: lua["refresh_expiration.lua"]
8
+ process_tick: lua["process_tick.lua"]
9
+ conditions_check: lua["conditions_check.lua"]
10
+ get_time: lua["get_time.lua"]
11
+
12
+ exports.allKeys = (id) -> [
13
+ ###
14
+ HASH
15
+ ###
16
+ "b_#{id}_settings"
17
+
18
+ ###
19
+ HASH
20
+ job index -> weight
21
+ ###
22
+ "b_#{id}_job_weights"
23
+
24
+ ###
25
+ ZSET
26
+ job index -> expiration
27
+ ###
28
+ "b_#{id}_job_expirations"
29
+
30
+ ###
31
+ HASH
32
+ job index -> client
33
+ ###
34
+ "b_#{id}_job_clients"
35
+
36
+ ###
37
+ ZSET
38
+ client -> sum running
39
+ ###
40
+ "b_#{id}_client_running"
41
+
42
+ ###
43
+ HASH
44
+ client -> num queued
45
+ ###
46
+ "b_#{id}_client_num_queued"
47
+
48
+ ###
49
+ ZSET
50
+ client -> last job registered
51
+ ###
52
+ "b_#{id}_client_last_registered"
53
+
54
+ ###
55
+ ZSET
56
+ client -> last seen
57
+ ###
58
+ "b_#{id}_client_last_seen"
59
+ ]
60
+
61
+ templates =
62
+ init:
63
+ keys: exports.allKeys
64
+ headers: ["process_tick"]
65
+ refresh_expiration: true
66
+ code: lua["init.lua"]
67
+ group_check:
68
+ keys: exports.allKeys
69
+ headers: []
70
+ refresh_expiration: false
71
+ code: lua["group_check.lua"]
72
+ register_client:
73
+ keys: exports.allKeys
74
+ headers: ["validate_keys"]
75
+ refresh_expiration: false
76
+ code: lua["register_client.lua"]
77
+ blacklist_client:
78
+ keys: exports.allKeys
79
+ headers: ["validate_keys", "validate_client"]
80
+ refresh_expiration: false
81
+ code: lua["blacklist_client.lua"]
82
+ heartbeat:
83
+ keys: exports.allKeys
84
+ headers: ["validate_keys", "validate_client", "process_tick"]
85
+ refresh_expiration: false
86
+ code: lua["heartbeat.lua"]
87
+ update_settings:
88
+ keys: exports.allKeys
89
+ headers: ["validate_keys", "validate_client", "process_tick"]
90
+ refresh_expiration: true
91
+ code: lua["update_settings.lua"]
92
+ running:
93
+ keys: exports.allKeys
94
+ headers: ["validate_keys", "validate_client", "process_tick"]
95
+ refresh_expiration: false
96
+ code: lua["running.lua"]
97
+ queued:
98
+ keys: exports.allKeys
99
+ headers: ["validate_keys", "validate_client"]
100
+ refresh_expiration: false
101
+ code: lua["queued.lua"]
102
+ done:
103
+ keys: exports.allKeys
104
+ headers: ["validate_keys", "validate_client", "process_tick"]
105
+ refresh_expiration: false
106
+ code: lua["done.lua"]
107
+ check:
108
+ keys: exports.allKeys
109
+ headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"]
110
+ refresh_expiration: false
111
+ code: lua["check.lua"]
112
+ submit:
113
+ keys: exports.allKeys
114
+ headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"]
115
+ refresh_expiration: true
116
+ code: lua["submit.lua"]
117
+ register:
118
+ keys: exports.allKeys
119
+ headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"]
120
+ refresh_expiration: true
121
+ code: lua["register.lua"]
122
+ free:
123
+ keys: exports.allKeys
124
+ headers: ["validate_keys", "validate_client", "process_tick"]
125
+ refresh_expiration: true
126
+ code: lua["free.lua"]
127
+ current_reservoir:
128
+ keys: exports.allKeys
129
+ headers: ["validate_keys", "validate_client", "process_tick"]
130
+ refresh_expiration: false
131
+ code: lua["current_reservoir.lua"]
132
+ increment_reservoir:
133
+ keys: exports.allKeys
134
+ headers: ["validate_keys", "validate_client", "process_tick"]
135
+ refresh_expiration: true
136
+ code: lua["increment_reservoir.lua"]
137
+
138
+ exports.names = Object.keys templates
139
+
140
+ exports.keys = (name, id) ->
141
+ templates[name].keys id
142
+
143
+ exports.payload = (name) ->
144
+ template = templates[name]
145
+ Array::concat(
146
+ headers.refs,
147
+ template.headers.map((h) -> headers[h]),
148
+ (if template.refresh_expiration then headers.refresh_expiration else ""),
149
+ template.code
150
+ )
151
+ .join("\n")
@@ -0,0 +1,43 @@
1
+ TaskpaceError = require "./TaskpaceError"
2
+ class States
3
+ constructor: (@status) ->
4
+ @_jobs = {}
5
+ @counts = @status.map(-> 0)
6
+
7
+ next: (id) ->
8
+ current = @_jobs[id]
9
+ next = current + 1
10
+ if current? and next < @status.length
11
+ @counts[current]--
12
+ @counts[next]++
13
+ @_jobs[id]++
14
+ else if current?
15
+ @counts[current]--
16
+ delete @_jobs[id]
17
+
18
+ start: (id) ->
19
+ initial = 0
20
+ @_jobs[id] = initial
21
+ @counts[initial]++
22
+
23
+ remove: (id) ->
24
+ current = @_jobs[id]
25
+ if current?
26
+ @counts[current]--
27
+ delete @_jobs[id]
28
+ current?
29
+
30
+ jobStatus: (id) -> @status[@_jobs[id]] ? null
31
+
32
+ statusJobs: (status) ->
33
+ if status?
34
+ pos = @status.indexOf status
35
+ if pos < 0
36
+ throw new TaskpaceError "status must be one of #{@status.join ', '}"
37
+ k for k,v of @_jobs when v == pos
38
+ else
39
+ Object.keys @_jobs
40
+
41
+ statusCounts: -> @counts.reduce(((acc, v, i) => acc[@status[i]] = v; acc), {})
42
+
43
+ module.exports = States
@@ -0,0 +1,28 @@
1
+ DLList = require "./DLList"
2
+ class Sync
3
+ constructor: (@name, @Promise) ->
4
+ @_running = 0
5
+ @_queue = new DLList()
6
+ isEmpty: -> @_queue.length == 0
7
+ _tryToRun: ->
8
+ if (@_running < 1) and @_queue.length > 0
9
+ @_running++
10
+ { task, args, resolve, reject } = @_queue.shift()
11
+ cb = try
12
+ returned = await task args...
13
+ () -> resolve returned
14
+ catch error
15
+ () -> reject error
16
+ @_running--
17
+ @_tryToRun()
18
+ cb()
19
+ schedule: (task, args...) =>
20
+ resolve = reject = null
21
+ promise = new @Promise (_resolve, _reject) ->
22
+ resolve = _resolve
23
+ reject = _reject
24
+ @_queue.push { task, args, resolve, reject }
25
+ @_tryToRun()
26
+ promise
27
+
28
+ module.exports = Sync