/* * Copyright (C) 2019 pengjian.uestc @ gmail.com */ /* * SPDX-License-Identifier: AGPL-3.0-or-later */ #pragma once #include "bytes.hh" #include #include #include #include #include "redis/exceptions.hh" #include "utils/fmt-compat.hh" namespace redis { class redis_message final { seastar::lw_shared_ptr> _message; public: redis_message() = delete; redis_message(const redis_message&) = delete; redis_message& operator=(const redis_message&) = delete; redis_message(redis_message&& o) noexcept : _message(std::move(o._message)) {} redis_message(lw_shared_ptr> m) noexcept : _message(m) {} static seastar::future ok() { auto m = make_lw_shared> (); m->append_static("+OK\r\n"); return make_ready_future(m); } static seastar::future pong() { auto m = make_lw_shared> (); m->append_static("+PONG\r\n"); return make_ready_future(m); } static seastar::future zero() { auto m = make_lw_shared> (); m->append_static(":0\r\n"); return make_ready_future(m); } static seastar::future one() { auto m = make_lw_shared> (); m->append_static(":1\r\n"); return make_ready_future(m); } static seastar::future nil() { auto m = make_lw_shared> (); m->append_static("$-1\r\n"); return make_ready_future(m); } static seastar::future err() { return zero(); } static seastar::future number(size_t n) { auto m = make_lw_shared> (); m->append(fmt::format(":{}\r\n", n)); return make_ready_future(m); } static seastar::future make_list_result(std::map& list_result) { auto m = make_lw_shared> (); m->append(fmt::format("*{}\r\n", list_result.size() * 2)); for (auto r : list_result) { write_bytes(m, (bytes&)r.first); write_bytes(m, r.second); } return make_ready_future(m); } static seastar::future make_strings_result(bytes result) { auto m = make_lw_shared> (); write_bytes(m, result); return make_ready_future(m); } static seastar::future unknown(const bytes& name) { return from_exception(make_message("-ERR unknown command '{}'\r\n", to_sstring(name))); } static seastar::future exception(const sstring& em) { auto m = make_lw_shared> (); m->append(make_message("-ERR {}\r\n", em)); return make_ready_future(m); } static seastar::future exception(const redis_exception& e) { return exception(e.what_message()); } inline lw_shared_ptr> message() { return _message; } private: static seastar::future from_exception(sstring data) { auto m = make_lw_shared> (); m->append(data); return make_ready_future(m); } template static inline sstring make_message(const char* fmt, Args&&... args) noexcept { try { return fmt::format(fmt::runtime(fmt), std::forward(args)...); } catch (...) { return sstring(); } } static sstring to_sstring(const bytes& b) { return sstring(reinterpret_cast(b.data()), b.size()); } static void write_bytes(lw_shared_ptr> m, bytes& b) { m->append(fmt::format("${}\r\n", b.size())); m->append(std::string_view(reinterpret_cast(b.data()), b.size())); m->append_static("\r\n"); } }; }