-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathttm.lua
More file actions
241 lines (199 loc) · 6.78 KB
/
ttm.lua
File metadata and controls
241 lines (199 loc) · 6.78 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
--- Temp Table Manager
--
local log = require('log')
local fiber = require('fiber')
local clock = require('clock')
local ttm = {}
-- Параметры по умолчанию
ttm.interval = 60
ttm.yield_every = 100
-- Инициализация служебного спейса
function ttm.init()
box.once('ttm_init', function()
local space = box.schema.create_space('temp_data', {
format = {
{ name = 't_key', type = 'string' }, -- Имя логической записи
{ name = 'key', type = 'string' }, -- Ключ (приводится к строке)
{ name = 'value', type = 'any' }, -- Произвольные данные
{ name = 'created', type = 'number' },
{ name = 'ttl', type = 'number' }
},
if_not_exists = true
})
space:create_index('primary', {
parts = { 't_key', 'key' }
})
space:create_index('by_expire', {
parts = { 'created', 'ttl' },
unique = false
})
end)
end
--- Добавление (или обновление) записи
-- @param t_key (string) - Имя логической записи
-- @param key (string) - Ключ записи
-- @param value (any) - Значение (по умолчанию true)
-- @param ttl (number) - TTL в секундах
-- @return boolean - true если добавлено впервые, false если запись ещё жива
function ttm.add(t_key, key, value, ttl)
value = value or true
ttl = ttl or 60
key = tostring(key)
local now = clock.time()
local existing = box.space.temp_data:get({ t_key, key })
if existing then
local created, old_ttl = existing.created, existing.ttl
if now - created < old_ttl then
return false
end
end
box.space.temp_data:put({ t_key, tostring(key), value, now, ttl })
return true
end
--- Проверка/регистрация одноразового действия
-- @param t_key (string) - Имя логической записи
-- @param key (string) - Ключ записи
-- @param ttl (number) - TTL в секундах
-- @return boolean - true если разрешено, false если еще рано
function ttm.try_once(t_key, key, ttl)
return ttm.add(t_key, key, true, ttl)
end
--- Возвращает оставшееся время до истечения записи
-- @param t_key (string) - Имя логической записи
-- @param key (string) - Ключ записи
-- @return number|nil - Секунды до истечения или nil если запись не найдена
function ttm.time_left(t_key, key)
key = tostring(key)
local rec = box.space.temp_data:get({ t_key, key })
if not rec then
return nil
end
local remaining = rec.ttl - (clock.time() - rec.created)
return (remaining > 0) and remaining or 0
end
--- Проверка существования активной записи
-- @param t_key (string) - Имя логической записи
-- @param key (string) - Ключ записи
-- @return boolean - true если запись существует и не истекла
function ttm.exists(t_key, key)
local time_left = ttm.time_left(t_key, key)
return time_left ~= nil and time_left > 0
end
--- Проверка значения записи, если она активна
-- @param t_key string - Имя логической записи
-- @param key string - Ключ записи
-- @return any|nil - Значение записи или nil если не найдена/истекла
function ttm.get(t_key, key)
key = tostring(key)
local rec = box.space.temp_data:get({ t_key, key })
if not rec then
return nil
end
-- Проверка на истечение
local now = clock.time()
if now - rec.created >= rec.ttl then
return nil
end
return rec.value
end
--- Удаление записи
-- @param t_key (string) - Имя логической записи
-- @param key (string) - Ключ записи
-- @return boolean - true если запись была удалена
function ttm.delete(t_key, key)
key = tostring(key)
local existing = box.space.temp_data:get({ t_key, key })
if existing then
box.space.temp_data:delete({ t_key, key })
return true
end
return false
end
--- Очистка устаревших записей
function ttm:sweep()
if not box.space.temp_data then
return
end
local now = clock.time()
local expired = {}
local yield_every = self.yield_every
local processed = 0
-- Сборка истекших записей
-- Проход по индексу by_expire для оптимизации
for _, tuple in box.space.temp_data.index.by_expire:pairs() do
local t_key = tuple[1]
local key = tuple[2]
local created = tuple[4]
local ttl = tuple[5]
if now - created >= ttl then
table.insert(expired, { t_key, key })
else
-- Поскольку индекс отсортирован по времени создания,
-- все последующие записи будут более новыми
break
end
processed = processed + 1
if processed % yield_every == 0 then
fiber.yield()
end
end
-- Удаляем истекшие записи
for _, record in ipairs(expired) do
box.space.temp_data:delete({ record[1], record[2] })
processed = processed + 1
if processed % yield_every == 0 then
fiber.yield()
end
end
if #expired > 0 then
log.info(string.format("TTM: Cleaned %d expired records", #expired))
end
end
--- Получение статистики
-- @return table - общая статистика и по логическим таблицам
function ttm.get_stats()
if not box.space.temp_data then
return {
total = 0,
active = 0,
expired = 0,
by_table = {}
}
end
local stats = {
total = 0,
active = 0,
expired = 0,
by_table = {}
}
local now = clock.time()
for _, tuple in box.space.temp_data:pairs() do
local t_key = tuple[1]
local created = tuple[4]
local ttl = tuple[5]
stats.total = stats.total + 1
if not stats.by_table[t_key] then
stats.by_table[t_key] = { total = 0, active = 0, expired = 0 }
end
stats.by_table[t_key].total = stats.by_table[t_key].total + 1
if now - created < ttl then
stats.active = stats.active + 1
stats.by_table[t_key].active = stats.by_table[t_key].active + 1
else
stats.expired = stats.expired + 1
stats.by_table[t_key].expired = stats.by_table[t_key].expired + 1
end
end
return stats
end
-- Запуск фонового fiber-а для очистки
function ttm.run()
fiber.create(function()
fiber.self():name('ttm_sweeper')
while true do
fiber.sleep(ttm.interval)
ttm:sweep()
end
end)
end
return ttm