Debian Codegraph @

_examples/custom_engine_tarantool/tntserver/centrifuge.lua

raw
1 local clock = require 'clock'
2 local fiber = require 'fiber'
3 local log = require 'log'
4 local json = require 'json'.new()
5 local indexpiration = require 'indexpiration'
6
7 --================================================================================
8 -- Centrifuge Tarantool module, provides Broker and PresenceManager functionality.
9 --================================================================================
10
11 local centrifuge = {}
12
13 centrifuge.init = function(opts)
14 if not opts then opts = {} end
15 log.info("Centrifuge init with opts: %s", json.encode(opts))
16
17 local pubs_temporary = opts.pubs_temporary or false
18 local meta_temporary = opts.meta_temporary or false
19 local presence_temporary = opts.presence_temporary or false
20
21 box.schema.create_space('pubs', {if_not_exists = true; temporary = pubs_temporary})
22 box.space.pubs:format( {
23 {name = 'id'; type = 'unsigned'},
24 {name = 'channel'; type = 'string'},
25 {name = 'offset'; type = 'unsigned'},
26 {name = 'exp'; type = 'number'},
27 {name = 'data'; type = 'string'},
28 {name = 'info'; type = 'string'},
29 });
30 box.space.pubs:create_index('primary', {
31 parts = {{field='id', type='unsigned'}};
32 if_not_exists = true;
33 })
34 box.space.pubs:create_index('channel', {
35 parts = {{field='channel', type='string'}, {field='offset', type='unsigned'}};
36 if_not_exists = true;
37 })
38 box.space.pubs:create_index('exp', {
39 parts = {{field='exp', type='number'}, {field='id', type='unsigned'}};
40 if_not_exists = true;
41 })
42
43 box.schema.create_space('meta', {if_not_exists = true; temporary = meta_temporary})
44 box.space.meta:format({
45 {name = 'channel'; type = 'string'},
46 {name = 'offset'; type = 'unsigned'},
47 {name = 'epoch'; type = 'string'},
48 {name = 'exp'; type = 'number'},
49 });
50 box.space.meta:create_index('primary', {
51 parts = {{field='channel', type='string'}};
52 if_not_exists = true;
53 })
54 box.space.meta:create_index('exp', {
55 parts = {{field='exp', type='number'}, {field='channel', type='string'}};
56 if_not_exists = true;
57 })
58
59 box.schema.create_space('presence', {if_not_exists = true; temporary = presence_temporary})
60 box.space.presence:format({
61 {name = 'channel'; type = 'string'},
62 {name = 'client_id'; type = 'string'},
63 {name = 'user_id'; type = 'string'},
64 {name = 'conn_info'; type = 'string'},
65 {name = 'chan_info'; type = 'string'},
66 {name = 'exp'; type = 'number'},
67 });
68 box.space.presence:create_index('primary', {
69 parts = {{field='channel', type='string'}, {field='client_id', type='string'}};
70 if_not_exists = true;
71 })
72 box.space.presence:create_index('exp', {
73 parts = {{field='exp', type='number'}};
74 if_not_exists = true;
75 })
76
77 indexpiration(box.space.pubs, {
78 field = 'exp';
79 kind = 'time';
80 precise = true;
81 on_delete = function(t) end
82 })
83
84 indexpiration(box.space.meta, {
85 field = 'exp';
86 kind = 'time';
87 precise = true;
88 on_delete = function(t) end
89 })
90
91 indexpiration(box.space.presence, {
92 field = 'exp';
93 kind = 'time';
94 precise = true;
95 on_delete = function(t) end
96 })
97 end
98
99 centrifuge.id_to_channels = {}
100 centrifuge.channel_to_ids = {}
101 centrifuge.id_to_messages = {}
102 centrifuge.id_to_fiber = {}
103
104 box.session.on_connect(function() end)
105
106 box.session.on_disconnect(function()
107 local id = box.session.storage.subscriber_id
108 if id then
109 local channelsById = centrifuge.id_to_channels[id]
110 if channelsById then
111 while next(channelsById) do
112 for key, _ in pairs(channelsById) do
113 centrifuge.channel_to_ids[key][id] = nil
114 if next(centrifuge.channel_to_ids[key]) == nil then
115 centrifuge.channel_to_ids[key] = nil
116 end
117 channelsById[key] = nil
118 end
119 end
120 centrifuge.id_to_channels[id] = nil
121 end
122 centrifuge.id_to_fiber[id]:close()
123 centrifuge.id_to_fiber[id] = nil
124 centrifuge.id_to_messages[id] = nil
125 end
126 end)
127
128 function centrifuge.get_messages(id, use_polling, timeout)
129 if not box.session.storage.subscriber_id then
130 -- register poller connection. Connection will use this id
131 -- to register or remove subscriptions.
132 box.session.storage.subscriber_id = id
133 centrifuge.id_to_fiber[id] = fiber.channel()
134 return
135 end
136 box.session.storage.subscriber_id = id
137 if not timeout then timeout = 0 end
138 local now = fiber.time()
139 while true do
140 local messages = centrifuge.id_to_messages[id]
141 centrifuge.id_to_messages[id] = nil
142 if messages then
143 if use_polling then
144 return messages
145 else
146 local ok = box.session.push(messages)
147 if ok ~= true then
148 error("write error")
149 end
150 end
151 else
152 local left = (now + timeout) - fiber.time()
153 if left <= 0 then
154 -- timed out, poller will call get_messages again.
155 return
156 end
157 centrifuge.id_to_fiber[id]:get(left)
158 end
159 end
160 end
161
162 function centrifuge.subscribe(id, channels)
163 for k,v in pairs(channels) do
164 local idChannels = centrifuge.id_to_channels[id] or {}
165 idChannels[v] = true
166 centrifuge.id_to_channels[id] = idChannels
167
168 local channelIds = centrifuge.channel_to_ids[v] or {}
169 channelIds[id] = true
170 centrifuge.channel_to_ids[v] = channelIds
171 end
172 end
173
174 function centrifuge.unsubscribe(id, channels)
175 for k,v in pairs(channels) do
176 if centrifuge.id_to_channels[id] then
177 centrifuge.id_to_channels[id][v] = nil
178 end
179 if centrifuge.channel_to_ids[v] then
180 centrifuge.channel_to_ids[v][id] = nil
181 end
182 if centrifuge.id_to_channels[id] then
183 centrifuge.id_to_channels[id] = nil
184 end
185 if centrifuge.channel_to_ids[v] and next(centrifuge.channel_to_ids[v]) == nil then
186 centrifuge.channel_to_ids[v] = nil
187 end
188 end
189 end
190
191 local function publish_to_subscribers(channel, message_tuple)
192 local channelIds = centrifuge.channel_to_ids[channel] or {}
193 if channelIds then
194 for k,v in pairs(channelIds) do
195 local id_to_messages = centrifuge.id_to_messages[k] or {}
196 table.insert(id_to_messages, message_tuple)
197 centrifuge.id_to_messages[k] = id_to_messages
198 end
199 end
200 end
201
202 local function wake_up_subscribers(channel)
203 local ids = centrifuge.channel_to_ids[channel]
204 if ids then
205 for k, _ in pairs(ids) do
206 local channel = centrifuge.id_to_fiber[k]
207 if channel:has_readers() then channel:put(true, 0) end
208 end
209 end
210 end
211
212 function centrifuge.publish(msg_type, channel, data, info, ttl, size, meta_ttl)
213 if not ttl then ttl = 0 end
214 if not size then size = 0 end
215 if not meta_ttl then meta_ttl = 0 end
216 local epoch = ""
217 local offset = 0
218 box.begin()
219 if ttl > 0 and size > 0 then
220 local now = clock.realtime()
221 local meta_exp = 0
222 if meta_ttl > 0 then
223 meta_exp = now + meta_ttl
224 end
225 local stream_meta = box.space.meta:get(channel)
226 if stream_meta then
227 offset = stream_meta[2] + 1
228 epoch = stream_meta[3]
229 else
230 epoch = tostring(now)
231 offset = 1
232 end
233 box.space.meta:upsert({channel, offset, epoch, meta_exp}, {{'=', 'channel', channel}, {'+', 'offset', 1}, {'=', 'exp', meta_exp}})
234 box.space.pubs:auto_increment{channel, offset, clock.realtime() + tonumber(ttl), data, info}
235 local max_offset_to_keep = offset - size
236 if max_offset_to_keep > 0 then
237 for _, v in box.space.pubs.index.channel:pairs({channel, max_offset_to_keep}, {iterator = box.index.LE}) do
238 box.space.pubs:delete{v.id}
239 end
240 end
241 end
242 publish_to_subscribers(channel, {msg_type, channel, offset, epoch, data, info})
243 wake_up_subscribers(channel)
244 box.commit()
245 return offset, epoch
246 end
247
248 function centrifuge.history(channel, since_offset, limit, include_pubs, meta_ttl)
249 if not meta_ttl then meta_ttl = 0 end
250 local meta_exp = 0
251 local now = clock.realtime()
252 if meta_ttl > 0 then
253 meta_exp = now + meta_ttl
254 end
255 local epoch = tostring(now)
256 box.begin()
257 box.space.meta:upsert({channel, 0, epoch, meta_exp}, {{'=', 'channel', channel}, {'=', 'exp', meta_exp}})
258 local stream_meta = box.space.meta:get(channel)
259 if not include_pubs then
260 box.commit()
261 return stream_meta[2], stream_meta[3], nil
262 end
263 if stream_meta[2] == since_offset - 1 then
264 box.commit()
265 return stream_meta[2], stream_meta[3], nil
266 end
267 local num_entries = 0
268 local pubs = box.space.pubs.index.channel:pairs({channel, since_offset}, {iterator = box.index.GE}):take_while(function(x)
269 num_entries = num_entries + 1
270 return x.channel == channel and (limit < 1 or num_entries < limit + 1)
271 end):totable()
272 box.commit()
273 return stream_meta[2], stream_meta[3], pubs
274 end
275
276 function centrifuge.remove_history(channel)
277 box.begin()
278 for _, v in box.space.pubs.index.channel:pairs{channel} do
279 box.space.pubs:delete{v.id}
280 end
281 box.commit()
282 end
283
284 function centrifuge.add_presence(channel, ttl, client_id, user_id, conn_info, chan_info)
285 if not ttl then ttl = 0 end
286 if not conn_info then conn_info = "" end
287 if not chan_info then chan_info = "" end
288 local exp = clock.realtime() + ttl
289 box.space.presence:put({channel, client_id, user_id, conn_info, chan_info, exp})
290 end
291
292 function centrifuge.remove_presence(channel, client_id)
293 for _, v in box.space.presence:pairs({channel, client_id}, {iterator = box.index.EQ}) do
294 box.space.presence:delete{channel, client_id}
295 end
296 end
297
298 function centrifuge.presence(channel)
299 return box.space.presence:select{channel}
300 end
301
302 function centrifuge.presence_stats(channel)
303 local users = {}
304 local num_clients = 0
305 local num_users = 0
306 for _, v in box.space.presence:pairs({channel}, {iterator = box.index.EQ}) do
307 num_clients = num_clients + 1
308 if not users[v.user_id] then
309 num_users = num_users + 1
310 users[v.user_id] = true
311 end
312 end
313 return num_clients, num_users
314 end
315
316 return centrifuge