/
dispatch.cr
95 lines (79 loc) · 1.97 KB
/
dispatch.cr
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
class Log
# Base interface implemented by log entry dispatchers
#
# Dispatchers are in charge of sending log entries according
# to different strategies.
module Dispatcher
alias Spec = Dispatcher | DispatchMode
# Dispatch a log entry to the specified backend
abstract def dispatch(entry : Entry, backend : Backend)
# Close the dispatcher, releasing resources
def close
end
# :nodoc:
def self.for(mode : DispatchMode) : self
case mode
in .sync?
SyncDispatcher.new
in .async?
AsyncDispatcher.new
in .direct?
DirectDispatcher
end
end
end
enum DispatchMode
Sync
Async
Direct
end
# Stateless dispatcher that deliver log entries immediately
module DirectDispatcher
extend Dispatcher
def self.dispatch(entry : Entry, backend : Backend)
backend.write(entry)
end
end
# Deliver log entries asynchronously through a channels
class AsyncDispatcher
include Dispatcher
def initialize(buffer_size = 2048)
@channel = Channel({Entry, Backend}).new(buffer_size)
@done = Channel(Nil).new
spawn write_logs
end
def dispatch(entry : Entry, backend : Backend) : Nil
@channel.send({entry, backend})
end
private def write_logs
while msg = @channel.receive?
entry, backend = msg
backend.write(entry)
end
@done.send nil
end
def close : Nil
# TODO: this might fail if being closed from different threads
unless @channel.closed?
@channel.close
@done.receive
end
end
def finalize
close
end
end
# Deliver log entries directly. It uses a mutex to guarantee
# one entry is delivered at a time.
class SyncDispatcher
include Dispatcher
def initialize
@mutex = Mutex.new(:unchecked)
end
def dispatch(entry : Entry, backend : Backend)
@mutex.synchronize do
backend.write(entry)
end
end
end
end