54 using multi_value_types = black_magic::S<bool, int64_t, double, std::string>;
122 using DataPair = std::pair<uint64_t , std::string >;
126 void add(std::string key, uint64_t time)
128 auto it = times_.find(key);
129 if (it != times_.end()) remove(key);
131 queue_.insert({time, std::move(key)});
134 void remove(
const std::string& key)
136 auto it = times_.find(key);
137 if (it != times_.end())
139 queue_.erase({it->second, key});
147 if (queue_.empty())
return std::numeric_limits<uint64_t>::max();
148 return queue_.begin()->first;
152 uint64_t
get(
const std::string& key)
const
154 auto it = times_.find(key);
155 if (it == times_.end())
return std::numeric_limits<uint64_t>::max();
159 std::string pop_first()
161 auto it = times_.find(queue_.begin()->second);
162 auto key = it->first;
164 queue_.erase(queue_.begin());
168 using iterator =
typename std::set<DataPair>::const_iterator;
170 iterator begin()
const {
return queue_.cbegin(); }
172 iterator end()
const {
return queue_.cend(); }
175 std::set<DataPair> queue_;
176 std::unordered_map<std::string, uint64_t> times_;
200 struct SessionMiddleware
202 using lock = std::scoped_lock<std::mutex>;
203 using rc_lock = std::scoped_lock<std::recursive_mutex>;
208 std::recursive_mutex& mutex()
215 bool exists() {
return bool(node); }
219 auto get(
const std::string& key,
const F& fallback = F())
225 ->
decltype(std::declval<session::multi_value>().get<F>(std::declval<F>()))
227 if (!node)
return fallback;
228 rc_lock l(node->mutex);
230 auto it = node->entries.find(key);
231 if (it != node->entries.end())
return it->second.get<F>(fallback);
237 void set(
const std::string& key, T value)
240 rc_lock l(node->mutex);
242 node->dirty.insert(key);
243 node->entries[key].set(std::move(value));
246 bool contains(
const std::string& key)
248 if (!node)
return false;
249 rc_lock l(node->mutex);
251 return node->entries.find(key) != node->entries.end();
255 template<
typename Func>
256 void apply(
const std::string& key,
const Func& f)
258 using traits = utility::function_traits<Func>;
259 using arg =
typename std::decay<typename traits::template arg<0>>::type;
260 using retv =
typename std::decay<typename traits::result_type>::type;
262 rc_lock l(node->mutex);
263 node->dirty.insert(key);
264 node->entries[key].set<retv>(f(node->entries[key].get(arg{})));
268 void remove(
const std::string& key)
271 rc_lock l(node->mutex);
272 node->dirty.insert(key);
273 node->entries.erase(key);
277 std::string string(
const std::string& key)
279 if (!node)
return "";
280 rc_lock l(node->mutex);
282 auto it = node->entries.find(key);
283 if (it != node->entries.end())
return it->second.string();
288 std::vector<std::string> keys()
290 if (!node)
return {};
291 rc_lock l(node->mutex);
293 std::vector<std::string> out;
294 for (
const auto& p : node->entries)
295 out.push_back(p.first);
301 void refresh_expiration()
304 node->requested_refresh =
true;
308 friend struct SessionMiddleware;
312 if (!node) node = std::make_shared<session::CachedSession>();
315 std::shared_ptr<session::CachedSession> node;
318 template<
typename... Ts>
323 id_length_(id_length),
325 store_(std::forward<Ts>(ts)...), mutex_(new std::mutex{})
328 template<
typename... Ts>
333 .max_age( 30 * 24 * 60 * 60)
337 std::forward<Ts>(ts)...)
340 template<
typename AllContext>
341 void before_handle(request& , response& , context& ctx, AllContext& all_ctx)
345 auto& cookies = all_ctx.template get<CookieParser>();
346 auto session_id = load_id(cookies);
347 if (session_id ==
"")
return;
350 auto it = cache_.find(session_id);
351 if (it != cache_.end())
353 it->second->referrers++;
354 ctx.node = it->second;
359 if (!store_.contains(session_id))
return;
361 auto node = std::make_shared<session::CachedSession>();
362 node->session_id = session_id;
371 CROW_LOG_ERROR <<
"Exception occurred during session load";
376 cache_[session_id] = node;
379 template<
typename AllContext>
380 void after_handle(request& , response& ,
context& ctx, AllContext& all_ctx)
383 if (!ctx.node || --ctx.node->referrers > 0)
return;
384 ctx.node->requested_refresh |= ctx.node->session_id ==
"";
387 if (ctx.node->session_id ==
"")
390 ctx.node->session_id = std::move(ctx.node->requested_session_id);
391 if (ctx.node->session_id ==
"")
393 ctx.node->session_id = utility::random_alphanum(id_length_);
398 cache_.erase(ctx.node->session_id);
401 if (ctx.node->requested_refresh)
403 auto& cookies = all_ctx.template get<CookieParser>();
404 store_id(cookies, ctx.node->session_id);
409 store_.save(*ctx.node);
413 CROW_LOG_ERROR <<
"Exception occurred during session save";
419 std::string next_id()
424 id = utility::random_alphanum(id_length_);
425 }
while (store_.contains(
id));
429 std::string load_id(
const CookieParser::context& cookies)
431 return cookies.get_cookie(cookie_.name());
434 void store_id(CookieParser::context& cookies,
const std::string& session_id)
436 cookie_.value(session_id);
437 cookies.set_cookie(cookie_);
444 CookieParser::Cookie cookie_;
449 std::unique_ptr<std::mutex> mutex_;
450 std::unordered_map<std::string, std::shared_ptr<session::CachedSession>> cache_;
483 FileStore(
const std::string& folder, uint64_t expiration_seconds = 30 * 24 * 60 * 60):
484 path_(folder), expiration_seconds_(expiration_seconds)
486 std::ifstream ifs(get_filename(
".expirations",
false));
488 auto current_ts = chrono_time();
491 while (ifs >> key >> time)
493 if (current_ts > time)
497 else if (contains(key))
499 expirations_.add(key, time);
506 std::ofstream ofs(get_filename(
".expirations",
false), std::ios::trunc);
507 for (
const auto& p : expirations_)
508 ofs << p.second <<
" " << p.first <<
"\n";
513 void handle_expired()
516 auto current_ts = chrono_time();
517 while (current_ts > expirations_.peek_first() && deleted < 3)
519 evict(expirations_.pop_first());
528 std::ifstream file(get_filename(cn.session_id));
530 std::stringstream buffer;
531 buffer << file.rdbuf() << std::endl;
533 for (
const auto& p : json::load(buffer.str()))
534 cn.entries[p.key()] = session::multi_value::from_json(p);
539 if (cn.requested_refresh)
540 expirations_.add(cn.session_id, chrono_time() + expiration_seconds_);
541 if (cn.dirty.empty())
return;
543 std::ofstream file(get_filename(cn.session_id));
545 for (
const auto& p : cn.entries)
546 jw[p.first] = p.second.json();
547 file << jw.dump() << std::flush;
550 std::string get_filename(
const std::string& key,
bool suffix =
true)
552 std::string filename{key};
554 utility::sanitize_filename(filename);
557 filename.append(
".json");
559 return (path_/filename).string();
562 bool contains(
const std::string& key)
565 if (chrono_time() > expirations_.get(key))
567 expirations_.remove(key);
572 std::ifstream file(get_filename(key));
576 void evict(
const std::string& key)
578 std::remove(get_filename(key).c_str());
582 uint64_t chrono_time()
const
584 return std::chrono::duration_cast<std::chrono::seconds>(
585 std::chrono::system_clock::now().time_since_epoch())
589 std::filesystem::path path_;
590 uint64_t expiration_seconds_;