/
jobs.coffee
98 lines (85 loc) · 3.4 KB
/
jobs.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
mongo = require 'mongodb'
path = require 'path'
db = new mongo.Db "concrete_#{path.basename(process.cwd()).replace(/\./, "-")}", new mongo.Server('localhost', mongo.Connection.DEFAULT_PORT, {auto_reconnect: true}), {}
db.open (error) ->
if error
console.log 'There was an error creating a connection with the Mongo database. Please check that MongoDB is properly installed and running.'.red
process.exit 1
ObjectID = mongo.BSONPure.ObjectID
jobs = module.exports =
current: null
addJob: (next)->
db.collection 'jobs', (error, collection) ->
job =
addedTime: new Date().getTime()
log: ''
running: no
finished: no
collection.insert job
next(job) if next?
getQueued: (next)->
getJobs {running: no}, next
getRunning: (next)->
getJobs {running: yes}, next
getAll: (next)->
getJobs null, next
getLast: (next)->
db.collection 'jobs', (error, collection) ->
collection.find().sort({$natural:-1}).limit(1).toArray (error, jobs) ->
if jobs.length > 0
next jobs[0]
else
next()
get: (id, next) ->
db.collection 'jobs', (error, collection) ->
collection.findOne {_id: new ObjectID id}, (error, job) ->
if job?
next job
else
next "No job found with the id '#{id}'"
clear: (next)->
db.dropCollection 'jobs', (error) ->
next() if next?
getLog: (id, next)->
db.collection 'jobs', (error, collection) ->
collection.findOne {_id: new ObjectID id}, (error, job) ->
if job?
next job.log
else
next "No job found with the id '#{id}'"
updateLog: (id, string, next)->
db.collection 'jobs', (error, collection) ->
collection.findOne {_id: new ObjectID id}, (error, job) ->
console.log "update log for job #{job}, #{string}"
return no if not job?
job.log += "#{string} <br />"
collection.save(job)
next() if next?
currentComplete: (success, next)->
db.collection 'jobs', (error, collection) ->
collection.findOne {_id: new ObjectID jobs.current}, (error, job) ->
return no if not job?
job.running = no
job.finished = yes
job.failed = not success
job.finishedTime = new Date().getTime()
jobs.current = null
collection.save(job)
next()
next: (next)->
db.collection 'jobs', (error, collection) ->
collection.findOne {running: no, finished: no}, (error, job) ->
return no if not job?
job.running = yes
job.startedTime = new Date().getTime()
jobs.current = job._id.toString()
collection.save(job)
next()
getJobs = (filter, next)->
db.collection 'jobs', (error, collection) ->
if filter?
collection.find(filter).sort({addedTime: 1}).toArray (error, results) ->
next results
else
collection.find().sort({addedTime: 1}).toArray (error, results) ->
next results