napkin/foppy.lua

114 lines
3.2 KiB
Lua

--[[
zlib License
Copyright (c) 2025 Nelson "N*" Lopez <darltrash@icloud.com>
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
]]
-- THIS IS A WIP LIBRARY, DO NOT USE YET UNLESS
-- YOU WANNA FIDDLE WITH THE MESS THAT IT IS.
local json = require "json"
local fs = require "fs"
local tick_precision = 2 -- tick each N seconds (decimal)
local timeout = 60 * 10 -- 10 minutes
local write_timeout = 30
local foppy = {}
foppy.cache = {}
foppy.open = function(file, writeable)
local c = foppy.cache[file]
if c then
c.timeout = timeout
c.write_timeout = writeable and write_timeout
return c.data
end
local raw = fs.readFileSync(file)
if not raw then
return nil, 404
end
local data = json.decode(raw)
c = {
timeout = timeout,
write_timeout = writeable and write_timeout,
data = data
}
foppy.cache[file] = c
return c.data
end
foppy.setup = function()
local timer = require "timer"
timer.setInterval(tick_precision * 1000, function()
for name, object in pairs(foppy.cache) do
object.timeout = object.timeout - tick_precision
object.write_timeout = object.write_timeout - tick_precision
if object.timeout <= 0 then
foppy.cache[name] = nil
object.write_timeout = 0
end
if object.write_timeout <= 0 then
fs.writeFileSync(name, json.encode(object.data))
end
end
end)
-- TODO: Finish this.
--[[
local process = require("process").globalProcess()
local hecc_everything = function()
print("foppy says hecc!!!")
fs.writeFileSync("hecc", "hecc")
for name, object in pairs(foppywrite_timeout.cache) do
if object.write_timeout then
fs.writeFileSync(name, json.encode(object.data))
end
end
end
process:on("sigint", hecc_everything)
process:on("sigterm", hecc_everything)
process:on("sighup", hecc_everything)
process:on("sigquit", hecc_everything)
]]
end
foppy.sync = function(what, close)
local object = foppy.cache[what]
if object then
if object.write_timeout then
fs.writeFileSync(what, json.encode(object.data))
end
if close then
foppy.cache[what] = nil
end
end
end
package.loaded["./foppy"] = foppy
return foppy