Files
mtusi2026lab3/src/main.cpp
T
2026-10-23 16:38:27 +03:00

1379 lines
50 KiB
C++

#include "models.hpp"
#include "db.hpp"
#include "auth.hpp"
#include "user_repo.hpp"
#include "chat_repo.hpp"
#include "message_repo.hpp"
#include "redis_pool.hpp"
#include "session_repo.hpp"
#include "pg_session_repo.hpp"
#include "session_repo_base.hpp"
#include "errors.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <regex>
#include <unordered_map>
#include <iostream>
#include <string>
#include <algorithm>
#include <atomic>
#include <functional>
#include <optional>
#include <thread>
#include <csignal>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <cerrno>
#include <cstdio>
#include <sys/time.h>
#include <cstdint>
#include <unordered_set>
#include <nlohmann/json.hpp>
#include <random>
static std::string g_instance_id;
static std::string make_instance_id() {
const char* env = std::getenv("INSTANCE_ID");
if (env && *env) {
return std::string(env);
}
const char* host = std::getenv("HOSTNAME");
if (host && *host) {
return std::string(host);
}
static const char hex[] = "0123456789abcdef";
std::random_device rd;
std::string s(8, '0');
for (auto& c : s) c = hex[rd() & 0xf];
return s;
}
static void send_all(int fd, const std::string& data) {
size_t sent = 0;
while (sent < data.size()) {
const ssize_t n = ::write(fd, data.data() + sent, data.size() - sent);
if (n <= 0) {
return;
}
sent += static_cast<size_t>(n);
}
}
static std::string http_response(int status, const char* reason,
const std::string& request_id,
const std::string& body) {
std::string out;
out += "HTTP/1.1 " + std::to_string(status) + " " + reason + "\r\n";
out += "Content-Type: application/json\r\n";
out += "X-Request-Id: " + request_id + "\r\n";
out += "X-Instance-Id: " + g_instance_id + "\r\n";
out += "Content-Length: " + std::to_string(body.size()) + "\r\n";
out += "Connection: close\r\n";
out += "\r\n";
out += body;
return out;
}
static std::string http_no_content(const std::string& request_id) {
std::string out;
out += "HTTP/1.1 204 No Content\r\n";
out += "X-Request-Id: " + request_id + "\r\n";
out += "X-Instance-Id: " + g_instance_id + "\r\n";
out += "Content-Length: 0\r\n";
out += "Connection: close\r\n";
out += "\r\n";
return out;
}
static const char* status_reason(int status) {
switch (status) {
case 400: return "Bad Request";
case 401: return "Unauthorized";
case 404: return "Not Found";
case 409: return "Conflict";
case 413: return "Payload Too Large";
case 415: return "Unsupported Media Type";
case 500: return "Internal Server Error";
case 503: return "Service Unavailable";
default: return "Error";
}
}
static std::string error_response(int status,
const std::string& code,
const std::string& message,
const std::string& request_id,
const std::string& www_authenticate = "") {
nlohmann::json j;
j["error"]["code"] = code;
j["error"]["message"] = message;
j["error"]["request_id"] = request_id;
const std::string body = j.dump();
std::string head =
"HTTP/1.1 " + std::to_string(status) + " " +
status_reason(status) + "\r\n"
"Content-Type: application/json\r\n"
"X-Request-Id: " + request_id + "\r\n" +
"X-Instance-Id: " + g_instance_id + "\r\n";
if (status == 401 && !www_authenticate.empty()) {
head += "WWW-Authenticate: " + www_authenticate + "\r\n";
}
head += "Content-Length: " + std::to_string(body.size()) + "\r\n";
head += "Connection: close\r\n\r\n";
return head + body;
}
static std::string failure_response(const std::exception& e, const char* what,
const std::string& request_id) {
std::clog << what << " failed: " << e.what() << "\n";
if (is_dependency_failure(e)) {
return error_response(503, "unavailable", "service unavailable", request_id);
}
return error_response(500, "internal_error", "internal error", request_id);
}
static std::optional<nlohmann::json> parse_json_object(const std::string& body) {
nlohmann::json j;
try {
j = nlohmann::json::parse(body);
} catch (const nlohmann::json::exception&) {
return std::nullopt;
}
if (!j.is_object()) {
return std::nullopt;
}
return j;
}
static std::optional<std::string> find_unexpected_key(
const nlohmann::json& j,
std::initializer_list<const char*> allowed) {
for (const auto& [key, value] : j.items()) {
bool ok = false;
for (const char* a : allowed) {
if (key == a) { ok = true; break; }
}
if (!ok) {
return key;
}
}
return std::nullopt;
}
static std::optional<std::string> get_string_field(
const nlohmann::json& j, const char* key) {
auto it = j.find(key);
if (it == j.end() || !it->is_string()) {
return std::nullopt;
}
return it->get<std::string>();
}
static std::optional<std::vector<std::string>> get_string_array(
const nlohmann::json& j, const char* key) {
auto it = j.find(key);
if (it == j.end() || !it->is_array()) {
return std::nullopt;
}
std::vector<std::string> out;
out.reserve(it->size());
for (const auto& item : *it) {
if (!item.is_string()) {
return std::nullopt;
}
out.push_back(item.get<std::string>());
}
return out;
}
static bool parse_request_line(const std::string& first_line,
std::string& method,
std::string& path,
std::string& query) {
query.clear();
const auto sp1 = first_line.find(' ');
if (sp1 == std::string::npos) {
return false;
}
const auto sp2 = first_line.find(' ', sp1 + 1);
if (sp2 == std::string::npos) {
return false;
}
method = first_line.substr(0, sp1);
path = first_line.substr(sp1 + 1, sp2 - sp1 - 1);
const auto q = path.find('?');
if (q != std::string::npos) {
query = path.substr(q + 1);
path.resize(q);
}
return !method.empty() && !path.empty() && path[0] == '/';
}
static bool match_id_path(const std::string& path,
const std::string& prefix,
std::string& id) {
if (path.compare(0, prefix.size(), prefix) != 0) {
return false;
}
id = path.substr(prefix.size());
return !id.empty() && id.find('/') == std::string::npos;
}
static bool match_chat_messages(const std::string& path, std::string& chat_id) {
const std::string prefix = "/api/v1/chats/";
const std::string suffix = "/messages";
if (path.size() <= prefix.size() + suffix.size()) {
return false;
}
if (path.compare(0, prefix.size(), prefix) != 0) {
return false;
}
if (path.compare(path.size() - suffix.size(), suffix.size(), suffix) != 0) {
return false;
}
chat_id = path.substr(prefix.size(),
path.size() - prefix.size() - suffix.size());
return !chat_id.empty() && chat_id.find('/') == std::string::npos;
}
static std::string to_lower(std::string s) {
for (char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return s;
}
static std::optional<size_t> utf8_cps(const std::string& s) {
size_t i = 0;
size_t n = 0;
while (i < s.size()) {
const unsigned char c = static_cast<unsigned char>(s[i]);
size_t w = 1;
if (c >= 0x80) {
if ((c & 0xE0) == 0xC0) w = 2;
else if ((c & 0xF0) == 0xE0) w = 3;
else if ((c & 0xF8) == 0xF0) w = 4;
else return std::nullopt;
if (i + w > s.size()) return std::nullopt;
for (size_t k = 1; k < w; ++k) {
if ((static_cast<unsigned char>(s[i + k]) & 0xC0) != 0x80) {
return std::nullopt;
}
}
}
++n;
i += w;
}
return n;
}
static bool cps_in_range(const std::string& s, size_t lo, size_t hi) {
const auto n = utf8_cps(s);
return n && *n >= lo && *n <= hi;
}
static std::unordered_map<std::string, std::string> parse_headers(
const std::string& request, std::string::size_type after_first_line) {
std::unordered_map<std::string, std::string> headers;
auto pos = after_first_line;
if (pos < request.size() && request.compare(pos, 2, "\r\n") == 0) {
pos += 2;
}
for (;;) {
const auto eol = request.find("\r\n", pos);
if (eol == std::string::npos || eol == pos) {
break;
}
const std::string line = request.substr(pos, eol - pos);
pos = eol + 2;
const auto colon = line.find(':');
if (colon == std::string::npos) {
continue;
}
std::string name = to_lower(line.substr(0, colon));
std::string value = line.substr(colon + 1);
while (!value.empty() && (value[0] == ' ' || value[0] == '\t')) {
value.erase(0, 1);
}
headers[name] = value;
}
return headers;
}
static std::string user_json(const User& user) {
nlohmann::json j;
j["id"] = user.id;
j["username"] = user.username;
j["display_name"] = user.display_name;
j["created_at"] = user.created_at;
return j.dump();
}
static std::string message_json(const Message& msg) {
nlohmann::json j;
j["id"] = msg.id;
j["chat_id"] = msg.chat_id;
j["sender_id"] = msg.sender_id;
j["text"] = msg.text;
j["created_at"] = msg.created_at;
return j.dump();
}
static std::string chat_json(const Chat& chat) {
nlohmann::json j;
j["id"] = chat.id;
j["title"] = chat.title;
j["member_ids"] = chat.member_ids;
j["created_at"] = chat.created_at;
return j.dump();
}
static std::string messages_page_json(const MessagePage& msgs) {
nlohmann::json j;
j["items"] = nlohmann::json::array();
for (const auto& m : msgs.items) {
j["items"].push_back(nlohmann::json::parse(message_json(m)));
}
if (msgs.next_cursor) {
j["next_cursor"] = *msgs.next_cursor;
} else {
j["next_cursor"] = nullptr;
}
return j.dump();
}
static std::string chats_page_json(const ChatPage& page) {
nlohmann::json j;
j["items"] = nlohmann::json::array();
for (const auto& c : page.items) {
j["items"].push_back(nlohmann::json::parse(chat_json(c)));
}
if (page.next_cursor) {
j["next_cursor"] = *page.next_cursor;
} else {
j["next_cursor"] = nullptr;
}
return j.dump();
}
static bool is_json_content_type(const std::string& raw) {
std::string s = to_lower(raw);
const auto sc = s.find(';');
if (sc != std::string::npos) {
s.resize(sc);
}
while (!s.empty() && (s.back() == ' ' || s.back() == '\t')) {
s.pop_back();
}
size_t a = 0;
while (a < s.size() && (s[a] == ' ' || s[a] == '\t')) {
++a;
}
return s.substr(a) == "application/json";
}
static int hex_val(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
static bool json_content_type_ok(
const std::unordered_map<std::string, std::string>& headers) {
const auto it = headers.find("content-type");
return it != headers.end() && is_json_content_type(it->second);
}
static bool contains_nul(const std::string& s) {
return s.find('\0') != std::string::npos;
}
static bool is_unicode_space(uint32_t cp) {
if (cp <= 0x7F) {
return std::isspace(static_cast<unsigned char>(cp)) != 0;
}
if (cp >= 0x2000 && cp <= 0x200A) {
return true;
}
switch (cp) {
case 0x00A0:
case 0x1680:
case 0x2028:
case 0x2029:
case 0x202F:
case 0x205F:
case 0x3000:
case 0xFEFF:
return true;
default:
return false;
}
}
static bool is_blank(const std::string& s) {
size_t i = 0;
while (i < s.size()) {
const unsigned char c = static_cast<unsigned char>(s[i]);
uint32_t cp = c;
size_t w = 1;
if (c >= 0x80) {
if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) {
w = 2;
cp = (static_cast<uint32_t>(c & 0x1F) << 6)
| (static_cast<unsigned char>(s[i + 1]) & 0x3F);
} else if ((c & 0xF0) == 0xE0 && i + 2 < s.size()) {
w = 3;
cp = (static_cast<uint32_t>(c & 0x0F) << 12)
| ((static_cast<unsigned char>(s[i + 1]) & 0x3F) << 6)
| (static_cast<unsigned char>(s[i + 2]) & 0x3F);
} else if ((c & 0xF8) == 0xF0 && i + 3 < s.size()) {
w = 4;
cp = (static_cast<uint32_t>(c & 0x07) << 18)
| ((static_cast<unsigned char>(s[i + 1]) & 0x3F) << 12)
| ((static_cast<unsigned char>(s[i + 2]) & 0x3F) << 6)
| (static_cast<unsigned char>(s[i + 3]) & 0x3F);
} else {
return false;
}
}
if (!is_unicode_space(cp)) {
return false;
}
i += w;
}
return true;
}
static bool valid_username(const std::string& s) {
static const std::regex re("^[a-z0-9_]{3,32}$");
return std::regex_match(s, re);
}
static bool valid_uuid(const std::string& s) {
static const std::regex re(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
return std::regex_match(s, re);
}
static bool valid_idempotency_key(const std::string& s) {
static const std::regex re("^[A-Za-z0-9._:-]{1,128}$");
return std::regex_match(s, re);
}
static bool has_duplicate_ids(const std::vector<std::string>& ids) {
std::unordered_set<std::string> seen;
for (const auto& id : ids) {
if (!seen.insert(to_lower(id)).second) {
return true;
}
}
return false;
}
static std::string url_decode(const std::string& s) {
std::string out;
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '%' && i + 2 < s.size()) {
const int hi = hex_val(s[i + 1]);
const int lo = hex_val(s[i + 2]);
if (hi >= 0 && lo >= 0) {
out.push_back(static_cast<char>((hi << 4) | lo));
i += 2;
continue;
}
}
out.push_back(s[i] == '+' ? ' ' : s[i]);
}
return out;
}
static std::unordered_map<std::string, std::string> parse_query(
const std::string& query) {
std::unordered_map<std::string, std::string> out;
size_t pos = 0;
while (pos < query.size()) {
auto amp = query.find('&', pos);
if (amp == std::string::npos) {
amp = query.size();
}
const auto pair = query.substr(pos, amp - pos);
const auto eq = pair.find('=');
if (eq != std::string::npos) {
out[url_decode(pair.substr(0, eq))] =
url_decode(pair.substr(eq + 1));
}
pos = amp + 1;
}
return out;
}
static std::atomic<int> g_listen{-1};
static std::atomic<bool> g_stop{false};
static std::atomic<bool> g_draining{false};
static std::mutex g_live_mu;
static std::unordered_set<int> g_live;
static void set_timeouts(int fd) {
timeval tv{};
tv.tv_sec = 2;
tv.tv_usec = 0;
::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
}
static void live_add(int fd) {
std::lock_guard<std::mutex> lk(g_live_mu);
g_live.insert(fd);
}
static void live_del(int fd) {
std::lock_guard<std::mutex> lk(g_live_mu);
g_live.erase(fd);
}
static std::string read_request(int client, bool& too_large) {
too_large = false;
std::string request;
char buf[4096];
constexpr std::size_t kMaxBody = 1048576;
for (;;) {
const ssize_t n = ::read(client, buf, sizeof(buf));
if (n < 0) {
if (errno == EINTR) {
continue;
}
return {};
}
if (n == 0) {
return request;
}
request.append(buf, static_cast<size_t>(n));
const auto hdr = request.find("\r\n\r\n");
if (hdr == std::string::npos) {
continue;
}
std::size_t content_length = 0;
const auto cl = to_lower(request).find("content-length:");
if (cl != std::string::npos && cl < hdr) {
const auto line_end = request.find("\r\n", cl);
const auto colon = request.find(':', cl);
if (line_end != std::string::npos && colon < line_end) {
content_length = static_cast<std::size_t>(
std::atoi(request.c_str() + colon + 1));
}
}
if (content_length > kMaxBody) {
too_large = true;
request.resize(hdr + 4);
return request;
}
const auto need = hdr + 4 + content_length;
if (request.size() >= need) {
request.resize(need);
return request;
}
}
}
static std::optional<std::pair<std::string, std::string>> parse_basic_auth(
const std::string& header_value) {
static const std::string prefix = "Basic ";
if (header_value.size() <= prefix.size() ||
header_value.compare(0, prefix.size(), prefix) != 0) {
return std::nullopt;
}
const std::string b64 = header_value.substr(prefix.size());
auto b64_val = [](char c) -> int {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
};
std::string decoded;
int buf = 0, bits = 0;
for (char c : b64) {
if (c == '=') break;
const int v = b64_val(c);
if (v < 0) return std::nullopt;
buf = (buf << 6) | v;
bits += 6;
if (bits >= 8) {
bits -= 8;
decoded.push_back(static_cast<char>((buf >> bits) & 0xFF));
}
}
const auto colon = decoded.find(':');
if (colon == std::string::npos) {
return std::nullopt;
}
return std::make_pair(decoded.substr(0, colon),
decoded.substr(colon + 1));
}
static void handle_client(int client,
std::atomic<unsigned>& request_n,
UserRepo& users,
ChatRepo& chats,
MessageRepo& messages,
ISessionRepo& sessions,
PgPool& pg,
RedisPool* redis) {
bool too_large = false;
const std::string request = read_request(client, too_large);
const unsigned nreq = ++request_n;
const std::string request_id = std::to_string(nreq);
if (too_large) {
send_all(client, error_response(413, "payload_too_large",
"payload too large", request_id));
live_del(client);
::close(client);
return;
}
if (request.empty()) {
live_del(client);
::close(client);
return;
}
const auto line_end = request.find("\r\n");
const std::string first_line = request.substr(0, line_end);
std::string method;
std::string path;
std::string query;
if (!parse_request_line(first_line, method, path, query)) {
send_all(client, error_response(400, "invalid_request",
"bad request line", request_id));
live_del(client);
::close(client);
return;
}
const auto headers = parse_headers(request, line_end);
std::string user_id;
std::string bearer_token;
bool auth_backend_error = false;
{
auto it = headers.find("authorization");
if (it != headers.end()) {
static const std::string prefix = "Bearer ";
const std::string& auth = it->second;
if (auth.size() > prefix.size() &&
auth.compare(0, prefix.size(), prefix) == 0) {
bearer_token = auth.substr(prefix.size());
}
}
if (!bearer_token.empty()) {
try {
auto found = sessions.lookup(bearer_token);
if (found) {
user_id = *found;
}
} catch (const std::exception& e) {
std::clog << "session lookup failed: " << e.what() << "\n";
auth_backend_error = true;
}
}
}
auto send_auth_error = [&]() -> bool {
if (auth_backend_error) {
send_all(client, error_response(503, "unavailable",
"service unavailable", request_id));
return true;
}
if (user_id.empty()) {
send_all(client, error_response(401, "unauthorized",
"unauthorized", request_id,
"Bearer realm=\"messenger\""));
return true;
}
return false;
};
// Сессия может пережить пользователя; недоступная БД — это 503, а не 401.
auto send_user_error = [&]() -> bool {
try {
if (users.find_by_id(user_id)) {
return false;
}
send_all(client, error_response(401, "unauthorized",
"unauthorized", request_id,
"Bearer realm=\"messenger\""));
} catch (const std::exception& e) {
send_all(client, failure_response(e, "find_user", request_id));
}
return true;
};
std::string chat_id;
if (method == "GET" && path == "/health/live") {
send_all(client, http_response(200, "OK", request_id, "{\"status\":\"ok\"}"));
}
else if (method == "GET" && path == "/health/ready") {
if (g_draining.load()) {
send_all(client, error_response(503, "unavailable",
"shutting down", request_id));
} else {
const bool pg_ok = pg.ping();
const bool redis_ok = redis == nullptr || redis->ping();
if (pg_ok && redis_ok) {
send_all(client, http_response(200, "OK", request_id, "{\"status\":\"ok\"}"));
} else {
std::clog << "readiness failed: pg=" << pg_ok
<< " redis=" << redis_ok << "\n";
send_all(client, error_response(503, "unavailable",
"service unavailable", request_id));
}
}
}
else if (method == "POST" && path == "/api/v1/auth/sessions") {
const auto body_at = request.find("\r\n\r\n");
const std::string session_body =
body_at == std::string::npos ? "" : request.substr(body_at + 4);
if (!session_body.empty()) {
send_all(client, error_response(400, "invalid_request",
"body not allowed", request_id));
} else {
auto it = headers.find("authorization");
std::optional<std::pair<std::string, std::string>> creds;
if (it != headers.end()) {
creds = parse_basic_auth(it->second);
}
const auto send_basic_401 = [&]() {
send_all(client, error_response(
401, "unauthorized", "unauthorized", request_id,
"Basic realm=\"messenger\", charset=\"UTF-8\""));
};
if (!creds) {
send_basic_401();
} else {
const auto& username = creds->first;
const auto& password = creds->second;
try {
const auto user = users.find_by_username(username);
if (!user || !verify_password(password, user->password_hash)) {
send_basic_401();
} else {
const auto created = sessions.create(user->id);
nlohmann::json j;
j["token"] = created.token;
j["token_type"] = "Bearer";
const std::time_t t = static_cast<std::time_t>(
created.expires_at);
std::tm tm{};
gmtime_r(&t, &tm);
std::ostringstream out;
out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ");
j["expires_at"] = out.str();
j["user"] = nlohmann::json::parse(user_json(*user));
send_all(client, http_response(201, "Created",
request_id, j.dump()));
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "create_session", request_id));
}
}
}
}
else if (method == "GET" && path == "/api/v1/users/me") {
if (send_auth_error()) {
} else {
try {
const auto user = users.find_by_id(user_id);
if (!user) {
send_all(client, error_response(401, "unauthorized",
"unauthorized", request_id,
"Bearer realm=\"messenger\""));
} else {
send_all(client, http_response(200, "OK", request_id,
user_json(*user)));
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "find_user", request_id));
}
}
}
else if (method == "POST" && path == "/api/v1/users") {
if (!json_content_type_ok(headers)) {
send_all(client, error_response(415, "unsupported_media_type",
"unsupported media type", request_id));
} else {
const auto body_at = request.find("\r\n\r\n");
const std::string body =
body_at == std::string::npos ? "" : request.substr(body_at + 4);
const auto j = parse_json_object(body);
if (!j) {
send_all(client, error_response(400, "invalid_request",
"invalid json", request_id));
} else if (auto bad = find_unexpected_key(
*j, {"username", "display_name", "password"})) {
send_all(client, error_response(400, "invalid_request",
"unexpected field: " + *bad, request_id));
} else {
const auto username = get_string_field(*j, "username");
const auto display_name = get_string_field(*j, "display_name");
const auto password = get_string_field(*j, "password");
if (!username || !display_name || !password) {
send_all(client, error_response(400, "invalid_request",
"invalid fields", request_id));
} else if (!valid_username(*username) ||
contains_nul(*display_name) ||
is_blank(*display_name) ||
!cps_in_range(*display_name, 1, 100)) {
send_all(client, error_response(400, "invalid_request",
"invalid fields", request_id));
} else if (contains_nul(*password) ||
!cps_in_range(*password, 12, 128)) {
send_all(client, error_response(400, "invalid_request",
"invalid password", request_id));
} else {
std::string hash;
try {
hash = hash_password(*password);
} catch (const std::exception& e) {
send_all(client, failure_response(e, "hash_password", request_id));
}
if (!hash.empty()) {
try {
const auto created = users.create(*username,
*display_name, hash);
if (!created) {
send_all(client, error_response(409, "conflict",
"username taken", request_id));
} else {
send_all(client, http_response(201, "Created", request_id,
user_json(*created)));
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "create_user", request_id));
}
}
}
}
}
}
else if (method == "POST" && path == "/api/v1/chats") {
if (send_auth_error()) {
// ответ отправлен
} else if (send_user_error()) {
// ответ отправлен
} else if (!json_content_type_ok(headers)) {
send_all(client, error_response(415, "unsupported_media_type",
"unsupported media type", request_id));
} else {
const auto body_at = request.find("\r\n\r\n");
const std::string body =
body_at == std::string::npos ? "" : request.substr(body_at + 4);
const auto j = parse_json_object(body);
if (!j) {
send_all(client, error_response(400, "invalid_request",
"invalid json", request_id));
} else if (auto bad = find_unexpected_key(*j, {"title", "member_ids"})) {
send_all(client, error_response(400, "invalid_request",
"unexpected field: " + *bad, request_id));
} else {
const auto title = get_string_field(*j, "title");
const auto member_ids = get_string_array(*j, "member_ids");
if (!title || !member_ids) {
send_all(client, error_response(400, "invalid_request",
"invalid fields", request_id));
} else if (contains_nul(*title) || is_blank(*title) ||
!cps_in_range(*title, 1, 100)) {
send_all(client, error_response(400, "invalid_request",
"invalid fields", request_id));
} else if (member_ids->empty() || member_ids->size() > 100) {
send_all(client, error_response(400, "invalid_request",
"invalid members", request_id));
} else if (std::find(member_ids->begin(), member_ids->end(),
user_id) == member_ids->end()) {
send_all(client, error_response(400, "invalid_request",
"caller not in members", request_id));
} else if (!std::all_of(member_ids->begin(), member_ids->end(),
valid_uuid)) {
send_all(client, error_response(400, "invalid_request",
"invalid members", request_id));
} else if (has_duplicate_ids(*member_ids)) {
send_all(client, error_response(400, "invalid_request",
"duplicate members", request_id));
} else {
try {
const auto created = chats.create(*title, *member_ids);
if (!created) {
send_all(client, error_response(400, "invalid_request",
"invalid members", request_id));
} else {
send_all(client, http_response(201, "Created", request_id,
chat_json(*created)));
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "create_chat", request_id));
}
}
}
}
}
else if (method == "POST" && match_chat_messages(path, chat_id)) {
if (send_auth_error()) {
// ответ отправлен
} else if (send_user_error()) {
// ответ отправлен
} else if (!valid_uuid(chat_id)) {
send_all(client, error_response(400, "invalid_request",
"invalid chat id", request_id));
} else {
try {
const auto chat = chats.find_by_id(chat_id);
const bool is_member = chat &&
(std::find(chat->member_ids.begin(),
chat->member_ids.end(),
user_id) != chat->member_ids.end());
if (!is_member) {
send_all(client, error_response(404, "not_found",
"not found", request_id));
} else if (!json_content_type_ok(headers)) {
send_all(client, error_response(415, "unsupported_media_type",
"unsupported media type", request_id));
} else {
const auto body_at = request.find("\r\n\r\n");
const std::string body =
body_at == std::string::npos ? "" : request.substr(body_at + 4);
const auto j = parse_json_object(body);
if (!j) {
send_all(client, error_response(400, "invalid_request",
"invalid json", request_id));
} else if (auto bad = find_unexpected_key(*j, {"text"})) {
send_all(client, error_response(400, "invalid_request",
"unexpected field: " + *bad, request_id));
} else {
const auto text = get_string_field(*j, "text");
if (!text) {
send_all(client, error_response(400, "invalid_request",
"invalid fields", request_id));
} else if (contains_nul(*text) || is_blank(*text) ||
!cps_in_range(*text, 1, 4000)) {
send_all(client, error_response(400, "invalid_request",
"invalid fields", request_id));
} else {
const auto idem = headers.find("idempotency-key");
if (idem == headers.end() ||
!valid_idempotency_key(idem->second)) {
send_all(client, error_response(
400, "invalid_request",
"invalid idempotency key", request_id));
} else {
const auto created = messages.create_idempotent(
chat_id, user_id, *text, idem->second);
if (created.status == CreateResult::Status::NotFound) {
send_all(client, error_response(404, "not_found",
"not found", request_id));
} else if (created.status ==
CreateResult::Status::KeyConflict) {
send_all(client, error_response(
409, "conflict",
"idempotency key reused", request_id));
} else if (!created.message) {
send_all(client, error_response(
500, "internal_error",
"internal error", request_id));
} else {
send_all(client, http_response(
201, "Created", request_id,
message_json(*created.message)));
}
}
}
}
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "post_message", request_id));
}
}
}
else if (method == "GET" && match_chat_messages(path, chat_id)) {
if (send_auth_error()) {
} else if (send_user_error()) {
// ответ отправлен
} else if (!valid_uuid(chat_id)) {
send_all(client, error_response(400, "invalid_request",
"invalid chat id", request_id));
} else {
try {
const auto chat = chats.find_by_id(chat_id);
const bool is_member = chat &&
(std::find(chat->member_ids.begin(),
chat->member_ids.end(),
user_id) != chat->member_ids.end());
if (!is_member) {
send_all(client, error_response(404, "not_found",
"not found", request_id));
} else {
const auto params = parse_query(query);
int limit = 50;
bool bad_limit = false;
if (params.count("limit")) {
try {
std::size_t consumed = 0;
limit = std::stoi(params.at("limit"), &consumed);
if (consumed != params.at("limit").size() ||
limit < 1 || limit > 100) {
bad_limit = true;
}
} catch (...) {
bad_limit = true;
}
}
std::optional<std::string> cursor;
if (params.count("cursor")) {
cursor = params.at("cursor");
}
if (bad_limit || (cursor && cursor->empty())) {
send_all(client, error_response(400, "invalid_request",
"bad query", request_id));
} else {
const auto page = messages.list_page(chat_id, limit, cursor);
if (!page) {
send_all(client, error_response(400, "invalid_request",
"bad cursor", request_id));
} else {
send_all(client, http_response(200, "OK",
request_id,
messages_page_json(*page)));
}
}
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "list_messages", request_id));
}
}
}
else if (method == "GET" && path == "/api/v1/chats") {
if (send_auth_error()) {
// ответ отправлен
} else if (send_user_error()) {
// ответ отправлен
} else {
const auto params = parse_query(query);
int limit = 50;
bool bad_limit = false;
if (params.count("limit")) {
try {
std::size_t consumed = 0;
limit = std::stoi(params.at("limit"), &consumed);
if (consumed != params.at("limit").size() ||
limit < 1 || limit > 100) {
bad_limit = true;
}
} catch (...) {
bad_limit = true;
}
}
std::optional<std::string> cursor;
if (params.count("cursor")) {
cursor = params.at("cursor");
}
if (bad_limit || (cursor && cursor->empty())) {
send_all(client, error_response(400, "invalid_request",
"bad query", request_id));
} else {
try {
const auto page = chats.list_for_user(user_id, limit, cursor);
if (!page) {
send_all(client, error_response(400, "invalid_request",
"bad cursor", request_id));
} else {
send_all(client, http_response(200, "OK", request_id,
chats_page_json(*page)));
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "list_chats", request_id));
}
}
}
}
else if (method == "GET" && match_id_path(path, "/api/v1/chats/", chat_id)) {
if (send_auth_error()) {
// ответ отправлен
} else if (send_user_error()) {
// ответ отправлен
} else if (!valid_uuid(chat_id)) {
send_all(client, error_response(400, "invalid_request",
"invalid chat id", request_id));
} else {
try {
const auto chat = chats.find_by_id(chat_id);
const bool is_member = chat &&
(std::find(chat->member_ids.begin(),
chat->member_ids.end(),
user_id) != chat->member_ids.end());
if (!is_member) {
send_all(client, error_response(404, "not_found",
"not found", request_id));
} else {
send_all(client, http_response(200, "OK", request_id,
chat_json(*chat)));
}
} catch (const std::exception& e) {
send_all(client, failure_response(e, "find_chat", request_id));
}
}
} else if (method == "DELETE" && path == "/api/v1/auth/sessions/current") {
if (send_auth_error()) {
} else {
try {
sessions.revoke(bearer_token);
send_all(client, http_no_content(request_id));
} catch (const std::exception& e) {
send_all(client, failure_response(e, "revoke_session", request_id));
}
}
}
else {
send_all(client, error_response(404, "not_found", "not found", request_id));
}
live_del(client);
::close(client);
}
int main() {
const char* host_env = std::getenv("APP_HOST");
const char* port_env = std::getenv("APP_PORT");
const char* host = host_env ? host_env : "0.0.0.0";
const int port = port_env ? std::atoi(port_env) : 8080;
g_instance_id = make_instance_id();
std::clog << "instance id: " << g_instance_id << "\n";
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGTERM);
sigaddset(&set, SIGINT);
if (pthread_sigmask(SIG_BLOCK, &set, nullptr) != 0) {
std::cerr << "pthread_sigmask failed" << std::endl;
return 1;
}
const std::string db_url = read_secret_file("DATABASE_URL_FILE");
std::clog << "connecting to db...\n";
{
auto conn = open_pg_connection(db_url, false);
std::clog << "applying migrations...\n";
apply_migrations(*conn, "./migrations");
std::clog << "migrations ok\n";
}
PgPool pool(db_url, 32);
std::clog << "pg pool ready (32 connections)\n";
UserRepo users(pool);
ChatRepo chats(pool);
MessageRepo messages(pool);
const char* ttl_env = std::getenv("SESSION_TTL_SECONDS");
const int ttl_seconds = ttl_env ? std::atoi(ttl_env) : 3600;
const char* store_env = std::getenv("SESSION_STORE");
const std::string store = store_env ? store_env : "redis";
std::unique_ptr<RedisPool> redis_pool;
std::unique_ptr<ISessionRepo> sessions;
if (store == "postgres") {
sessions = std::make_unique<PgSessionRepo>(pool, ttl_seconds);
std::clog << "session store: postgres\n";
} else if (store == "redis") {
redis_pool = std::make_unique<RedisPool>(read_secret_file("CACHE_URL_FILE"), 4);
std::clog << "redis pool ready (4 connections)\n";
sessions = std::make_unique<SessionRepo>(*redis_pool, ttl_seconds);
std::clog << "session store: redis\n";
} else {
throw std::runtime_error("unknown SESSION_STORE: " + store);
}
std::clog << "session ttl: " << ttl_seconds << "s\n";
const int fd = ::socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) {
std::cerr << "socket failed" << std::endl;
return 1;
}
const int yes = 1;
::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(static_cast<uint16_t>(port));
if (::inet_pton(AF_INET, host, &addr.sin_addr) != 1) {
std::cerr << "invalid APP_HOST" << std::endl;
::close(fd);
return 1;
}
if (::bind(fd, reinterpret_cast<sockaddr*>(&addr), sizeof(addr)) != 0) {
std::cerr << "bind failed on " << host << ":" << port << std::endl;
::close(fd);
return 1;
}
if (::listen(fd, 16) != 0) {
std::cerr << "listen failed" << std::endl;
::close(fd);
return 1;
}
g_listen.store(fd);
std::clog << "listening on " << host << ":" << port << std::endl;
std::atomic<unsigned> request_n{0};
std::mutex q_mu;
std::condition_variable q_cv;
std::queue<int> q;
const int workers_n = 32;
std::vector<std::thread> workers;
for (int i = 0; i < workers_n; ++i) {
workers.emplace_back([&]() {
for (;;) {
int client = -1;
{
std::unique_lock<std::mutex> lk(q_mu);
q_cv.wait(lk, [&]() { return g_stop.load() || !q.empty(); });
if (g_stop.load() && q.empty()) {
return;
}
client = q.front();
q.pop();
}
try {
handle_client(client, request_n, users, chats, messages, *sessions, pool, redis_pool.get());
} catch (const std::exception& e) {
std::clog << "unhandled request error: " << e.what() << "\n";
send_all(client, error_response(500, "internal_error",
"internal error",
std::to_string(request_n.load())));
live_del(client);
::close(client);
} catch (...) {
live_del(client);
::close(client);
}
}
});
}
std::thread signal_thread([&]() {
int sig = 0;
if (sigwait(&set, &sig) != 0) {
return;
}
g_draining.store(true);
int drain_seconds = 2;
if (const char* env = std::getenv("DRAIN_SECONDS")) {
if (*env) {
drain_seconds = std::atoi(env);
if (drain_seconds < 0) {
drain_seconds = 0;
} else if (drain_seconds > 30) {
drain_seconds = 30;
}
}
}
std::clog << "draining: /health/ready is 503 for "
<< drain_seconds << "s before listen socket closes\n";
if (drain_seconds > 0) {
::sleep(static_cast<unsigned>(drain_seconds));
}
g_stop.store(true);
const int lfd = g_listen.load();
if (lfd >= 0) {
::shutdown(lfd, SHUT_RDWR);
}
});
for (;;) {
const int client = ::accept(fd, nullptr, nullptr);
if (client < 0) {
if (g_stop.load()) {
std::clog << "shutting down\n";
break;
}
std::cerr << "accept failed\n";
break;
}
set_timeouts(client);
live_add(client);
{
std::lock_guard<std::mutex> lk(q_mu);
q.push(client);
}
q_cv.notify_one();
}
{
std::lock_guard<std::mutex> lk(q_mu);
g_stop.store(true);
}
q_cv.notify_all();
for (auto& t : workers) {
t.join();
}
signal_thread.detach();
::close(fd);
std::clog << "stopped\n";
return 0;
}