/
base.rb
412 lines (300 loc) · 9.5 KB
/
base.rb
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#--
# Copyright (c) 2005-2012, John Mettraux, jmettraux@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# Made in Japan.
#++
require 'ostruct'
require 'ruote/util/time'
module Ruote
#
# Base methods for storage implementations.
#
module StorageBase
#--
# misc
#++
def context
@context ||= Ruote::Context.new(self)
end
def context=(c)
@context = c
end
# Attempts to delete a document, returns true if the deletion
# succeeded. This is used with msgs to reserve work on them.
#
def reserve(doc)
delete(doc).nil?
end
# Warning, this is not equivalent to doing @context.worker, this method
# fetches the worker from the local thread variables.
#
def worker
Ruote.current_worker
end
#--
# configurations
#++
def get_configuration(key)
get('configurations', key)
end
def replace_engine_configuration(options)
return if options.delete('preserve_configuration')
conf = get('configurations', 'engine')
doc = options.merge('type' => 'configurations', '_id' => 'engine')
doc['_rev'] = conf['_rev'] if conf
put(doc)
end
#--
# messages
#++
def put_msg(action, options)
msg = prepare_msg_doc(action, options)
put(msg)
end
def get_msgs
get_many('msgs', nil, :limit => 300).sort_by { |d| d['put_at'] }
end
def empty?(type)
(get_many(type, nil, :count => true) == 0)
end
#--
# expressions
#++
# Given a wfid, returns all the expressions of that process instance.
#
def find_expressions(wfid)
get_many('expressions', wfid)
end
# For a given wfid, returns all the expressions (array of Hash instances)
# that have a nil 'parent_id'.
#
def find_root_expressions(wfid)
find_expressions(wfid).select { |hexp| hexp['parent_id'].nil? }
end
# For a given wfid, fetches all the root expressions, sort by expid and
# return the first. Hopefully it's the right root_expression.
#
def find_root_expression(wfid)
find_root_expressions(wfid).sort_by { |hexp| hexp['fei']['expid'] }.first
end
# Given all the expressions stored here, returns a sorted list of unique
# wfids (this is used in Engine#processes(opts).
#
# Understands the :skip, :limit and :descending options.
#
# This is a base implementation, different storage implementations may
# come up with different implementations (think CouchDB, which could
# provide a view for it).
#
def expression_wfids(opts)
wfids = ids('expressions').collect { |fei| fei.split('!').last }.uniq.sort
wfids = wfids.reverse if opts[:descending]
skip = opts[:skip] || 0
limit = opts[:limit] || wfids.length
wfids[skip, limit]
end
#--
# trackers
#++
def get_trackers
get('variables', 'trackers') ||
{ '_id' => 'trackers', 'type' => 'variables', 'trackers' => {} }
end
#--
# ats and crons
#++
def get_schedules(delta, now)
# TODO : bring that 'optimization' back in,
# maybe every minute, if min != last_min ...
#if delta < 1.0
# at = now.strftime('%Y%m%d%H%M%S')
# get_many('schedules', /-#{at}$/)
#elsif delta < 60.0
# at = now.strftime('%Y%m%d%H%M')
# scheds = get_many('schedules', /-#{at}\d\d$/)
# filter_schedules(scheds, now)
#else # load all the schedules
scheds = get_many('schedules')
filter_schedules(scheds, now)
#end
end
# Places schedule in storage. Returns the id of the 'schedule' document.
# If the schedule got triggered immediately, nil is returned.
#
def put_schedule(flavour, owner_fei, s, msg)
doc = prepare_schedule_doc(flavour, owner_fei, s, msg)
return nil unless doc
r = put(doc)
raise "put_schedule failed" if r != nil
doc['_id']
end
def delete_schedule(schedule_id)
return if schedule_id.nil?
s = get('schedules', schedule_id)
delete(s) if s
end
#--
# engine variables
#++
def get_engine_variable(k)
get_engine_variables['variables'][k]
end
def put_engine_variable(k, v)
vars = get_engine_variables
vars['variables'][k] = v
put_engine_variable(k, v) unless put(vars).nil?
end
#--
# migrations
#++
# Copies the content of this storage into a target storage.
#
# Of course, the target storage may be a different implementation.
#
def copy_to(target, opts={})
counter = 0
%w[
configurations errors expressions msgs schedules variables workitems
].each do |type|
ids(type).each do |id|
item = get(type, id)
item.delete('_rev')
target.put(item)
counter += 1
puts(" #{type}/#{item['_id']}") if opts[:verbose]
end
end
counter
end
# Used when doing integration tests, removes all
# msgs, schedules, errors, expressions and workitems.
#
# NOTE that it doesn't remove engine variables (danger)
#
def clear
%w[ msgs schedules errors expressions workitems ].each do |type|
purge_type!(type)
end
end
# Removes a process by removing all its schedules, expressions, errors,
# workitems and trackers.
#
# Warning: will not trigger any cancel behaviours at all, just removes
# the process.
#
def remove_process(wfid)
2.times do
# two passes
Thread.pass
%w[ schedules expressions errors workitems ].each do |type|
get_many(type, wfid).each { |d| delete(d) }
end
doc = get_trackers
doc['trackers'].delete_if { |k, v| k.end_with?("!#{wfid}") }
@context.storage.put(doc)
end
end
def dump(type)
require 'yaml'
YAML.dump({ type => get_many(type) })
end
protected
# Used by put_msg
#
def prepare_msg_doc(action, options)
# merge! is way faster than merge (no object creation probably)
@counter ||= 0
t = Time.now.utc
ts = "#{t.strftime('%Y-%m-%d')}!#{t.to_i}.#{'%06d' % t.usec}"
_id = "#{$$}!#{Thread.current.object_id}!#{ts}!#{'%03d' % @counter}"
@counter = (@counter + 1) % 1000
# some platforms (windows) have shallow usecs, so adding that counter...
msg = options.merge!('type' => 'msgs', '_id' => _id, 'action' => action)
msg.delete('_rev')
# in case of message replay
msg
end
# Used by put_schedule
#
def prepare_schedule_doc(flavour, owner_fei, s, msg)
at = if s.is_a?(Time) # at or every
s
elsif Ruote.cron_string?(s) # cron
Rufus::CronLine.new(s).next_time(Time.now + 1)
else # at or every
Ruote.s_to_at(s)
end
at = at.utc
if at <= Time.now.utc && flavour == 'at'
put_msg(msg.delete('action'), msg)
return false
end
sat = at.strftime('%Y%m%d%H%M%S')
i = "#{flavour}-#{Ruote.to_storage_id(owner_fei)}-#{sat}"
{
'_id' => i,
'type' => 'schedules',
'flavour' => flavour,
'original' => s,
'at' => Ruote.time_to_utc_s(at),
'owner' => owner_fei,
'wfid' => owner_fei['wfid'],
'msg' => msg
}
end
def get_engine_variables
get('variables', 'variables') || {
'type' => 'variables', '_id' => 'variables', 'variables' => {} }
end
# Returns all the ats whose due date arrived (now or earlier)
#
def filter_schedules(schedules, now)
now = Ruote.time_to_utc_s(now)
schedules.select { |sch| sch['at'] <= now }
end
# Used by #get_many. Returns true whenever one of the keys matches the
# doc['_id']. Works with strings (_id ends with key) or regexes (_id matches
# key).
#
def key_match?(type, keys, doc)
_id = doc.is_a?(Hash) ? doc['_id'] : doc
if keys.first.is_a?(String) && type == 'schedules'
keys.find { |key| _id.match(/#{key}-\d+$/) }
elsif keys.first.is_a?(String)
keys.find { |key| _id.end_with?(key) }
else # Regexp
keys.find { |key| _id.match(key) }
end
end
# (Only used by ruote-couch 2.2.x)
#
# TODO: remove me at some point
#
def self.key_match?(keys, doc)
_id = doc.is_a?(Hash) ? doc['_id'] : doc
if keys.first.is_a?(String)
keys.find { |key| _id.end_with?(key) }
else # Regexp
keys.find { |key| _id.match(key) }
end
end
end
end