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;
151 std::string pop_first()
153 auto it = times_.find(queue_.begin()->second);
154 auto key = it->first;
156 queue_.erase(queue_.begin());
160 using iterator =
typename std::set<DataPair>::const_iterator;
162 iterator begin()
const {
return queue_.cbegin(); }
164 iterator end()
const {
return queue_.cend(); }
167 std::set<DataPair> queue_;
168 std::unordered_map<std::string, uint64_t> times_;
194 using lock = std::scoped_lock<std::mutex>;
195 using rc_lock = std::scoped_lock<std::recursive_mutex>;
200 std::recursive_mutex& mutex()
207 bool exists() {
return bool(node); }
211 auto get(
const std::string& key,
const F& fallback = F())
217 ->
decltype(std::declval<session::multi_value>().get<F>(std::declval<F>()))
219 if (!node)
return fallback;
220 rc_lock l(node->mutex);
222 auto it = node->entries.find(key);
223 if (it != node->entries.end())
return it->second.get<F>(fallback);
229 void set(
const std::string& key, T value)
232 rc_lock l(node->mutex);
234 node->dirty.insert(key);
235 node->entries[key].set(std::move(value));
238 bool contains(
const std::string& key)
240 if (!node)
return false;
241 return node->entries.find(key) != node->entries.end();
245 template<
typename Func>
246 void apply(
const std::string& key,
const Func& f)
248 using traits = utility::function_traits<Func>;
249 using arg =
typename std::decay<typename traits::template arg<0>>::type;
250 using retv =
typename std::decay<typename traits::result_type>::type;
252 rc_lock l(node->mutex);
253 node->dirty.insert(key);
254 node->entries[key].set<retv>(f(node->entries[key].get(arg{})));
258 void remove(
const std::string& key)
261 rc_lock l(node->mutex);
262 node->dirty.insert(key);
263 node->entries.erase(key);
267 std::string string(
const std::string& key)
269 if (!node)
return "";
270 rc_lock l(node->mutex);
272 auto it = node->entries.find(key);
273 if (it != node->entries.end())
return it->second.string();
278 std::vector<std::string> keys()
280 if (!node)
return {};
281 rc_lock l(node->mutex);
283 std::vector<std::string> out;
284 for (
const auto& p : node->entries)
285 out.push_back(p.first);
291 void refresh_expiration()
294 node->requested_refresh =
true;
302 if (!node) node = std::make_shared<session::CachedSession>();
305 std::shared_ptr<session::CachedSession> node;
308 template<
typename... Ts>
313 id_length_(id_length),
315 store_(std::forward<Ts>(ts)...), mutex_(new std::mutex{})
318 template<
typename... Ts>
323 .max_age( 30 * 24 * 60 * 60)
327 std::forward<Ts>(ts)...)
330 template<
typename AllContext>
331 void before_handle(request& , response& , context& ctx, AllContext& all_ctx)
335 auto& cookies = all_ctx.template get<CookieParser>();
336 auto session_id = load_id(cookies);
337 if (session_id ==
"")
return;
340 auto it = cache_.find(session_id);
341 if (it != cache_.end())
343 it->second->referrers++;
344 ctx.node = it->second;
349 if (!store_.contains(session_id))
return;
351 auto node = std::make_shared<session::CachedSession>();
352 node->session_id = session_id;
361 CROW_LOG_ERROR <<
"Exception occurred during session load";
366 cache_[session_id] = node;
369 template<
typename AllContext>
370 void after_handle(request& , response& , context& ctx, AllContext& all_ctx)
373 if (!ctx.node || --ctx.node->referrers > 0)
return;
374 ctx.node->requested_refresh |= ctx.node->session_id ==
"";
377 if (ctx.node->session_id ==
"")
380 ctx.node->session_id = std::move(ctx.node->requested_session_id);
381 if (ctx.node->session_id ==
"")
383 ctx.node->session_id = utility::random_alphanum(id_length_);
388 cache_.erase(ctx.node->session_id);
391 if (ctx.node->requested_refresh)
393 auto& cookies = all_ctx.template get<CookieParser>();
394 store_id(cookies, ctx.node->session_id);
399 store_.save(*ctx.node);
403 CROW_LOG_ERROR <<
"Exception occurred during session save";
409 std::string next_id()
414 id = utility::random_alphanum(id_length_);
415 }
while (store_.contains(
id));
419 std::string load_id(
const CookieParser::context& cookies)
421 return cookies.get_cookie(cookie_.name());
424 void store_id(CookieParser::context& cookies,
const std::string& session_id)
426 cookie_.value(session_id);
427 cookies.set_cookie(cookie_);
434 CookieParser::Cookie cookie_;
439 std::unique_ptr<std::mutex> mutex_;
440 std::unordered_map<std::string, std::shared_ptr<session::CachedSession>> cache_;
473 FileStore(
const std::string& folder, uint64_t expiration_seconds = 30 * 24 * 60 * 60):
474 path_(folder), expiration_seconds_(expiration_seconds)
476 std::ifstream ifs(get_filename(
".expirations",
false));
478 auto current_ts = chrono_time();
481 while (ifs >> key >> time)
483 if (current_ts > time)
487 else if (contains(key))
489 expirations_.
add(key, time);
496 std::ofstream ofs(get_filename(
".expirations",
false), std::ios::trunc);
497 for (
const auto& p : expirations_)
498 ofs << p.second <<
" " << p.first <<
"\n";
503 void handle_expired()
506 auto current_ts = chrono_time();
507 while (current_ts > expirations_.
peek_first() && deleted < 3)
509 evict(expirations_.pop_first());
518 std::ifstream file(get_filename(cn.session_id));
520 std::stringstream buffer;
521 buffer << file.rdbuf() << std::endl;
523 for (
const auto& p : json::load(buffer.str()))
524 cn.entries[p.key()] = session::multi_value::from_json(p);
529 if (cn.requested_refresh)
530 expirations_.
add(cn.session_id, chrono_time() + expiration_seconds_);
531 if (cn.dirty.empty())
return;
533 std::ofstream file(get_filename(cn.session_id));
535 for (
const auto& p : cn.entries)
536 jw[p.first] = p.second.json();
537 file << jw.dump() << std::flush;
540 std::string get_filename(
const std::string& key,
bool suffix =
true)
542 std::string filename{key};
544 utility::sanitize_filename(filename);
547 filename.append(
".json");
549 return (path_/filename).string();
552 bool contains(
const std::string& key)
554 std::ifstream file(get_filename(key));
558 void evict(
const std::string& key)
560 std::remove(get_filename(key).c_str());
563 uint64_t chrono_time()
const
565 return std::chrono::duration_cast<std::chrono::seconds>(
566 std::chrono::steady_clock::now().time_since_epoch())
570 std::filesystem::path path_;
571 uint64_t expiration_seconds_;