56 lines
1.4 KiB
Lua
56 lines
1.4 KiB
Lua
local metrics = require("utils.metrics")
|
|
|
|
-- config
|
|
local flush_interval_ticks = 60 -- flush every n ticks
|
|
|
|
-- state
|
|
--- @type table<number, fun()>
|
|
local queue = {}
|
|
|
|
--- @type table<number, string>
|
|
local buffer = {}
|
|
local last_reset = 0
|
|
|
|
-- queue operations to perform for each round of metric processing
|
|
-- that way, avoid doing too much work in a single game tick and causing UPS inconsistencies
|
|
local function prepare_queue()
|
|
queue = {}
|
|
for _, surface in pairs(game.surfaces) do
|
|
for _, force in pairs(game.forces) do
|
|
table.insert(queue, metrics.calc_item_production_statistics(buffer, surface, force))
|
|
table.insert(queue, metrics.calc_fluid_production_statistics(buffer, surface, force))
|
|
end
|
|
table.insert(queue, metrics.calc_power_statistics(buffer, surface))
|
|
end
|
|
end
|
|
|
|
local function process_queue()
|
|
local entry = table.remove(queue, 1)
|
|
if entry then
|
|
entry()
|
|
end
|
|
end
|
|
|
|
local function tick()
|
|
process_queue()
|
|
|
|
if #queue == 0 and #buffer > 0 then
|
|
helpers.write_file("metrics.prom", table.concat(buffer, "\n"), false)
|
|
buffer = {}
|
|
end
|
|
|
|
if #queue == 0 and game.tick - last_reset >= flush_interval_ticks then
|
|
prepare_queue()
|
|
last_reset = game.tick
|
|
end
|
|
end
|
|
|
|
-- main tick handler
|
|
script.on_event(defines.events.on_tick, tick)
|
|
|
|
-- startup
|
|
script.on_init(function()
|
|
last_reset = game.tick
|
|
prepare_queue()
|
|
end)
|