feat: implement MoloApp plans 01-15 with integration
Full C++23 framework tree: runtime, observability, security, data, app, realtime, supervisor, clients, CLI, example plus enterprise tenancy, audit, operability, governance, supplychain. Postgres via docker compose for tests.
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
// Minimal CHECK harness. Each test file registers TEST cases and ends with
|
||||
// TEST_MAIN(). Prints one PASS/FAIL line per case, exit 0 when all pass.
|
||||
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace mini {
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
std::function<void()> fn;
|
||||
};
|
||||
|
||||
inline std::vector<Case>& Registry() {
|
||||
static std::vector<Case> r;
|
||||
return r;
|
||||
}
|
||||
|
||||
inline int& Failures() {
|
||||
static int f = 0;
|
||||
return f;
|
||||
}
|
||||
|
||||
inline void Register(std::string name, std::function<void()> fn) {
|
||||
Registry().push_back(Case{std::move(name), std::move(fn)});
|
||||
}
|
||||
|
||||
inline void Check(bool cond, const char* expr, const char* file, int line) {
|
||||
if (!cond) {
|
||||
++Failures();
|
||||
std::cerr << "FAIL " << file << ":" << line << ": " << expr << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace mini
|
||||
|
||||
#define CHECK(cond) ::mini::Check(static_cast<bool>(cond), #cond, __FILE__, __LINE__)
|
||||
#define CHECK_EQ(a, b) ::mini::Check(((a) == (b)), #a " == " #b, __FILE__, __LINE__)
|
||||
#define CHECK_NE(a, b) ::mini::Check(((a) != (b)), #a " != " #b, __FILE__, __LINE__)
|
||||
|
||||
#define TEST(name) \
|
||||
static void name(); \
|
||||
static bool _reg_##name = ([]() { \
|
||||
::mini::Register(#name, &name); \
|
||||
return true; \
|
||||
})(); \
|
||||
static void name()
|
||||
|
||||
#define TEST_MAIN() \
|
||||
int main() { \
|
||||
for (auto& c : ::mini::Registry()) { \
|
||||
int before = ::mini::Failures(); \
|
||||
c.fn(); \
|
||||
std::cout << (before == ::mini::Failures() ? "PASS " \
|
||||
: "FAIL ") \
|
||||
<< c.name << "\n"; \
|
||||
} \
|
||||
return ::mini::Failures() == 0 ? 0 : 1; \
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// Bridge: per-database isolation, cross-file transaction refusal, txn
|
||||
// commit/rollback staging, and open caps.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/bridge.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::DatabaseBridge;
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(per_db_isolation) {
|
||||
DatabaseBridge b("/var/molo/tenants");
|
||||
CHECK(b.open("acme"));
|
||||
CHECK(b.open("globex"));
|
||||
CHECK(b.file_for("acme") == "/var/molo/tenants/acme.db");
|
||||
CHECK(b.put("acme", "theme", "dark"));
|
||||
CHECK(b.put("globex", "theme", "light"));
|
||||
CHECK(b.get("acme", "theme") == "dark");
|
||||
CHECK(b.get("globex", "theme") == "light");
|
||||
CHECK(!b.get("acme", "missing").has_value());
|
||||
CHECK(!b.put("unknown", "k", "v"));
|
||||
CHECK(!b.get("unknown", "k").has_value());
|
||||
CHECK(!b.open("Bad Slug!!"));
|
||||
}
|
||||
|
||||
TEST(txn_commit_rollback) {
|
||||
DatabaseBridge b("/var/molo/tenants");
|
||||
CHECK(b.open("acme"));
|
||||
auto t = b.begin("acme");
|
||||
CHECK(t.active());
|
||||
CHECK(t.put("k", "staged"));
|
||||
CHECK(t.get("k") == "staged");
|
||||
CHECK(!b.get("acme", "k").has_value());
|
||||
CHECK(t.commit());
|
||||
CHECK(!t.active());
|
||||
CHECK(b.get("acme", "k") == "staged");
|
||||
auto t2 = b.begin("acme");
|
||||
CHECK(t2.put("k2", "nope"));
|
||||
t2.rollback();
|
||||
CHECK(!b.get("acme", "k2").has_value());
|
||||
auto missing = b.begin("ghost");
|
||||
CHECK(!missing.active());
|
||||
}
|
||||
|
||||
TEST(cross_file_txn_refused) {
|
||||
DatabaseBridge b("/var/molo/tenants");
|
||||
CHECK(b.open("acme"));
|
||||
CHECK(b.open("globex"));
|
||||
auto same = b.begin2("acme", "acme");
|
||||
CHECK(same.active());
|
||||
bool threw = false;
|
||||
try {
|
||||
auto cross = b.begin2("acme", "globex");
|
||||
} catch (const DatabaseBridge::CrossFileError&) {
|
||||
threw = true;
|
||||
}
|
||||
CHECK(threw);
|
||||
}
|
||||
|
||||
TEST(open_caps) {
|
||||
DatabaseBridge b("/var/molo/tenants");
|
||||
for (int i = 0; i < 1024; ++i) {
|
||||
CHECK(b.open("d" + std::to_string(i)));
|
||||
}
|
||||
CHECK_EQ(b.db_count(), 1024u);
|
||||
CHECK_EQ(b.file_count(), 2048u);
|
||||
CHECK(!b.open("one-too-many"));
|
||||
CHECK_EQ(b.db_count(), 1024u);
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
@@ -0,0 +1,76 @@
|
||||
// Feature flags: defaults, tenant overrides, unknown reads false, 256 cap.
|
||||
// Config overlay: global plus tenant precedence, typed getters, key cap.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/config_overlay.h"
|
||||
#include "tenancy/feature_flags.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::ConfigOverlay;
|
||||
using molo::tenancy::FeatureFlags;
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(flags_defaults_and_overrides) {
|
||||
FeatureFlags f;
|
||||
CHECK(f.define("new_ui", false));
|
||||
CHECK(f.define("fast_path", true));
|
||||
CHECK(!f.enabled("acme", "new_ui"));
|
||||
CHECK(f.enabled("acme", "fast_path"));
|
||||
CHECK(f.set_tenant("acme", "new_ui", true));
|
||||
CHECK(f.enabled("acme", "new_ui"));
|
||||
CHECK(!f.enabled("globex", "new_ui"));
|
||||
CHECK(f.set_tenant("acme", "fast_path", false));
|
||||
CHECK(!f.enabled("acme", "fast_path"));
|
||||
CHECK(!f.enabled("acme", "undefined_flag"));
|
||||
CHECK(!f.set_tenant("acme", "undefined_flag", true));
|
||||
}
|
||||
|
||||
TEST(flags_cap) {
|
||||
FeatureFlags f;
|
||||
for (int i = 0; i < 256; ++i) {
|
||||
CHECK(f.define("flag" + std::to_string(i), false));
|
||||
}
|
||||
CHECK_EQ(f.count(), 256u);
|
||||
CHECK(!f.define("flag256", false));
|
||||
CHECK(f.define("flag0", true));
|
||||
CHECK(f.enabled("acme", "flag0"));
|
||||
}
|
||||
|
||||
TEST(config_precedence_and_typed) {
|
||||
ConfigOverlay c;
|
||||
c.set_global("timeout", "30");
|
||||
c.set_global("debug", "false");
|
||||
CHECK(c.get("acme", "timeout", "?") == "30");
|
||||
CHECK(c.get("acme", "missing", "fb") == "fb");
|
||||
CHECK(c.set_tenant("acme", "timeout", "5"));
|
||||
CHECK(c.get("acme", "timeout", "?") == "5");
|
||||
CHECK(c.get("globex", "timeout", "?") == "30");
|
||||
CHECK_EQ(c.get_int("acme", "timeout", 99), 5);
|
||||
CHECK_EQ(c.get_int("globex", "timeout", 99), 30);
|
||||
CHECK_EQ(c.get_int("acme", "missing", 99), 99);
|
||||
CHECK(c.set_tenant("acme", "bad_int", "12x"));
|
||||
CHECK_EQ(c.get_int("acme", "bad_int", 99), 99);
|
||||
CHECK(!c.get_bool("acme", "debug", true));
|
||||
CHECK(c.set_tenant("acme", "debug", "yes"));
|
||||
CHECK(c.get_bool("acme", "debug", false));
|
||||
CHECK(c.get_bool("acme", "missing", true));
|
||||
CHECK(c.clear_tenant("acme"));
|
||||
CHECK(c.get("acme", "timeout", "?") == "30");
|
||||
CHECK(!c.clear_tenant("acme"));
|
||||
}
|
||||
|
||||
TEST(config_key_cap) {
|
||||
ConfigOverlay c;
|
||||
for (int i = 0; i < 1024; ++i) {
|
||||
CHECK(c.set_tenant("acme", "k" + std::to_string(i), "v"));
|
||||
}
|
||||
CHECK(!c.set_tenant("acme", "k1024", "v"));
|
||||
CHECK(c.set_tenant("acme", "k0", "v2"));
|
||||
CHECK(c.get("acme", "k0", "") == "v2");
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
@@ -0,0 +1,47 @@
|
||||
// Tenant metrics: 512 tenants keep labels, the 513th folds into "other",
|
||||
// counts accumulate per label.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/metrics.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::TenantMetrics;
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(label_allowlist) {
|
||||
TenantMetrics m;
|
||||
for (int i = 0; i < 512; ++i) {
|
||||
std::string slug = "t" + std::to_string(i);
|
||||
CHECK(m.label_for(slug) == slug);
|
||||
}
|
||||
CHECK(m.label_for("t512") == "other");
|
||||
CHECK(m.label_for("t999") == "other");
|
||||
CHECK(m.label_for("t0") == "t0");
|
||||
CHECK(m.label_for("other") == "other");
|
||||
}
|
||||
|
||||
TEST(counts_fold_into_other) {
|
||||
TenantMetrics m;
|
||||
for (int i = 0; i < 512; ++i) m.label_for("t" + std::to_string(i));
|
||||
m.record_request("t0");
|
||||
m.record_request("t0");
|
||||
m.record_error("t0");
|
||||
m.record_request("late-a");
|
||||
m.record_request("late-b");
|
||||
m.record_error("late-c");
|
||||
auto snap = m.snapshot();
|
||||
CHECK_EQ(snap["t0"].requests, 2u);
|
||||
CHECK_EQ(snap["t0"].errors, 1u);
|
||||
CHECK_EQ(snap["other"].requests, 2u);
|
||||
CHECK_EQ(snap["other"].errors, 1u);
|
||||
std::uint64_t total = 0;
|
||||
for (const auto& [label, c] : snap) total += c.requests + c.errors;
|
||||
CHECK_EQ(total, 6u);
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
@@ -0,0 +1,151 @@
|
||||
// Pool scope: two tenants across pg and sqlite checkouts, GUC set/reset,
|
||||
// dirty slot refusal, registry cap, 100k checkout leak check, ORM scoping
|
||||
// and RLS proof strings.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/adapters/db.h"
|
||||
#include "tenancy/orm_scope.h"
|
||||
#include "tenancy/pool_factory.h"
|
||||
#include "tenancy/rls_policy.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::adapters::db::Backend;
|
||||
using molo::tenancy::adapters::db::DbError;
|
||||
using molo::tenancy::OrmScope;
|
||||
using molo::tenancy::PoolFactory;
|
||||
using molo::tenancy::RlsPolicy;
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(two_tenant_checkout_both_backends) {
|
||||
PoolFactory f;
|
||||
{
|
||||
auto a = f.acquire("acme", Backend::Postgres);
|
||||
CHECK(a.active());
|
||||
CHECK(a.slug() == "acme");
|
||||
CHECK(a.guc() == "acme");
|
||||
CHECK_EQ(f.active_count(), 1u);
|
||||
auto b = f.acquire("globex", Backend::Sqlite);
|
||||
CHECK(b.guc() == "globex");
|
||||
CHECK(b.backend() == Backend::Sqlite);
|
||||
CHECK_EQ(f.active_count(), 2u);
|
||||
}
|
||||
CHECK_EQ(f.active_count(), 0u);
|
||||
CHECK_EQ(f.tenant_count(), 2u);
|
||||
auto c = f.acquire("globex", Backend::Postgres);
|
||||
CHECK(c.guc() == "globex");
|
||||
c.release();
|
||||
CHECK(!c.active());
|
||||
CHECK_EQ(f.active_count(), 0u);
|
||||
}
|
||||
|
||||
TEST(dirty_slot_refused) {
|
||||
PoolFactory f;
|
||||
{
|
||||
auto a = f.acquire("acme", Backend::Postgres);
|
||||
}
|
||||
CHECK_EQ(f.slot_count(), 1u);
|
||||
f.DebugDirtySlotForTest(0, "stale-tenant");
|
||||
bool threw = false;
|
||||
try {
|
||||
auto b = f.acquire("globex", Backend::Postgres);
|
||||
} catch (const DbError& e) {
|
||||
threw = true;
|
||||
CHECK(e.code() == "scope_dirty");
|
||||
}
|
||||
CHECK(threw);
|
||||
f.DebugDirtySlotForTest(0, "");
|
||||
auto c = f.acquire("globex", Backend::Postgres);
|
||||
CHECK(c.guc() == "globex");
|
||||
}
|
||||
|
||||
TEST(invalid_slug_rejected) {
|
||||
PoolFactory f;
|
||||
bool threw = false;
|
||||
try {
|
||||
auto a = f.acquire("Bad Slug!!", Backend::Postgres);
|
||||
} catch (const DbError& e) {
|
||||
threw = true;
|
||||
CHECK(e.code() == "invalid_tenant");
|
||||
}
|
||||
CHECK(threw);
|
||||
CHECK_EQ(f.tenant_count(), 0u);
|
||||
}
|
||||
|
||||
TEST(registry_cap) {
|
||||
PoolFactory f;
|
||||
for (int i = 0; i < 100000; ++i) {
|
||||
auto l = f.acquire("t" + std::to_string(i), Backend::Postgres);
|
||||
}
|
||||
CHECK_EQ(f.tenant_count(), 100000u);
|
||||
CHECK_EQ(f.active_count(), 0u);
|
||||
bool threw = false;
|
||||
try {
|
||||
auto l = f.acquire("one-too-many", Backend::Postgres);
|
||||
} catch (const DbError& e) {
|
||||
threw = true;
|
||||
CHECK(e.code() == "too_many_tenants");
|
||||
}
|
||||
CHECK(threw);
|
||||
}
|
||||
|
||||
TEST(checkout_leak_loop) {
|
||||
PoolFactory f;
|
||||
for (int i = 0; i < 100000; ++i) {
|
||||
auto a = f.acquire(i % 2 == 0 ? "acme" : "globex",
|
||||
i % 3 == 0 ? Backend::Sqlite : Backend::Postgres);
|
||||
CHECK(a.guc() == (i % 2 == 0 ? "acme" : "globex"));
|
||||
}
|
||||
CHECK_EQ(f.active_count(), 0u);
|
||||
CHECK_EQ(f.tenant_count(), 2u);
|
||||
CHECK(f.slot_count() <= 4u);
|
||||
}
|
||||
|
||||
TEST(orm_scope_injection) {
|
||||
std::string scoped = OrmScope::ApplySelect("SELECT * FROM orders", "acme", false);
|
||||
CHECK(scoped.find("tenant_id = 'acme'") != std::string::npos);
|
||||
std::string with_where =
|
||||
OrmScope::ApplySelect("SELECT * FROM orders WHERE total > 10", "acme", false);
|
||||
CHECK(with_where.find("WHERE tenant_id = 'acme' AND") != std::string::npos);
|
||||
std::string with_order =
|
||||
OrmScope::ApplySelect("SELECT * FROM orders ORDER BY id", "acme", false);
|
||||
CHECK(with_order.find("WHERE tenant_id = 'acme'") != std::string::npos);
|
||||
CHECK(with_order.find("ORDER BY") != std::string::npos);
|
||||
std::string upd =
|
||||
OrmScope::ApplyUpdate("UPDATE orders SET total = 1", "acme", false);
|
||||
CHECK(upd.find("tenant_id = 'acme'") != std::string::npos);
|
||||
std::string priv = OrmScope::ApplySelect("SELECT * FROM orders", "acme", true);
|
||||
CHECK(priv == "SELECT * FROM orders");
|
||||
std::string already =
|
||||
OrmScope::ApplySelect("SELECT * FROM orders WHERE tenant_id = 'x'", "acme", false);
|
||||
CHECK(already.find("AND") == std::string::npos);
|
||||
std::string ins = OrmScope::InsertWithTenant("orders", "total", "?", "acme");
|
||||
CHECK(ins.find("tenant_id") != std::string::npos);
|
||||
CHECK(ins.find("'acme'") != std::string::npos);
|
||||
CHECK(OrmScope::KeyPrefix("acme") == "tenant:acme:");
|
||||
CHECK(OrmScope::ScopedChannel("acme", "events") == "tenant:acme:events");
|
||||
std::string quote = OrmScope::FilterClause("o'brien");
|
||||
CHECK(quote == "tenant_id = 'o''brien'");
|
||||
}
|
||||
|
||||
TEST(rls_proof) {
|
||||
PoolFactory f;
|
||||
auto lease = f.acquire("acme", Backend::Postgres);
|
||||
std::string set_local = RlsPolicy::SetLocal(lease.guc());
|
||||
CHECK(set_local == "SET LOCAL app.current_tenant = 'acme'");
|
||||
std::string scoped = OrmScope::ApplySelect("SELECT * FROM orders", lease.guc(), false);
|
||||
CHECK(scoped.find("tenant_id = 'acme'") != std::string::npos);
|
||||
CHECK(RlsPolicy::ResetLocal() == "RESET app.current_tenant");
|
||||
std::string policy = RlsPolicy::PolicyDdl("orders");
|
||||
CHECK(policy.find("current_setting('app.current_tenant', true)") != std::string::npos);
|
||||
CHECK(policy.find("tenant_id") != std::string::npos);
|
||||
CHECK(RlsPolicy::EnableRls("orders").find("ENABLE ROW LEVEL SECURITY") !=
|
||||
std::string::npos);
|
||||
lease.release();
|
||||
CHECK(lease.guc() == "");
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
@@ -0,0 +1,194 @@
|
||||
// Provisioner: happy path, duplicate/invalid rejection, hook rollback,
|
||||
// tombstone and purge gates. DbCatalog round trip over a test-local fake
|
||||
// Connection emulating the tenants table.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/adapters/db.h"
|
||||
#include "tenancy/catalog.h"
|
||||
#include "tenancy/provisioner.h"
|
||||
#include "tenancy/store/db_catalog.h"
|
||||
#include "tenancy/store/memory_catalog.h"
|
||||
#include "tenancy/strategy.h"
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::adapters::db::Backend;
|
||||
using molo::tenancy::adapters::db::BoundStatement;
|
||||
using molo::tenancy::adapters::db::Connection;
|
||||
using molo::tenancy::adapters::db::Context;
|
||||
using molo::tenancy::adapters::db::Result;
|
||||
using molo::tenancy::adapters::db::Row;
|
||||
using molo::tenancy::adapters::db::Value;
|
||||
using molo::tenancy::Catalog;
|
||||
using molo::tenancy::Provisioner;
|
||||
using molo::tenancy::PurgeResult;
|
||||
using molo::tenancy::Strategy;
|
||||
using molo::tenancy::Tenant;
|
||||
|
||||
class FakeConnection : public Connection {
|
||||
public:
|
||||
Result exec(const Context&, const BoundStatement& stmt) override {
|
||||
const std::string& sql = stmt.sql();
|
||||
if (sql.rfind("CREATE TABLE", 0) == 0) return Result{};
|
||||
if (sql.rfind("UPDATE tenants", 0) == 0) {
|
||||
std::string id = molo::tenancy::adapters::db::AsString(stmt.params()[6]);
|
||||
auto it = rows_.find(id);
|
||||
if (it == rows_.end()) return Result{};
|
||||
it->second["slug"] = stmt.params()[0];
|
||||
it->second["strategy"] = stmt.params()[1];
|
||||
it->second["status"] = stmt.params()[2];
|
||||
it->second["storage_bytes"] = stmt.params()[3];
|
||||
it->second["created_unix"] = stmt.params()[4];
|
||||
it->second["tombstoned_unix"] = stmt.params()[5];
|
||||
Result r;
|
||||
r.affected = 1;
|
||||
return r;
|
||||
}
|
||||
if (sql.rfind("INSERT INTO tenants", 0) == 0) {
|
||||
Row row;
|
||||
row["id"] = stmt.params()[0];
|
||||
row["slug"] = stmt.params()[1];
|
||||
row["strategy"] = stmt.params()[2];
|
||||
row["status"] = stmt.params()[3];
|
||||
row["storage_bytes"] = stmt.params()[4];
|
||||
row["created_unix"] = stmt.params()[5];
|
||||
row["tombstoned_unix"] = stmt.params()[6];
|
||||
rows_[molo::tenancy::adapters::db::AsString(stmt.params()[0])] = row;
|
||||
Result r;
|
||||
r.affected = 1;
|
||||
return r;
|
||||
}
|
||||
if (sql.rfind("SELECT ", 0) == 0) {
|
||||
Result r;
|
||||
if (sql.find("WHERE id=?") != std::string::npos) {
|
||||
auto it = rows_.find(molo::tenancy::adapters::db::AsString(stmt.params()[0]));
|
||||
if (it != rows_.end()) r.rows.push_back(it->second);
|
||||
return r;
|
||||
}
|
||||
if (sql.find("WHERE slug=?") != std::string::npos) {
|
||||
std::string slug = molo::tenancy::adapters::db::AsString(stmt.params()[0]);
|
||||
for (const auto& [id, row] : rows_) {
|
||||
if (molo::tenancy::adapters::db::AsString(row.at("slug")) == slug) {
|
||||
r.rows.push_back(row);
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
std::vector<std::string> ids;
|
||||
for (const auto& [id, row] : rows_) ids.push_back(id);
|
||||
std::sort(ids.begin(), ids.end());
|
||||
long limit = molo::tenancy::adapters::db::AsInt(stmt.params()[0]);
|
||||
for (const auto& id : ids) {
|
||||
if (static_cast<long>(r.rows.size()) >= limit) break;
|
||||
r.rows.push_back(rows_.at(id));
|
||||
}
|
||||
return r;
|
||||
}
|
||||
if (sql.rfind("DELETE FROM tenants", 0) == 0) {
|
||||
Result r;
|
||||
r.affected = rows_.erase(molo::tenancy::adapters::db::AsString(stmt.params()[0])) > 0 ? 1 : 0;
|
||||
return r;
|
||||
}
|
||||
return Result{};
|
||||
}
|
||||
void prepare(const std::string&, const std::string&) override {}
|
||||
Result exec_prepared(const Context&, const std::string&, const std::vector<Value>&) override {
|
||||
return Result{};
|
||||
}
|
||||
bool ping() override { return true; }
|
||||
void close() override {}
|
||||
Backend backend() const override { return Backend::Postgres; }
|
||||
|
||||
private:
|
||||
std::map<std::string, Row> rows_;
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(provision_happy_path) {
|
||||
Catalog cat(std::make_unique<molo::tenancy::store::MemoryCatalog>());
|
||||
int created = 0;
|
||||
Provisioner::Hooks hooks;
|
||||
hooks.on_create = [&created](const Tenant&) { ++created; return true; };
|
||||
Provisioner p(cat, hooks);
|
||||
auto t = p.provision("acme", Strategy::SharedSchema, 1000);
|
||||
CHECK(t.has_value());
|
||||
CHECK_EQ(created, 1);
|
||||
CHECK(t->id() == "ten-acme");
|
||||
CHECK(cat.find_by_slug("acme").has_value());
|
||||
CHECK(!p.provision("acme", Strategy::SharedSchema, 1000).has_value());
|
||||
CHECK(!p.provision("Bad Slug!!", Strategy::SharedSchema, 1000).has_value());
|
||||
}
|
||||
|
||||
TEST(provision_hook_failure_rolls_back) {
|
||||
Catalog cat(std::make_unique<molo::tenancy::store::MemoryCatalog>());
|
||||
int dropped = 0;
|
||||
Provisioner::Hooks hooks;
|
||||
hooks.on_create = [](const Tenant&) { return false; };
|
||||
hooks.on_drop = [&dropped](const Tenant&) { ++dropped; return true; };
|
||||
Provisioner p(cat, hooks);
|
||||
CHECK(!p.provision("acme", Strategy::SharedSchema, 1000).has_value());
|
||||
CHECK_EQ(dropped, 1);
|
||||
CHECK(!cat.find_by_slug("acme").has_value());
|
||||
CHECK(cat.list(10).empty());
|
||||
}
|
||||
|
||||
TEST(rollback_removes_tenant) {
|
||||
Catalog cat(std::make_unique<molo::tenancy::store::MemoryCatalog>());
|
||||
Provisioner p(cat);
|
||||
CHECK(p.provision("acme", Strategy::SharedSchema, 1000).has_value());
|
||||
CHECK(p.rollback("acme", 1001));
|
||||
CHECK(!cat.find_by_slug("acme").has_value());
|
||||
CHECK(!p.rollback("ghost", 1001));
|
||||
}
|
||||
|
||||
TEST(purge_gates) {
|
||||
Catalog cat(std::make_unique<molo::tenancy::store::MemoryCatalog>());
|
||||
int dropped = 0;
|
||||
Provisioner::Hooks hooks;
|
||||
hooks.on_drop = [&dropped](const Tenant&) { ++dropped; return true; };
|
||||
Provisioner p(cat, hooks);
|
||||
CHECK(p.provision("acme", Strategy::SharedSchema, 1000).has_value());
|
||||
CHECK(p.purge("acme", "PURGE:ten-acme", 2000, 100) == PurgeResult::NotTombstone);
|
||||
CHECK_EQ(dropped, 0);
|
||||
CHECK(p.tombstone("acme", 1500));
|
||||
CHECK(p.purge("acme", "PURGE:ten-acme", 1550, 100) == PurgeResult::RetentionHold);
|
||||
CHECK(p.purge("acme", "wrong", 1700, 100) == PurgeResult::BadConfirm);
|
||||
CHECK(p.purge("acme", "PURGE:ten-acme", 1700, 100) == PurgeResult::Ok);
|
||||
CHECK_EQ(dropped, 1);
|
||||
CHECK(!cat.find_by_slug("acme").has_value());
|
||||
CHECK(p.purge("acme", "PURGE:ten-acme", 9999, 100) == PurgeResult::NotFound);
|
||||
}
|
||||
|
||||
TEST(db_catalog_round_trip) {
|
||||
FakeConnection conn;
|
||||
molo::tenancy::store::DbCatalog db(conn);
|
||||
db.ensure_schema();
|
||||
Tenant t("ten-acme", "acme", Strategy::SchemaPerTenant,
|
||||
molo::tenancy::TenantStatus::Active, 10, 1000, 0);
|
||||
CHECK(db.upsert(t));
|
||||
auto by_id = db.get_by_id("ten-acme");
|
||||
CHECK(by_id.has_value());
|
||||
CHECK(by_id->slug() == "acme");
|
||||
CHECK(by_id->strategy() == Strategy::SchemaPerTenant);
|
||||
CHECK(by_id->storage_bytes() == 10);
|
||||
auto by_slug = db.get_by_slug("acme");
|
||||
CHECK(by_slug.has_value());
|
||||
CHECK(by_slug->id() == "ten-acme");
|
||||
t.suspend();
|
||||
CHECK(db.upsert(t));
|
||||
CHECK(db.get_by_id("ten-acme")->status() == molo::tenancy::TenantStatus::Suspended);
|
||||
CHECK_EQ(db.list(10).size(), 1u);
|
||||
CHECK(db.remove("ten-acme"));
|
||||
CHECK(!db.get_by_id("ten-acme").has_value());
|
||||
CHECK(!db.remove("ten-acme"));
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
@@ -0,0 +1,79 @@
|
||||
// Quota: burst then 429 with retry_after, refill over time, storage 507,
|
||||
// tenant independence and reset.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/quota.h"
|
||||
#include "tenancy/tenant_buckets.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::Quota;
|
||||
using molo::tenancy::TenantBuckets;
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(burst_then_429) {
|
||||
std::int64_t now = 1000000;
|
||||
Quota::Limits limits;
|
||||
limits.requests_per_minute = 60.0;
|
||||
limits.burst = 3.0;
|
||||
Quota q(limits, [&now]() { return now; });
|
||||
CHECK(q.check_request("acme").allowed);
|
||||
CHECK(q.check_request("acme").allowed);
|
||||
CHECK(q.check_request("acme").allowed);
|
||||
Quota::Verdict v = q.check_request("acme");
|
||||
CHECK(!v.allowed);
|
||||
CHECK_EQ(v.status, 429);
|
||||
CHECK(v.retry_after_sec > 0);
|
||||
now += 61000;
|
||||
CHECK(q.check_request("acme").allowed);
|
||||
}
|
||||
|
||||
TEST(tenants_independent_and_reset) {
|
||||
std::int64_t now = 1000000;
|
||||
Quota::Limits limits;
|
||||
limits.requests_per_minute = 60.0;
|
||||
limits.burst = 1.0;
|
||||
Quota q(limits, [&now]() { return now; });
|
||||
CHECK(q.check_request("acme").allowed);
|
||||
CHECK(!q.check_request("acme").allowed);
|
||||
CHECK(q.check_request("globex").allowed);
|
||||
q.reset("acme");
|
||||
CHECK(q.check_request("acme").allowed);
|
||||
}
|
||||
|
||||
TEST(storage_507) {
|
||||
Quota::Limits limits;
|
||||
limits.storage_bytes = 100;
|
||||
Quota q(limits);
|
||||
CHECK(q.add_storage("acme", 60).allowed);
|
||||
CHECK(q.add_storage("acme", 40).allowed);
|
||||
CHECK_EQ(q.storage_used("acme"), 100);
|
||||
Quota::Verdict v = q.add_storage("acme", 1);
|
||||
CHECK(!v.allowed);
|
||||
CHECK_EQ(v.status, 507);
|
||||
CHECK_EQ(q.storage_used("acme"), 100);
|
||||
CHECK(q.add_storage("globex", 100).allowed);
|
||||
}
|
||||
|
||||
TEST(tenant_buckets) {
|
||||
TenantBuckets b;
|
||||
TenantBuckets::Spec spec;
|
||||
spec.capacity = 2.0;
|
||||
spec.refill_per_sec = 1.0;
|
||||
CHECK(b.configure("api", spec));
|
||||
CHECK(b.take("api", "acme", 1000));
|
||||
CHECK(b.take("api", "acme", 1000));
|
||||
CHECK(!b.take("api", "acme", 1000));
|
||||
CHECK(b.take("api", "globex", 1000));
|
||||
CHECK(!b.take("unknown-bucket", "acme", 1000));
|
||||
CHECK(b.take("api", "acme", 3000));
|
||||
b.reset("api", "acme");
|
||||
CHECK_EQ(b.entries(), 1u);
|
||||
CHECK(b.take("api", "acme", 3000));
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
@@ -0,0 +1,185 @@
|
||||
// TenantId validation matrix, strategy round trip, resolver source matrix,
|
||||
// conflict rule, dev default, and middleware attach/strip behavior.
|
||||
#include "mini.hpp"
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/adapters/http.h"
|
||||
#include "tenancy/catalog.h"
|
||||
#include "tenancy/context.h"
|
||||
#include "tenancy/middleware.h"
|
||||
#include "tenancy/resolver.h"
|
||||
#include "tenancy/store/memory_catalog.h"
|
||||
#include "tenancy/strategy.h"
|
||||
#include "tenancy/tenant.h"
|
||||
#include "tenancy/tenant_id.h"
|
||||
|
||||
namespace {
|
||||
|
||||
using molo::tenancy::Catalog;
|
||||
using molo::tenancy::ResolveOutcome;
|
||||
using molo::tenancy::ResolveRequest;
|
||||
using molo::tenancy::ResolveStatus;
|
||||
using molo::tenancy::Resolver;
|
||||
using molo::tenancy::Strategy;
|
||||
using molo::tenancy::TenantId;
|
||||
using molo::tenancy::TenantMiddleware;
|
||||
|
||||
std::unique_ptr<Catalog> SeedCatalog() {
|
||||
auto cat = std::make_unique<Catalog>(std::make_unique<molo::tenancy::store::MemoryCatalog>());
|
||||
CHECK(cat->create("acme", Strategy::SharedSchema, 1000).has_value());
|
||||
CHECK(cat->create("globex", Strategy::SchemaPerTenant, 1000).has_value());
|
||||
CHECK(cat->create("dev", Strategy::SharedSchema, 1000).has_value());
|
||||
return cat;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(tenant_id_matrix) {
|
||||
CHECK(TenantId::TryParse("a").has_value());
|
||||
CHECK(TenantId::TryParse("acme").has_value());
|
||||
CHECK(TenantId::TryParse("acme-2").has_value());
|
||||
CHECK(TenantId::TryParse("0").has_value());
|
||||
CHECK(TenantId::TryParse(std::string(63, 'x')).has_value());
|
||||
CHECK(!TenantId::TryParse("").has_value());
|
||||
CHECK(!TenantId::TryParse(std::string(64, 'x')).has_value());
|
||||
CHECK(!TenantId::TryParse("Acme").has_value());
|
||||
CHECK(!TenantId::TryParse("acme inc").has_value());
|
||||
CHECK(!TenantId::TryParse("-acme").has_value());
|
||||
CHECK(!TenantId::TryParse("acme-").has_value());
|
||||
CHECK(!TenantId::TryParse("acme_inc").has_value());
|
||||
CHECK(!TenantId::TryParse("acme.inc").has_value());
|
||||
CHECK(TenantId::TryParse("acme")->slug() == "acme");
|
||||
CHECK(TenantId::TryParse("acme") == TenantId::TryParse("acme"));
|
||||
CHECK(TenantId::TryParse("acme") != TenantId::TryParse("globex"));
|
||||
}
|
||||
|
||||
TEST(strategy_round_trip) {
|
||||
CHECK(molo::tenancy::ToString(Strategy::SharedSchema) == "shared_schema");
|
||||
CHECK(molo::tenancy::ToString(Strategy::SchemaPerTenant) == "schema_per_tenant");
|
||||
CHECK(molo::tenancy::ToString(Strategy::DatabasePerTenant) == "database_per_tenant");
|
||||
CHECK(molo::tenancy::ToString(Strategy::FilePerTenant) == "file_per_tenant");
|
||||
CHECK(molo::tenancy::TryParseStrategy("shared_schema") == Strategy::SharedSchema);
|
||||
CHECK(molo::tenancy::TryParseStrategy("schema_per_tenant") == Strategy::SchemaPerTenant);
|
||||
CHECK(molo::tenancy::TryParseStrategy("database_per_tenant") == Strategy::DatabasePerTenant);
|
||||
CHECK(molo::tenancy::TryParseStrategy("file_per_tenant") == Strategy::FilePerTenant);
|
||||
CHECK(!molo::tenancy::TryParseStrategy("nope").has_value());
|
||||
CHECK(molo::tenancy::ParseStrategy("nope") == Strategy::SharedSchema);
|
||||
}
|
||||
|
||||
TEST(strip_prefix) {
|
||||
CHECK(Resolver::StripTenantPrefix("/t/acme/dash").first == "/dash");
|
||||
CHECK(Resolver::StripTenantPrefix("/t/acme/dash").second == "acme");
|
||||
CHECK(Resolver::StripTenantPrefix("/t/acme").first == "/");
|
||||
CHECK(Resolver::StripTenantPrefix("/t/acme").second == "acme");
|
||||
CHECK(Resolver::StripTenantPrefix("/dash").first == "/dash");
|
||||
CHECK(Resolver::StripTenantPrefix("/dash").second == "");
|
||||
CHECK(Resolver::StripTenantPrefix("/t/Acme/x").second == "");
|
||||
CHECK(Resolver::StripTenantPrefix("/t//x").second == "");
|
||||
CHECK(Resolver::SlugFromHost("acme.example.com:8080", {"example.com"}) == "acme");
|
||||
CHECK(Resolver::SlugFromHost("example.com", {"example.com"}) == "");
|
||||
CHECK(Resolver::SlugFromHost("globex.localhost", {"localhost"}) == "globex");
|
||||
CHECK(Resolver::SlugFromHost("localhost", {"localhost"}) == "");
|
||||
CHECK(Resolver::SlugFromHost("ACME.Example.COM", {"example.com"}) == "acme");
|
||||
CHECK(Resolver::SlugFromHost("a.b.example.com", {"example.com"}) == "");
|
||||
CHECK(Resolver::SlugFromHost("acme.other.com", {"example.com"}) == "");
|
||||
}
|
||||
|
||||
TEST(resolve_matrix) {
|
||||
auto cat = SeedCatalog();
|
||||
Resolver::Options ropts;
|
||||
ropts.base_domains = {"example.com"};
|
||||
Resolver r(ropts);
|
||||
ResolveOutcome o = r.Resolve(ResolveRequest{"example.com", "/x", "acme"}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Resolved);
|
||||
CHECK(o.tenant->slug() == "acme");
|
||||
o = r.Resolve(ResolveRequest{"example.com", "/t/globex/dash", ""}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Resolved);
|
||||
CHECK(o.tenant->slug() == "globex");
|
||||
o = r.Resolve(ResolveRequest{"acme.example.com", "/x", ""}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Resolved);
|
||||
CHECK(o.tenant->slug() == "acme");
|
||||
o = r.Resolve(ResolveRequest{"acme.example.com", "/t/acme/x", "acme"}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Resolved);
|
||||
o = r.Resolve(ResolveRequest{"example.com", "/x", "unknown-tenant"}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Unknown);
|
||||
o = r.Resolve(ResolveRequest{"example.com", "/x", "Bad Header!!"}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Unknown);
|
||||
}
|
||||
|
||||
TEST(resolve_conflict) {
|
||||
auto cat = SeedCatalog();
|
||||
Resolver::Options ropts;
|
||||
ropts.base_domains = {"example.com"};
|
||||
Resolver r(ropts);
|
||||
ResolveOutcome o = r.Resolve(ResolveRequest{"example.com", "/t/globex/x", "acme"}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Conflict);
|
||||
o = r.Resolve(ResolveRequest{"globex.example.com", "/x", "acme"}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Conflict);
|
||||
o = r.Resolve(ResolveRequest{"globex.example.com", "/t/acme", ""}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Conflict);
|
||||
}
|
||||
|
||||
TEST(resolve_dev_default) {
|
||||
auto cat = SeedCatalog();
|
||||
Resolver::Options opts;
|
||||
opts.dev_mode = true;
|
||||
Resolver dev(opts);
|
||||
ResolveOutcome o = dev.Resolve(ResolveRequest{"localhost:8080", "/x", ""}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Resolved);
|
||||
CHECK(o.dev_default);
|
||||
CHECK(o.tenant->slug() == "dev");
|
||||
Resolver prod;
|
||||
o = prod.Resolve(ResolveRequest{"localhost:8080", "/x", ""}, *cat);
|
||||
CHECK(o.status == ResolveStatus::Unknown);
|
||||
CHECK(!o.dev_default);
|
||||
auto empty = std::make_unique<Catalog>(std::make_unique<molo::tenancy::store::MemoryCatalog>());
|
||||
o = dev.Resolve(ResolveRequest{"localhost", "/x", ""}, *empty);
|
||||
CHECK(o.status == ResolveStatus::Unknown);
|
||||
}
|
||||
|
||||
TEST(middleware_attach_and_errors) {
|
||||
auto cat = SeedCatalog();
|
||||
cat->suspend("globex");
|
||||
Resolver::Options opts;
|
||||
opts.base_domains = {"example.com"};
|
||||
TenantMiddleware mw(*cat, Resolver(opts));
|
||||
CHECK(mw.name() == "tenant");
|
||||
CHECK(mw.category() == molo::tenancy::adapters::Category::Security);
|
||||
|
||||
auto next = [](molo::tenancy::adapters::HttpRequest& req)
|
||||
-> molo::tenancy::adapters::Task<molo::tenancy::adapters::HttpResponse> {
|
||||
auto ext = req.get_ext<molo::tenancy::TenantContext>("tenancy.context");
|
||||
molo::tenancy::adapters::HttpResponse r;
|
||||
r.status = 200;
|
||||
r.body = (ext.has_value() ? ext->slug() : "missing") + "|" + req.path();
|
||||
co_return r;
|
||||
};
|
||||
|
||||
molo::tenancy::adapters::HttpRequest ok;
|
||||
ok.set_path("/t/acme/dash");
|
||||
ok.set_header("host", "example.com");
|
||||
molo::tenancy::adapters::HttpResponse r = mw.handle(ok, next).Get();
|
||||
CHECK_EQ(r.status, 200);
|
||||
CHECK(r.body == "acme|/dash");
|
||||
|
||||
molo::tenancy::adapters::HttpRequest suspended;
|
||||
suspended.set_path("/x");
|
||||
suspended.set_header("x-tenant", "globex");
|
||||
r = mw.handle(suspended, next).Get();
|
||||
CHECK_EQ(r.status, 403);
|
||||
|
||||
molo::tenancy::adapters::HttpRequest unknown;
|
||||
unknown.set_path("/x");
|
||||
r = mw.handle(unknown, next).Get();
|
||||
CHECK_EQ(r.status, 404);
|
||||
|
||||
molo::tenancy::adapters::HttpRequest conflict;
|
||||
conflict.set_path("/t/acme/x");
|
||||
conflict.set_header("x-tenant", "globex");
|
||||
r = mw.handle(conflict, next).Get();
|
||||
CHECK_EQ(r.status, 400);
|
||||
}
|
||||
|
||||
TEST_MAIN()
|
||||
Reference in New Issue
Block a user