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
|
# encoding: UTF-8
#-- vim:sw=2:et
#++
#
# :title: rbot's persistent message queue
require 'thread'
require 'securerandom'
module Irc
class Bot
module Journal
=begin rdoc
The journal is a persistent message queue for rbot, its based on a basic
publish/subscribe model and persists messages into backend databases
that can be efficiently searched for past messages.
It is a addition to the key value storage already present in rbot
through its registry subsystem.
=end
Config.register Config::StringValue.new('journal.storage',
:default => nil,
:requires_restart => true,
:desc => 'storage engine used by the journal')
Config.register Config::StringValue.new('journal.storage.uri',
:default => nil,
:requires_restart => true,
:desc => 'storage database uri')
class InvalidJournalMessage < StandardError
end
class ConsumeInterrupt < StandardError
end
class StorageError < StandardError
end
class JournalMessage
# a unique identification of this message
attr_reader :id
# describes a hierarchical queue into which this message belongs
attr_reader :topic
# when this message was published as a Time instance
attr_reader :timestamp
# contains the actual message as a Hash
attr_reader :payload
def initialize(message)
@id = message[:id]
@timestamp = message[:timestamp]
@topic = message[:topic]
@payload = message[:payload]
if @payload.class != Hash
raise InvalidJournalMessage.new('payload must be a hash!')
end
end
def get(pkey, default=:exception) # IDENTITY = Object.new instead of :ex..?
value = pkey.split('.').reduce(@payload) do |hash, key|
if hash.has_key?(key) or hash.has_key?(key.to_sym)
hash[key] || hash[key.to_sym]
else
if default == :exception
raise ArgumentError.new
else
default
end
end
end
end
def ==(other)
(@id == other.id) rescue false
end
def self.create(topic, payload, opt={})
JournalMessage.new(
id: opt[:id] || SecureRandom.uuid,
timestamp: opt[:timestamp] || Time.now,
topic: topic,
payload: payload
)
end
end
module Storage
class AbstractStorage
# intializes/opens a new storage connection
def initialize(opts={})
end
# inserts a message in storage
def insert(message)
end
# creates/ensures a index exists on the payload specified by key
def ensure_index(key)
end
# returns a array of message instances that match the query
def find(query=nil, limit=100, offset=0)
end
# returns the number of messages that match the query
def count(query=nil)
end
# remove messages that match the query
def remove(query=nil)
end
# destroy the underlying table/collection
def drop
end
# Returns all classes from the namespace that implement this interface
def self.get_impl
ObjectSpace.each_object(Class).select { |klass| klass < self }
end
end
def self.create(name, uri)
log 'load journal storage adapter: ' + name
load File.join(File.dirname(__FILE__), 'journal', name + '.rb')
cls = AbstractStorage.get_impl.first
cls.new(uri: uri)
end
end
# Describes a query on journal entries, it is used both to describe
# a subscription aswell as to query persisted messages.
# There two ways to declare a Query instance, using
# the DSL like this:
#
# Query.define do
# id 'foo'
# id 'bar'
# topic 'log.irc.*'
# topic 'log.core'
# timestamp from: Time.now, to: Time.now + 60 * 10
# payload 'action': :privmsg
# payload 'channel': '#rbot'
# payload 'foo.bar': 'baz'
# end
#
# or using a hash: (NOTE: avoid using symbols in payload)
#
# Query.define({
# id: ['foo', 'bar'],
# topic: ['log.irc.*', 'log.core'],
# timestamp: {
# from: Time.now
# to: Time.now + 60 * 10
# },
# payload: {
# 'action' => 'privmsg'
# 'channel' => '#rbot',
# 'foo.bar' => 'baz'
# }
# })
#
class Query
# array of ids to match (OR)
attr_reader :id
# array of topics to match with wildcard support (OR)
attr_reader :topic
# hash with from: timestamp and to: timestamp
attr_reader :timestamp
# hash of key values to match
attr_reader :payload
def initialize(query)
@id = query[:id]
@topic = query[:topic]
@timestamp = query[:timestamp]
@payload = query[:payload]
end
# returns true if the given message matches the query
def matches?(message)
return false if not @id.empty? and not @id.include? message.id
return false if not @topic.empty? and not topic_matches? message.topic
if @timestamp[:from]
return false unless message.timestamp >= @timestamp[:from]
end
if @timestamp[:to]
return false unless message.timestamp <= @timestamp[:to]
end
found = false
@payload.each_pair do |key, value|
begin
message.get(key.to_s)
rescue ArgumentError
end
found = true
end
return false if not found and not @payload.empty?
true
end
def topic_matches?(_topic)
@topic.each do |topic|
if topic.include? '*'
match = true
topic.split('.').zip(_topic.split('.')).each do |a, b|
if a == '*'
if not b or b.empty?
match = false
end
else
match = false unless a == b
end
end
return true if match
else
return true if topic == _topic
end
end
return false
end
# factory that constructs a query
class Factory
attr_reader :query
def initialize
@query = {
id: [],
topic: [],
timestamp: {
from: nil, to: nil
},
payload: {}
}
end
def id(*_id)
@query[:id] += _id
end
def topic(*_topic)
@query[:topic] += _topic
end
def timestamp(range)
@query[:timestamp] = range
end
def payload(query)
@query[:payload].merge!(query)
end
end
def self.define(query=nil, &block)
factory = Factory.new
if block_given?
factory.instance_eval(&block)
query = factory.query
end
Query.new query
end
end
class JournalBroker
class Subscription
attr_reader :query
attr_reader :block
def initialize(broker, query, block)
@broker = broker
@query = query
@block = block
end
def cancel
@broker.unsubscribe(self)
end
end
def initialize(opts={})
# overrides the internal consumer with a block
@consumer = opts[:consumer]
@bot = opts[:bot]
# storage backend
if @bot
@storage = opts[:storage] || Storage.create(
@bot.config['journal.storage'], @bot.config['journal.storage.uri'])
else
@storage = opts[:storage]
end
unless @storage
warning 'journal broker: no storage set up, won\'t persist messages'
end
@queue = Queue.new
# consumer thread:
@thread = Thread.new do
loop do
begin
consume @queue.pop
# pop(true) ... rescue ThreadError => e
rescue ConsumeInterrupt => e
error 'journal broker: stop thread, consume interrupt raised'
break
rescue Exception => e
error 'journal broker: exception in consumer thread'
error $!
end
end
end
# TODO: this is a first naive implementation, later we do the
# message/query matching for incoming messages more efficiently
@subscriptions = []
end
def consume(message)
return unless message
@consumer.call(message) if @consumer
# notify subscribers
@subscriptions.each do |s|
if s.query.matches? message
s.block.call(message)
end
end
@storage.insert(message) if @storage
end
def persists?
true if @storage
end
def join
@thread.join
end
def shutdown
@thread.raise ConsumeInterrupt.new
end
def publish(topic, payload)
@queue.push JournalMessage::create(topic, payload)
end
# subscribe to messages that match the given query
def subscribe(query, &block)
raise ArgumentError.new unless block_given?
s = Subscription.new(self, query, block)
@subscriptions << s
s
end
def unsubscribe(subscription)
@subscriptions.delete subscription
end
def find(query=nil, limit=100, offset=0, &block)
if block_given?
begin
res = @storage.find(query, limit, offset)
block.call(res)
end until res.length > 0
else
@storage.find(query, limit, offset)
end
end
def count(query=nil)
@storage.count(query)
end
def remove(query=nil)
@storage.remove(query)
end
end
end # Journal
end # Bot
end # Irc
|