summaryrefslogtreecommitdiff
path: root/store.lua
blob: b978b17c90cda7cc2b0621a0f97289a152d9f7cb (plain)
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
local cqueues = require'cqueues'
local db = require'r.db'
local schema = require'r.db.schema'
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)
	schema.schemafy {
		messages = {
			{"p_type","text",not nil},
			{"p_name","text",not nil},
			{"channel","text",not nil},
			{"author","text",not nil},
			{"ts","text",not nil},
			{"body","text"},
		},
	}
	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  (p_type,
			p_name,channel,author,ts,body)
			values (?, ?, ?, ?, ?, ?); ]],
			msg.pylon.type,msg.pylon.name,
			msg.channel.id, msg.author.id,
            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 p_type p_name channel author 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