#pragma once // Platform framework skeleton for the living example (namespace molo::example::fw): // i18n, gzip negotiation, ETag and Range, health probes, Prometheus export, // structured log ring, W3C trace context, DI registry, flash cookies, // expose stats. Every store has a hard cap; past a cap input is rejected or // the oldest entry is dropped, never grown. // Gap: the real modules are src/cli/i18n, src/runtime/compress, // src/runtime/static/etag.*, src/cli/ops, src/observability, src/app/di, // src/app/views/flash.h and src/realtime/expose/stats.*. #include #include #include #include #include #include #include #include #include "App.hpp" #include "Http.hpp" #include "Observ.hpp" #include "Stats.hpp" namespace molo::example::fw { namespace platform_caps { inline constexpr std::size_t kMaxLocales = 8; inline constexpr std::size_t kMaxMessages = 64; inline constexpr long kMaxPluralN = 1000000; inline constexpr std::size_t kMaxCompressBody = 65536; inline constexpr std::size_t kCompressMin = 256; inline constexpr std::size_t kMaxDocBytes = 4096; inline constexpr std::size_t kMaxChecks = 32; inline constexpr std::size_t kLogRing = 200; inline constexpr std::size_t kLogMessage = 500; inline constexpr std::size_t kMaxServices = 64; inline constexpr std::size_t kFlashBytes = 200; inline constexpr std::size_t kExposeMethods = 16; inline constexpr long kExposeWindowSec = 60; inline constexpr long kExposeBucketSec = 10; } // namespace platform_caps // ---- i18n ----------------------------------------------------------------- class PluralRule { public: // Form index for count n in locale (en/nl/de: 2 forms, fr: 2, ru: 3, ja: 1). static int index(const std::string& locale, long n); static int forms(const std::string& locale); }; class MessageCatalog { public: bool add(const std::string& locale, const std::string& msgid, std::vector forms); // Plural-aware lookup; falls back to the default locale, then the msgid. std::string translate(const std::string& locale, const std::string& msgid, long n = 1) const; std::vector locales() const; bool has_locale(const std::string& locale) const; // gettext .po style dump of one locale. std::string to_po(const std::string& locale) const; void set_default(std::string locale); const std::string& default_locale() const; private: std::map>> data_; std::string default_ = "en"; }; // ?lang beats Accept-Language (q-weighted) beats the default. std::string negotiate_locale(const std::string& lang_param, const std::string& accept_language, const MessageCatalog& catalog); // ---- compression ---------------------------------------------------------- std::uint32_t crc32(const std::string& data); // Valid gzip member using stored deflate blocks (same approach as // src/cli/embed/gzip_stored.cpp). Gap: no real LZ77 (src/runtime/compress/gzip.cpp). std::string gzip_stored(const std::string& data); bool accepts_encoding(const std::string& accept_encoding, const std::string& coding); // ---- conditional GET and ranges ------------------------------------------- std::string make_etag(const std::string& body); // True when If-None-Match (list, weak tags, or *) matches etag. bool etag_matches(const std::string& header, const std::string& etag); struct ByteRange { enum class Kind { None, Ok, Unsatisfiable } kind = Kind::None; std::size_t first = 0; std::size_t last = 0; // inclusive }; // Single range only: "a-b", "a-", "-n". Multi-range is ignored (Kind::None). ByteRange parse_range(const std::string& header, std::size_t size); // ---- health probes -------------------------------------------------------- class HealthRegistry { public: bool add_check(const std::string& name, bool up); bool set_check(const std::string& name, bool up); bool add_startup_task(const std::string& name, bool done); bool set_startup_task(const std::string& name, bool done); bool startup_complete() const; bool ready() const; std::string liveness_json() const; std::string readiness_json() const; std::string startup_json() const; private: mutable std::mutex mu_; std::map checks_; std::map tasks_; std::chrono::steady_clock::time_point started_ = std::chrono::steady_clock::now(); }; // ---- Prometheus ----------------------------------------------------------- class PrometheusExporter { public: PrometheusExporter(const Metrics* metrics, const Stats* stats); // text exposition format 0.0.4: HELP, TYPE, samples. std::string render() const; static std::string sanitize(const std::string& name); private: const Metrics* metrics_; const Stats* stats_; }; // ---- structured logging --------------------------------------------------- enum class LogLevel { Debug = 0, Info = 1, Warn = 2, Error = 3 }; bool parse_level(const std::string& name, LogLevel& out); std::string level_name(LogLevel level); struct LogRecord { unsigned long seq = 0; long ts = 0; LogLevel level = LogLevel::Info; std::string message; std::string correlation_id; }; class LogRing { public: // Redacts secret=value style fields, caps the message, drops the oldest. void log(LogLevel level, std::string message, std::string correlation_id); std::vector last(std::size_t n, LogLevel min) const; void set_min_level(LogLevel level); LogLevel min_level() const; std::size_t size() const; unsigned long dropped_below_min() const; static std::string redact(const std::string& message); static std::string to_json(const LogRecord& record); private: mutable std::mutex mu_; std::deque ring_; LogLevel min_ = LogLevel::Debug; unsigned long next_seq_ = 1; unsigned long filtered_ = 0; }; // ---- trace context -------------------------------------------------------- struct TraceContext { bool had_parent = false; bool parent_valid = true; std::string trace_id; std::string parent_span_id; std::string span_id; std::string flags = "01"; std::string traceparent() const; }; class TraceContextFactory { public: // Continues a valid W3C traceparent, else starts a new trace. TraceContext from_header(const std::string& traceparent); private: std::string next_hex(std::size_t digits); std::mutex mu_; unsigned long long counter_ = 0x1000; }; // ---- DI registry ---------------------------------------------------------- enum class Lifetime { Singleton, Scoped, Transient }; std::string lifetime_name(Lifetime lifetime); class ServiceRegistry { public: bool add(const std::string& name, Lifetime lifetime, std::function factory); // Singleton built once, scoped once per scope key (max 16 kept), transient // on every call. bool resolve(const std::string& name, const std::string& scope, std::string& out); struct Entry { std::string name; Lifetime lifetime; unsigned long created; unsigned long resolved; }; std::vector list() const; private: struct Slot { Lifetime lifetime; std::function factory; std::string instance; std::map scoped; bool built = false; unsigned long created = 0; unsigned long resolved = 0; }; mutable std::mutex mu_; std::map slots_; }; // ---- flash messages ------------------------------------------------------- class FlashCodec { public: static std::string encode(const std::string& message); static bool decode(const std::string& cookie, std::string& message); }; // ---- expose stats --------------------------------------------------------- struct ExposeRow { unsigned long count = 0; unsigned long bytes_up = 0; unsigned long bytes_down = 0; unsigned long micros = 0; double kb_s_up = 0; double kb_s_down = 0; double avg_ms() const { return count ? micros / 1000.0 / count : 0.0; } }; class ExposeStats { public: explicit ExposeStats(long (*now_sec)() = nullptr); bool record(const std::string& method, unsigned long up, unsigned long down, unsigned long micros); // Rows by method plus "_total"; windowed kB/s over the last 60 s. std::map snapshot() const; void set_clock(long (*now_sec)()); static bool known_method(const std::string& method); private: struct Bucket { long slot = -1; unsigned long up = 0; unsigned long down = 0; }; long now() const; mutable std::mutex mu_; long (*clock_)() = nullptr; std::map rows_; std::map> windows_; }; } // namespace molo::example::fw