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
|
local cqueues = require'cqueues'
local db = require'r.db'
local qw = require'r.qw'
local html = require'r.html'
local T = html.T
local class = require'r.class'
local App = require'r.web.app'
local server = require'r.web.server'
local Queue = require'queue'
local Log = require'log'
local Store = class() -- we only have 1 instance of this, but, ough,
function Store.make(cls) return setmetatable({
q = Queue(),
log = Log"store",
},cls) end
function Store.storing(self)
local conn = db.conn()
for msg in self.q:iter() do
-- needs to go in its own coro
-- so we don't gum up the works while waiting on the db
conn:exec("insert into messages (ts, body) values (?,?);",
os.time(), msg.body)
self.log("stored",msg.body)
assert(conn:commit()) end end
function Store.store(self, msg) self.q:enqueue(msg) end
local function view(req)
local conn <close> = db.conn()
local rows = conn:fetch"select * from messages order by ts asc;"
local fields = qw"id ts body"
-- list comprehensions? WHAT ARE THOSE?????
local ths={} for i,v in ipairs(fields) do ths[i]=T.th(v) end
local trs={} for ri,r in ipairs(rows) do
local tds = {} for i,v in ipairs(fields) do tds[i]=T.td(r[v]) end
trs[ri] = T.tr(tds) end
local tab = T.table{
T.thead(T.tr(ths)),
T.tbody(trs),
}
return html.html {
T.h1'the messages',
tab
} end
local app = App{ view = view }
function Store.serving(self)
return server.run(self.cq, app) end
function Store.run(self)
self.cq = cqueues.new()
self.cq:wrap(self.storing, self)
self.cq:wrap(self.serving, self)
self.log("now running")
self.log:loop(self.cq)
end
return Store
|