gluon-announced: add support for caching announced data

This commit is contained in:
Matthias Schiffer 2015-12-12 20:49:17 +01:00
parent 5927fd66db
commit eba7ecbbc0

View File

@ -1,6 +1,7 @@
local announce = require 'gluon.announce' local announce = require 'gluon.announce'
local deflate = require 'deflate' local deflate = require 'deflate'
local json = require 'luci.jsonc' local json = require 'luci.jsonc'
local util = require 'luci.util'
local nixio = require 'nixio' local nixio = require 'nixio'
local fs = require 'nixio.fs' local fs = require 'nixio.fs'
@ -10,16 +11,36 @@ nixio.chdir('/lib/gluon/announce/')
for dir in fs.glob('*.d') do for dir in fs.glob('*.d') do
local name = dir:sub(1, -3) local name = dir:sub(1, -3)
memoize[name] = announce.collect_dir(dir) memoize[name] = {
collect = announce.collect_dir(dir),
-- tonumber will return 0 for invalid inputs
cache_time = tonumber(util.trim(fs.readfile(name .. '.cache') or ''))
}
end end
local function collect(type) local function collect(type, timestamp)
return memoize[type] and memoize[type]() local c = memoize[type]
if not c then
return nil
end
if c.cache_timeout and timestamp < c.cache_timeout then
return c.cache
else
local ret = c.collect()
if c.cache_time then
c.cache = ret
c.cache_timeout = timestamp + c.cache_time
end
return ret
end
end end
module('gluon.announced', package.seeall) module('gluon.announced', package.seeall)
function handle_request(query) function handle_request(query, timestamp)
collectgarbage() collectgarbage()
local m = query:match('^GET ([a-z ]+)$') local m = query:match('^GET ([a-z ]+)$')
@ -28,7 +49,7 @@ function handle_request(query)
local data = {} local data = {}
for q in m:gmatch('([a-z]+)') do for q in m:gmatch('([a-z]+)') do
local ok, val = pcall(collect, q) local ok, val = pcall(collect, q, timestamp)
if ok then if ok then
data[q] = val data[q] = val
end end
@ -38,7 +59,7 @@ function handle_request(query)
ret = deflate.compress(json.stringify(data)) ret = deflate.compress(json.stringify(data))
end end
elseif query:match('^[a-z]+$') then elseif query:match('^[a-z]+$') then
local ok, data = pcall(collect, query) local ok, data = pcall(collect, query, timestamp)
if ok then if ok then
ret = json.stringify(data) ret = json.stringify(data)
end end