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,346 @@
|
||||
# Required base-tree edits
|
||||
|
||||
Each section names one repo-relative base file plus unified diff hunks to
|
||||
apply. The base tree is absent from this worktree, so context lines follow
|
||||
the seam spec API; apply with fuzz and verify with the full build. After
|
||||
applying, delete `src/tenancy/adapters/` and swap the adapter type names in
|
||||
tenancy headers for the real base types (same member shapes).
|
||||
|
||||
## 1. src/data/context.hpp
|
||||
|
||||
Add `TenantContext` (uuid plus slug plus strategy) alongside the tenant
|
||||
string. Keep the existing constructor signature working.
|
||||
|
||||
```diff
|
||||
--- a/src/data/context.hpp
|
||||
+++ b/src/data/context.hpp
|
||||
@@ -1,6 +1,20 @@
|
||||
#pragma once
|
||||
+#include <string>
|
||||
+
|
||||
+namespace molo::data {
|
||||
+
|
||||
+struct TenantContext {
|
||||
+ std::string uuid;
|
||||
+ std::string slug;
|
||||
+ std::string strategy = "shared_schema";
|
||||
+ bool privileged = false;
|
||||
+};
|
||||
+
|
||||
+} // namespace molo::data
|
||||
```
|
||||
|
||||
```diff
|
||||
--- a/src/data/context.hpp
|
||||
+++ b/src/data/context.hpp
|
||||
@@ -10,6 +24,10 @@ class Context {
|
||||
Context(std::string correlation_id, std::string tenant, int timeout_sec);
|
||||
+ Context(std::string correlation_id, TenantContext tenant_ctx, int timeout_sec);
|
||||
const std::string& tenant() const;
|
||||
+ const TenantContext& tenant_ctx() const;
|
||||
+ bool privileged() const;
|
||||
bool expired() const;
|
||||
```
|
||||
|
||||
## 2. src/data/pool.hpp
|
||||
|
||||
Set the tenant scope on pinned acquire, assert it was empty, reset on
|
||||
release so a checkout can never leak across tenants.
|
||||
|
||||
```diff
|
||||
--- a/src/data/pool.hpp
|
||||
+++ b/src/data/pool.hpp
|
||||
@@ -20,8 +20,13 @@ class Pool {
|
||||
Checkout acquire_pinned(const Context& ctx) {
|
||||
Checkout out = acquire_free_or_wait(ctx);
|
||||
+ if (!out.connection()->scope_tag().empty())
|
||||
+ throw DbError(out.connection()->backend(), "scope_dirty",
|
||||
+ "pooled connection scope not reset");
|
||||
+ out.connection()->exec(ctx, BoundStatement::raw(
|
||||
+ "SET LOCAL app.current_tenant = '" + ctx.tenant() + "'"));
|
||||
+ out.connection()->set_scope_tag(ctx.tenant());
|
||||
return out;
|
||||
}
|
||||
```
|
||||
|
||||
```diff
|
||||
--- a/src/data/pool.hpp
|
||||
+++ b/src/data/pool.hpp
|
||||
@@ -35,6 +40,8 @@ class Pool {
|
||||
void release(Checkout&& out) {
|
||||
+ out.connection()->exec(Context("pool", "", 5),
|
||||
+ BoundStatement::raw("RESET app.current_tenant"));
|
||||
+ out.connection()->set_scope_tag("");
|
||||
park(std::move(out));
|
||||
}
|
||||
```
|
||||
|
||||
## 3. src/data/transaction.hpp
|
||||
|
||||
Emit `SET LOCAL` after `BEGIN` on Postgres so the transaction carries the
|
||||
request tenant even when the pool checkout predates resolution.
|
||||
|
||||
```diff
|
||||
--- a/src/data/transaction.hpp
|
||||
+++ b/src/data/transaction.hpp
|
||||
@@ -15,6 +15,10 @@ class Transaction {
|
||||
: conn_(conn), ctx_(ctx) {
|
||||
conn_.exec(ctx_, BoundStatement::raw("BEGIN"));
|
||||
+ if (conn_.backend() == Backend::Postgres && !ctx_.tenant().empty())
|
||||
+ conn_.exec(ctx_, BoundStatement::raw(
|
||||
+ "SET LOCAL app.current_tenant = '" + ctx_.tenant() + "'"));
|
||||
}
|
||||
```
|
||||
|
||||
## 4. src/data/orm/query.hpp
|
||||
|
||||
Auto-inject the `tenant_id` filter unless the context is privileged or the
|
||||
query already scopes itself.
|
||||
|
||||
```diff
|
||||
--- a/src/data/orm/query.hpp
|
||||
+++ b/src/data/orm/query.hpp
|
||||
@@ -30,6 +30,12 @@ class Query {
|
||||
std::string build() const;
|
||||
+ std::string build(const Context& ctx) const {
|
||||
+ std::string sql = build();
|
||||
+ if (!ctx.privileged() && !ctx.tenant().empty())
|
||||
+ sql = tenancy::OrmScope::ApplySelect(sql, ctx.tenant(), false);
|
||||
+ return sql;
|
||||
+ }
|
||||
```
|
||||
|
||||
## 5. src/data/orm/model.hpp
|
||||
|
||||
Stamp `tenant_id` on insert; scope update and delete to the context tenant.
|
||||
|
||||
```diff
|
||||
--- a/src/data/orm/model.hpp
|
||||
+++ b/src/data/orm/model.hpp
|
||||
@@ -40,6 +40,10 @@ class Model {
|
||||
static bool save(Connection& conn, const Context& ctx, ...) {
|
||||
+ if (!ctx.privileged() && !ctx.tenant().empty())
|
||||
+ derived().set_field("tenant_id", ctx.tenant());
|
||||
return insert_or_update(conn, ctx, ...);
|
||||
}
|
||||
+ // Update and delete paths must add "AND tenant_id = '<ctx.tenant()>'"
|
||||
+ // to their WHERE clause under the same condition.
|
||||
```
|
||||
|
||||
## 6. src/data/orm/sync.hpp
|
||||
|
||||
Add the `tenant_id` column plus composite index to synced tables and emit
|
||||
the RLS policy DDL through the migrator journal.
|
||||
|
||||
```diff
|
||||
--- a/src/data/orm/sync.hpp
|
||||
+++ b/src/data/orm/sync.hpp
|
||||
@@ -50,6 +50,13 @@ class Syncer {
|
||||
SyncReport sync(const Context& ctx, Connection& conn, ...) {
|
||||
+ for (const ModelInfo& model : models)
|
||||
+ ensure_column(conn, model.table, "tenant_id", "TEXT NOT NULL DEFAULT ''");
|
||||
SyncReport report = sync_tables(ctx, conn, models);
|
||||
+ for (const ModelInfo& model : models) {
|
||||
+ apply_ddl(conn, tenancy::RlsPolicy::TenantIndexDdl(model.table));
|
||||
+ apply_ddl(conn, tenancy::RlsPolicy::EnableRls(model.table));
|
||||
+ apply_ddl(conn, tenancy::RlsPolicy::PolicyDdl(model.table));
|
||||
+ }
|
||||
return report;
|
||||
}
|
||||
```
|
||||
|
||||
## 7. src/data/orm/migrator.hpp
|
||||
|
||||
Iterate the journal per migration target so tenant scoped DDL applies to
|
||||
every schema or database target, not just the default one.
|
||||
|
||||
```diff
|
||||
--- a/src/data/orm/migrator.hpp
|
||||
+++ b/src/data/orm/migrator.hpp
|
||||
@@ -22,7 +22,9 @@ class Migrator {
|
||||
void apply(const Context& ctx, Connection& conn, const Migration& m) {
|
||||
- exec_migration(conn, m.up_sql);
|
||||
+ for (const std::string& target : list_targets(conn))
|
||||
+ exec_on_target(conn, target, m.up_sql);
|
||||
journal_applied(ctx, conn, m);
|
||||
}
|
||||
```
|
||||
|
||||
## 8. src/data/orm/healer.hpp
|
||||
|
||||
Guard only, no widening: the healer must never alter the `tenant_id`
|
||||
column type or drop its index. Skip heal actions targeting it.
|
||||
|
||||
```diff
|
||||
--- a/src/data/orm/healer.hpp
|
||||
+++ b/src/data/orm/healer.hpp
|
||||
@@ -18,6 +18,8 @@ class Healer {
|
||||
bool heal_column(Connection& conn, const std::string& table,
|
||||
const std::string& column, ...) {
|
||||
+ if (column == "tenant_id") return false;
|
||||
return widen_or_extend(conn, table, column, ...);
|
||||
}
|
||||
```
|
||||
|
||||
## 9. src/data/drivers/sqlite/db.hpp
|
||||
|
||||
Driver guard: in pool mode reject statements that lack a tenant scope
|
||||
unless the context is privileged.
|
||||
|
||||
```diff
|
||||
--- a/src/data/drivers/sqlite/db.hpp
|
||||
+++ b/src/data/drivers/sqlite/db.hpp
|
||||
@@ -30,6 +30,11 @@ class SqliteDb {
|
||||
Result exec_scoped(const Context& ctx, const BoundStatement& stmt) {
|
||||
+ if (!ctx.privileged() && !ctx.tenant().empty() &&
|
||||
+ stmt.sql().find("tenant_id") == std::string::npos &&
|
||||
+ stmt.sql().find("tenants") == std::string::npos)
|
||||
+ throw DbError(Backend::Sqlite, "tenant_scope_missing",
|
||||
+ "pool-mode statement lacks tenant scope");
|
||||
return exec_inner(ctx, stmt);
|
||||
}
|
||||
```
|
||||
|
||||
## 10. src/data/cache/cache.hpp
|
||||
|
||||
Prefix cache keys with the tenant so entries never cross tenants.
|
||||
|
||||
```diff
|
||||
--- a/src/data/cache/cache.hpp
|
||||
+++ b/src/data/cache.hpp
|
||||
@@ -25,6 +25,10 @@ class Cache {
|
||||
static std::string tag_for_table(const std::string& table);
|
||||
+ static std::string scoped_key(const Context& ctx, const std::string& key) {
|
||||
+ return ctx.tenant().empty() ? key : "tenant:" + ctx.tenant() + ":" + key;
|
||||
+ }
|
||||
+ // Route get/put/get_or_compute key arguments through scoped_key(ctx, key).
|
||||
```
|
||||
|
||||
## 11. src/data/pubsub/broker.hpp
|
||||
|
||||
Scope channel names per tenant at publish and subscribe time.
|
||||
|
||||
```diff
|
||||
--- a/src/data/pubsub/broker.hpp
|
||||
+++ b/src/data/pubsub/broker.hpp
|
||||
@@ -18,6 +18,10 @@ class Broker {
|
||||
void publish(const std::string& channel, ...);
|
||||
+ static std::string scoped_channel(const Context& ctx, const std::string& ch) {
|
||||
+ return ctx.tenant().empty() ? ch : "tenant:" + ctx.tenant() + ":" + ch;
|
||||
+ }
|
||||
+ // Route publish/subscribe/unsubscribe channel arguments through it.
|
||||
```
|
||||
|
||||
## 12. src/app/app/application.h
|
||||
|
||||
Register `TenantMiddleware` first in the Security category so it runs right
|
||||
after observability and before all other security middleware.
|
||||
|
||||
```diff
|
||||
--- a/src/app/app/application.h
|
||||
+++ b/src/app/app/application.h
|
||||
@@ -40,6 +40,8 @@ class Application {
|
||||
void install_default_chain(Catalog& tenants, Resolver resolver) {
|
||||
chain_.use(std::make_shared<ExceptionMappingMiddleware>());
|
||||
chain_.use(std::make_shared<ObservabilityMiddleware>());
|
||||
+ chain_.use(std::make_shared<tenancy::TenantMiddleware>(tenants, resolver));
|
||||
chain_.use(std::make_shared<CorsMiddleware>());
|
||||
```
|
||||
|
||||
## 13. src/app/errors/http_error.h
|
||||
|
||||
Add the tenant error codes plus 507.
|
||||
|
||||
```diff
|
||||
--- a/src/app/errors/http_error.h
|
||||
+++ b/src/app/errors/http_error.h
|
||||
@@ -30,6 +30,18 @@ class HttpError {
|
||||
static HttpError TooManyRequests(const std::string& msg);
|
||||
+ static HttpError TenantUnknown(const std::string& msg) {
|
||||
+ return HttpError(404, "tenant_unknown", msg);
|
||||
+ }
|
||||
+ static HttpError TenantSuspended(const std::string& msg) {
|
||||
+ return HttpError(403, "tenant_suspended", msg);
|
||||
+ }
|
||||
+ static HttpError TenantConflict(const std::string& msg) {
|
||||
+ return HttpError(400, "tenant_conflict", msg);
|
||||
+ }
|
||||
+ static HttpError InsufficientStorage(const std::string& msg) {
|
||||
+ return HttpError(507, "insufficient_storage", msg);
|
||||
+ }
|
||||
```
|
||||
|
||||
## 14. src/app/routing/router.h
|
||||
|
||||
Tenant-aware helpers: strip the `/t/<slug>` prefix and build URLs that
|
||||
carry the tenant.
|
||||
|
||||
```diff
|
||||
--- a/src/app/routing/router.h
|
||||
+++ b/src/app/routing/router.h
|
||||
@@ -45,6 +45,13 @@ class Router {
|
||||
std::string url_for(const std::string& name, ...);
|
||||
+ static std::pair<std::string, std::string> strip_tenant_prefix(
|
||||
+ const std::string& path) {
|
||||
+ return tenancy::Resolver::StripTenantPrefix(path);
|
||||
+ }
|
||||
+ std::string url_for_tenant(const std::string& tenant,
|
||||
+ const std::string& name, ...) {
|
||||
+ return "/t/" + tenant + url_for(name, ...);
|
||||
+ }
|
||||
```
|
||||
|
||||
## 15. src/security/session/Session.h
|
||||
|
||||
Bind the session to the tenant id and rotate the session on tenant switch.
|
||||
|
||||
```diff
|
||||
--- a/src/security/session/Session.h
|
||||
+++ b/src/security/session/Session.h
|
||||
@@ -20,6 +20,12 @@ class Session {
|
||||
std::map<std::string, std::string> data;
|
||||
+ void bind_tenant(const std::string& tid) { data["tid"] = tid; }
|
||||
+ std::string tenant_id() const {
|
||||
+ auto it = data.find("tid");
|
||||
+ return it == data.end() ? "" : it->second;
|
||||
+ }
|
||||
+ // SessionManager: when the request tenant differs from tenant_id(),
|
||||
+ // rotate the session id before rebinding.
|
||||
```
|
||||
|
||||
## 16. src/security/guard/RateLimiter.h
|
||||
|
||||
Key verdicts per tenant plus route so one tenant cannot burn another
|
||||
tenant's budget. Backed by `tenancy::TenantBuckets`.
|
||||
|
||||
```diff
|
||||
--- a/src/security/guard/RateLimiter.h
|
||||
+++ b/src/security/guard/RateLimiter.h
|
||||
@@ -25,6 +25,9 @@ class RateLimiter {
|
||||
Verdict check(const HttpRequestView& req, const std::string& user_id);
|
||||
+ // Key construction must prefix the tenant slug from the request
|
||||
+ // tenant extension: key = tenant + "|" + route + "|" + user_or_ip.
|
||||
+ // Wire the per-tenant take() through tenancy::TenantBuckets.
|
||||
```
|
||||
|
||||
## 17. Makefile
|
||||
|
||||
Include the tenancy fragment and wire its targets.
|
||||
|
||||
```diff
|
||||
--- a/Makefile
|
||||
+++ b/Makefile
|
||||
@@ -5,6 +5,7 @@
|
||||
include src/data.mk
|
||||
+include src/tenancy.mk
|
||||
```
|
||||
|
||||
```diff
|
||||
--- a/Makefile
|
||||
+++ b/Makefile
|
||||
@@ -20,8 +21,8 @@
|
||||
-all:: data-tests
|
||||
-test:: data-check
|
||||
+all:: data-tests tenancy-tests
|
||||
+test:: data-check tenancy-check
|
||||
```
|
||||
@@ -0,0 +1,75 @@
|
||||
# Tenancy part specification
|
||||
|
||||
Namespace `molo::tenancy` (`molo::tenancy::store` for catalog backends,
|
||||
`molo::tenancy::adapters` for standalone-only seam mirrors). Header-only
|
||||
C++23, stdlib plus OS syscalls only. One class per file. All ceilings live
|
||||
in `caps.h`. No em dashes anywhere.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Class | Purpose |
|
||||
|------|-------|---------|
|
||||
| caps.h | Caps | Static ceilings for every map, cache and quota |
|
||||
| tenant_id.h | TenantId | Validated slug (`[a-z0-9-]`, 1..63, wrapped ends) |
|
||||
| strategy.h | Strategy | SharedSchema, SchemaPerTenant, DatabasePerTenant, FilePerTenant |
|
||||
| tenant.h | Tenant | Record: id, slug, strategy, status, storage, timestamps |
|
||||
| context.h | TenantContext | uuid plus slug plus strategy; renders `tenant:<slug>` for data Context |
|
||||
| store/catalog_store.h | CatalogStore | Abstract tenant record storage |
|
||||
| store/memory_catalog.h | MemoryCatalog | Mutex guarded in-memory store, capped |
|
||||
| store/db_catalog.h | DbCatalog | Tenants table via `Connection::exec` only |
|
||||
| catalog.h | Catalog | Facade: lifecycle plus bounded slug cache (FIFO, 65536) |
|
||||
| resolver.h | Resolver | Header/path/host sources, conflict rule, dev default |
|
||||
| middleware.h | TenantMiddleware | Resolve, strip `/t/<slug>`, attach context, map errors |
|
||||
| provisioner.h | Provisioner | Provision with hook rollback, suspend, tombstone, gated purge |
|
||||
| orm_scope.h | OrmScope | `tenant_id` filter injection, insert stamping, key/channel prefixes |
|
||||
| rls_policy.h | RlsPolicy | RLS DDL plus `SET LOCAL` / `RESET` statements |
|
||||
| pool_factory.h | PoolFactory | Per-tenant checkout discipline, GUC assert, RAII Lease |
|
||||
| config_overlay.h | ConfigOverlay | Global defaults with per-tenant overrides, typed getters |
|
||||
| quota.h | Quota | Token bucket rate (429) plus storage cap (507) |
|
||||
| tenant_buckets.h | TenantBuckets | Named bucket registry for tenant scoped rate limits |
|
||||
| feature_flags.h | FeatureFlags | Global defaults plus per-tenant overrides, 256 cap |
|
||||
| metrics.h | TenantMetrics | Per-tenant counters, 512 labels, rest folds to `other` |
|
||||
| bridge.h | DatabaseBridge | FilePerTenant SQLite files, single-db transactions only |
|
||||
| adapters/task.h | Task | ADAPTER: eager coroutine task (delete at integration) |
|
||||
| adapters/http.h | HttpRequest | ADAPTER: request/response/error/middleware seam mirror |
|
||||
| adapters/db.h | Connection | ADAPTER: data Context/Connection seam mirror |
|
||||
|
||||
## Resolution matrix (resolver.h)
|
||||
|
||||
Sources: `X-Tenant` header, `/t/<slug>` path prefix, host subdomain.
|
||||
One distinct slug resolves; two distinct slugs conflict; none resolves to
|
||||
the dev default only in dev mode, else unknown. Invalid values are ignored
|
||||
as sources, never errors by themselves.
|
||||
|
||||
## Lifecycle
|
||||
|
||||
`create` (unique slug) -> `suspend` (403s) -> `tombstone` (404s, terminal)
|
||||
-> `purge` only when tombstoned plus retention elapsed plus confirm token
|
||||
`PURGE:<id>` matches. Provision hooks that fail roll the entry back fully.
|
||||
|
||||
## Data scoping contract
|
||||
|
||||
- SharedSchema: every table carries `tenant_id`; `OrmScope` injects the
|
||||
predicate unless privileged; RLS policy enforces it in Postgres.
|
||||
- Pool checkouts set scope on acquire and reset on release; a dirty slot
|
||||
throws instead of leaking across tenants.
|
||||
- Cache keys and pubsub channels are prefixed `tenant:<slug>:`.
|
||||
- Cross-file SQLite transactions are refused.
|
||||
|
||||
## Base-tree integration
|
||||
|
||||
Exact edits live in `PATCHES.md` as unified diffs. After applying them,
|
||||
delete `adapters/` and swap the adapter type names for the real base types;
|
||||
tenancy call sites keep the same shape.
|
||||
|
||||
## Tests (tests/src/tenancy, mini.hpp CHECK harness)
|
||||
|
||||
| Test | Coverage |
|
||||
|------|----------|
|
||||
| test_tenant_id_resolve | id matrix, strategy, resolver matrix, conflict, dev default, middleware |
|
||||
| test_pool_scope | 2-tenant CRUD both backends, RLS proof, dirty refusal, 100k leak loop |
|
||||
| test_bridge | per-db isolation, txn staging, cross-file refusal, open caps |
|
||||
| test_provision | rollback, tombstone, purge gates, DbCatalog round trip |
|
||||
| test_quota | 429 burst, refill, 507 storage, buckets |
|
||||
| test_flags_config | flags, overrides, 256 cap, overlay precedence, key cap |
|
||||
| test_metrics | 512 labels, 513th is `other`, folded counts |
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
// ADAPTER: minimal local mirror of the molo::data seams used by tenancy:
|
||||
// Context, BoundStatement, Result/Row/Value, DbError, Connection. Shapes match
|
||||
// the seam spec; swap for the real base headers at integration (PATCHES.md).
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace molo::tenancy::adapters::db {
|
||||
|
||||
enum class Backend { Postgres, Sqlite };
|
||||
|
||||
using Value = std::variant<std::nullptr_t, std::int64_t, double, std::string>;
|
||||
using Row = std::map<std::string, Value>;
|
||||
|
||||
inline Value MakeString(std::string s) { return Value{std::move(s)}; }
|
||||
inline Value MakeInt(std::int64_t v) { return Value{v}; }
|
||||
|
||||
inline std::string AsString(const Value& v) {
|
||||
if (auto* s = std::get_if<std::string>(&v)) return *s;
|
||||
if (auto* i = std::get_if<std::int64_t>(&v)) return std::to_string(*i);
|
||||
if (auto* d = std::get_if<double>(&v)) return std::to_string(*d);
|
||||
return {};
|
||||
}
|
||||
|
||||
inline std::int64_t AsInt(const Value& v) {
|
||||
if (auto* i = std::get_if<std::int64_t>(&v)) return *i;
|
||||
if (auto* s = std::get_if<std::string>(&v)) {
|
||||
try {
|
||||
return std::stoll(*s);
|
||||
} catch (...) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
if (auto* d = std::get_if<double>(&v)) return static_cast<std::int64_t>(*d);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct Result {
|
||||
std::vector<Row> rows;
|
||||
long affected = 0;
|
||||
};
|
||||
|
||||
class BoundStatement {
|
||||
public:
|
||||
BoundStatement(std::string sql, std::vector<Value> params)
|
||||
: sql_(std::move(sql)), params_(std::move(params)) {}
|
||||
static BoundStatement Raw(std::string sql, std::vector<Value> params = {}) {
|
||||
return BoundStatement(std::move(sql), std::move(params));
|
||||
}
|
||||
const std::string& sql() const { return sql_; }
|
||||
const std::vector<Value>& params() const { return params_; }
|
||||
|
||||
private:
|
||||
std::string sql_;
|
||||
std::vector<Value> params_;
|
||||
};
|
||||
|
||||
class DbError : public std::runtime_error {
|
||||
public:
|
||||
DbError(Backend backend, std::string code, std::string message, std::int64_t detail = 0)
|
||||
: std::runtime_error(message),
|
||||
backend_(backend),
|
||||
code_(std::move(code)),
|
||||
message_(std::move(message)),
|
||||
detail_(detail) {}
|
||||
Backend backend() const { return backend_; }
|
||||
const std::string& code() const { return code_; }
|
||||
const std::string& message() const { return message_; }
|
||||
|
||||
private:
|
||||
Backend backend_;
|
||||
std::string code_;
|
||||
std::string message_;
|
||||
std::int64_t detail_;
|
||||
};
|
||||
|
||||
class Context {
|
||||
public:
|
||||
Context(std::string correlation_id, std::string tenant, int timeout_sec)
|
||||
: correlation_id_(std::move(correlation_id)),
|
||||
tenant_(std::move(tenant)),
|
||||
timeout_sec_(timeout_sec) {}
|
||||
const std::string& correlation_id() const { return correlation_id_; }
|
||||
const std::string& tenant() const { return tenant_; }
|
||||
int timeout_sec() const { return timeout_sec_; }
|
||||
bool expired() const { return timeout_sec_ <= 0; }
|
||||
|
||||
private:
|
||||
std::string correlation_id_;
|
||||
std::string tenant_;
|
||||
int timeout_sec_;
|
||||
};
|
||||
|
||||
class Connection {
|
||||
public:
|
||||
virtual ~Connection() = default;
|
||||
virtual Result exec(const Context& ctx, const BoundStatement& stmt) = 0;
|
||||
virtual void prepare(const std::string& name, const std::string& sql) = 0;
|
||||
virtual Result exec_prepared(const Context& ctx,
|
||||
const std::string& name,
|
||||
const std::vector<Value>& params) = 0;
|
||||
virtual bool ping() = 0;
|
||||
virtual void close() = 0;
|
||||
virtual Backend backend() const = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy::adapters::db
|
||||
@@ -0,0 +1,130 @@
|
||||
#pragma once
|
||||
// ADAPTER: minimal local mirror of the molo::app seams used by tenancy:
|
||||
// http_msg Request/Response, middleware Middleware/Chain/Next, errors HttpError.
|
||||
// Shapes match the seam spec; swap these types for the real base headers at
|
||||
// integration time (see PATCHES.md). Delete this file once wired.
|
||||
|
||||
#include <any>
|
||||
#include <cctype>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/adapters/task.h"
|
||||
|
||||
namespace molo::tenancy::adapters {
|
||||
|
||||
inline std::string Lower(std::string_view s) {
|
||||
std::string out(s);
|
||||
for (char& c : out) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
|
||||
return out;
|
||||
}
|
||||
|
||||
class HttpRequest {
|
||||
public:
|
||||
void set_path(std::string path) { path_ = std::move(path); }
|
||||
const std::string& path() const { return path_; }
|
||||
|
||||
void set_header(std::string name, std::string value) {
|
||||
headers_[Lower(name)] = std::move(value);
|
||||
}
|
||||
std::string header(std::string_view name) const {
|
||||
auto it = headers_.find(Lower(name));
|
||||
return it == headers_.end() ? std::string{} : it->second;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void set_ext(std::string key, T value) {
|
||||
ext_[std::move(key)] = std::move(value);
|
||||
}
|
||||
template <typename T>
|
||||
std::optional<T> get_ext(const std::string& key) const {
|
||||
auto it = ext_.find(key);
|
||||
if (it == ext_.end()) return std::nullopt;
|
||||
if (auto* p = std::any_cast<T>(&it->second)) return *p;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
void set_path_param(std::string key, std::string value) {
|
||||
params_[std::move(key)] = std::move(value);
|
||||
}
|
||||
std::string path_param(std::string_view key) const {
|
||||
auto it = params_.find(std::string(key));
|
||||
return it == params_.end() ? std::string{} : it->second;
|
||||
}
|
||||
|
||||
private:
|
||||
std::string path_;
|
||||
std::map<std::string, std::string> headers_;
|
||||
std::map<std::string, std::any> ext_;
|
||||
std::map<std::string, std::string> params_;
|
||||
};
|
||||
|
||||
class HttpError : public std::exception {
|
||||
public:
|
||||
HttpError(int status, std::string code, std::string message)
|
||||
: status_(status), code_(std::move(code)), message_(std::move(message)) {}
|
||||
int status() const { return status_; }
|
||||
const std::string& code() const { return code_; }
|
||||
const std::string& message() const { return message_; }
|
||||
const char* what() const noexcept override { return message_.c_str(); }
|
||||
|
||||
static HttpError TenantUnknown(std::string detail) {
|
||||
return HttpError(404, "tenant_unknown", std::move(detail));
|
||||
}
|
||||
static HttpError TenantSuspended(std::string detail) {
|
||||
return HttpError(403, "tenant_suspended", std::move(detail));
|
||||
}
|
||||
static HttpError TenantConflict(std::string detail) {
|
||||
return HttpError(400, "tenant_conflict", std::move(detail));
|
||||
}
|
||||
static HttpError InsufficientStorage(std::string detail) {
|
||||
return HttpError(507, "insufficient_storage", std::move(detail));
|
||||
}
|
||||
static HttpError TooManyRequests(std::string detail) {
|
||||
return HttpError(429, "too_many_requests", std::move(detail));
|
||||
}
|
||||
|
||||
private:
|
||||
int status_;
|
||||
std::string code_;
|
||||
std::string message_;
|
||||
};
|
||||
|
||||
class HttpResponse {
|
||||
public:
|
||||
int status = 200;
|
||||
std::string body;
|
||||
std::map<std::string, std::string> headers;
|
||||
|
||||
static HttpResponse FromError(const HttpError& err) {
|
||||
HttpResponse r;
|
||||
r.status = err.status();
|
||||
r.body = err.code() + ": " + err.message();
|
||||
return r;
|
||||
}
|
||||
};
|
||||
|
||||
enum class Category {
|
||||
Errors = 0,
|
||||
Observability = 1,
|
||||
Security = 2,
|
||||
SessionAuth = 3,
|
||||
User = 4,
|
||||
RouterAdjacent = 5,
|
||||
};
|
||||
|
||||
using Next = std::function<Task<HttpResponse>(HttpRequest&)>;
|
||||
|
||||
class MiddlewareBase {
|
||||
public:
|
||||
virtual ~MiddlewareBase() = default;
|
||||
virtual Category category() const = 0;
|
||||
virtual std::string name() const = 0;
|
||||
virtual Task<HttpResponse> handle(HttpRequest& req, Next next) = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy::adapters
|
||||
@@ -0,0 +1,63 @@
|
||||
#pragma once
|
||||
// ADAPTER: minimal local stand-in for the framework Task<T> coroutine type.
|
||||
// Lets tenancy middleware use real co_await/co_return syntax while the base
|
||||
// tree is absent. Runs eagerly and completes synchronously. Delete when the
|
||||
// real molo::app task type is available; call sites need no change.
|
||||
|
||||
#include <coroutine>
|
||||
#include <exception>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace molo::tenancy::adapters {
|
||||
|
||||
template <typename T>
|
||||
class Task {
|
||||
public:
|
||||
struct promise_type {
|
||||
std::optional<T> value;
|
||||
std::exception_ptr error;
|
||||
Task get_return_object() {
|
||||
return Task{std::coroutine_handle<promise_type>::from_promise(*this)};
|
||||
}
|
||||
std::suspend_never initial_suspend() noexcept { return {}; }
|
||||
std::suspend_always final_suspend() noexcept { return {}; }
|
||||
void return_value(T v) { value.emplace(std::move(v)); }
|
||||
void unhandled_exception() { error = std::current_exception(); }
|
||||
};
|
||||
|
||||
using Handle = std::coroutine_handle<promise_type>;
|
||||
|
||||
explicit Task(Handle h) : handle_(h) {}
|
||||
Task(Task&& other) noexcept : handle_(std::exchange(other.handle_, {})) {}
|
||||
Task& operator=(Task&& other) noexcept {
|
||||
if (this != &other) {
|
||||
Reset();
|
||||
handle_ = std::exchange(other.handle_, {});
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
~Task() { Reset(); }
|
||||
|
||||
Task(const Task&) = delete;
|
||||
Task& operator=(const Task&) = delete;
|
||||
|
||||
bool await_ready() const noexcept { return true; }
|
||||
void await_suspend(std::coroutine_handle<>) noexcept {}
|
||||
T await_resume() { return Get(); }
|
||||
|
||||
T Get() {
|
||||
auto& p = handle_.promise();
|
||||
if (p.error) std::rethrow_exception(p.error);
|
||||
return std::move(*p.value);
|
||||
}
|
||||
|
||||
private:
|
||||
void Reset() {
|
||||
if (handle_) handle_.destroy();
|
||||
handle_ = {};
|
||||
}
|
||||
Handle handle_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy::adapters
|
||||
@@ -0,0 +1,146 @@
|
||||
#pragma once
|
||||
// DatabaseBridge maps each FilePerTenant tenant to its own SQLite file under
|
||||
// a root directory and keeps the stores isolated. A transaction binds to
|
||||
// exactly one database: opening one across two files throws CrossFileError.
|
||||
// Each open database counts two files (data plus journal) toward the file cap.
|
||||
|
||||
#include <cstddef>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
#include "tenancy/tenant_id.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class DatabaseBridge {
|
||||
public:
|
||||
class CrossFileError : public std::runtime_error {
|
||||
public:
|
||||
explicit CrossFileError(const std::string& msg) : std::runtime_error(msg) {}
|
||||
};
|
||||
|
||||
class Txn {
|
||||
public:
|
||||
Txn() : bridge_(nullptr) {}
|
||||
Txn(DatabaseBridge* bridge, std::string slug)
|
||||
: bridge_(bridge), slug_(std::move(slug)), active_(true) {}
|
||||
|
||||
Txn(Txn&&) = default;
|
||||
Txn& operator=(Txn&&) = default;
|
||||
Txn(const Txn&) = delete;
|
||||
Txn& operator=(const Txn&) = delete;
|
||||
|
||||
bool active() const { return active_; }
|
||||
const std::string& slug() const { return slug_; }
|
||||
|
||||
bool put(const std::string& key, const std::string& value) {
|
||||
if (!active_ || bridge_ == nullptr) return false;
|
||||
staged_[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<std::string> get(const std::string& key) {
|
||||
if (!active_ || bridge_ == nullptr) return std::nullopt;
|
||||
auto it = staged_.find(key);
|
||||
if (it != staged_.end()) return it->second;
|
||||
return bridge_->get(slug_, key);
|
||||
}
|
||||
|
||||
bool commit() {
|
||||
if (!active_ || bridge_ == nullptr) return false;
|
||||
bool ok = bridge_->ApplyStaged(slug_, staged_);
|
||||
active_ = false;
|
||||
staged_.clear();
|
||||
return ok;
|
||||
}
|
||||
|
||||
void rollback() {
|
||||
active_ = false;
|
||||
staged_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
DatabaseBridge* bridge_;
|
||||
std::string slug_;
|
||||
bool active_ = false;
|
||||
std::map<std::string, std::string> staged_;
|
||||
};
|
||||
|
||||
explicit DatabaseBridge(std::string root) : root_(std::move(root)) {}
|
||||
|
||||
std::string file_for(const std::string& slug) const { return root_ + "/" + slug + ".db"; }
|
||||
|
||||
bool open(const std::string& slug) {
|
||||
if (!TenantId::TryParse(slug).has_value()) return false;
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (dbs_.find(slug) != dbs_.end()) return true;
|
||||
if (dbs_.size() >= Caps::kBridgeDbsMax) return false;
|
||||
if ((dbs_.size() + 1) * 2 > Caps::kBridgeFilesMax) return false;
|
||||
dbs_.emplace(slug, std::map<std::string, std::string>{});
|
||||
return true;
|
||||
}
|
||||
|
||||
bool is_open(const std::string& slug) const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return dbs_.find(slug) != dbs_.end();
|
||||
}
|
||||
|
||||
bool put(const std::string& slug, const std::string& key, const std::string& value) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = dbs_.find(slug);
|
||||
if (it == dbs_.end()) return false;
|
||||
it->second[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<std::string> get(const std::string& slug, const std::string& key) const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = dbs_.find(slug);
|
||||
if (it == dbs_.end()) return std::nullopt;
|
||||
auto jt = it->second.find(key);
|
||||
if (jt == it->second.end()) return std::nullopt;
|
||||
return jt->second;
|
||||
}
|
||||
|
||||
Txn begin(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (dbs_.find(slug) == dbs_.end()) return Txn{};
|
||||
return Txn(this, slug);
|
||||
}
|
||||
|
||||
Txn begin2(const std::string& a, const std::string& b) {
|
||||
if (a != b) throw CrossFileError("cross-file transaction refused: " + a + " vs " + b);
|
||||
return begin(a);
|
||||
}
|
||||
|
||||
std::size_t db_count() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return dbs_.size();
|
||||
}
|
||||
|
||||
std::size_t file_count() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return dbs_.size() * 2;
|
||||
}
|
||||
|
||||
private:
|
||||
bool ApplyStaged(const std::string& slug, const std::map<std::string, std::string>& staged) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = dbs_.find(slug);
|
||||
if (it == dbs_.end()) return false;
|
||||
for (const auto& [k, v] : staged) it->second[k] = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string root_;
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<std::string, std::map<std::string, std::string>> dbs_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,30 @@
|
||||
#pragma once
|
||||
// All static ceilings for the tenancy part. Every map, cache, registry and
|
||||
// quota in this part is bounded by one of these constants. No autotuning.
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
struct Caps {
|
||||
static constexpr std::size_t kSlugCacheMax = 65536;
|
||||
static constexpr std::size_t kPoolTenantsMax = 100000;
|
||||
static constexpr std::size_t kPoolSlotsMax = 1024;
|
||||
static constexpr std::size_t kBridgeDbsMax = 1024;
|
||||
static constexpr std::size_t kBridgeFilesMax = 4096;
|
||||
static constexpr std::size_t kMetricTenantsMax = 512;
|
||||
static constexpr std::size_t kFlagsMax = 256;
|
||||
static constexpr std::size_t kCatalogTenantsMax = 100000;
|
||||
static constexpr std::size_t kConfigTenantsMax = 100000;
|
||||
static constexpr std::size_t kConfigKeysPerTenantMax = 1024;
|
||||
static constexpr std::size_t kRateBucketsMax = 4096;
|
||||
static constexpr std::size_t kBucketEntriesMax = 65536;
|
||||
static constexpr std::size_t kSlugMaxLen = 63;
|
||||
static constexpr double kRequestsPerMinuteDefault = 600.0;
|
||||
static constexpr double kRequestBurstDefault = 100.0;
|
||||
static constexpr std::int64_t kStorageBytesDefault = 1073741824;
|
||||
static constexpr std::int64_t kRetentionSecDefault = 604800;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,124 @@
|
||||
#pragma once
|
||||
// Catalog facade over a CatalogStore with a bounded slug lookup cache
|
||||
// (kSlugCacheMax, FIFO eviction). Owns lifecycle transitions: create,
|
||||
// suspend, tombstone, and the gated purge.
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
#include "tenancy/store/catalog_store.h"
|
||||
#include "tenancy/strategy.h"
|
||||
#include "tenancy/tenant.h"
|
||||
#include "tenancy/tenant_id.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
enum class PurgeResult { Ok, NotFound, NotTombstone, RetentionHold, BadConfirm };
|
||||
|
||||
class Catalog {
|
||||
public:
|
||||
explicit Catalog(std::unique_ptr<store::CatalogStore> backend)
|
||||
: backend_(std::move(backend)) {}
|
||||
|
||||
std::optional<Tenant> create(const std::string& slug,
|
||||
Strategy strategy,
|
||||
std::int64_t now_unix) {
|
||||
auto id = TenantId::TryParse(slug);
|
||||
if (!id.has_value()) return std::nullopt;
|
||||
if (find_by_slug(slug).has_value()) return std::nullopt;
|
||||
Tenant tenant("ten-" + slug, slug, strategy, TenantStatus::Active, 0, now_unix, 0);
|
||||
if (!backend_->upsert(tenant)) return std::nullopt;
|
||||
CachePut(tenant);
|
||||
return tenant;
|
||||
}
|
||||
|
||||
std::optional<Tenant> find_by_slug(const std::string& slug) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = cache_.find(slug);
|
||||
if (it != cache_.end()) return it->second;
|
||||
}
|
||||
auto found = backend_->get_by_slug(slug);
|
||||
if (found.has_value()) CachePut(*found);
|
||||
return found;
|
||||
}
|
||||
|
||||
std::optional<Tenant> find_by_id(const std::string& id) {
|
||||
return backend_->get_by_id(id);
|
||||
}
|
||||
|
||||
bool suspend(const std::string& slug) {
|
||||
auto found = backend_->get_by_slug(slug);
|
||||
if (!found.has_value() || !found->is_active()) return false;
|
||||
found->suspend();
|
||||
if (!backend_->upsert(*found)) return false;
|
||||
CachePut(*found);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool tombstone(const std::string& slug, std::int64_t now_unix) {
|
||||
auto found = backend_->get_by_slug(slug);
|
||||
if (!found.has_value()) return false;
|
||||
found->mark_tombstone(now_unix);
|
||||
if (!backend_->upsert(*found)) return false;
|
||||
Invalidate(slug);
|
||||
return true;
|
||||
}
|
||||
|
||||
PurgeResult purge(const std::string& slug,
|
||||
const std::string& confirm,
|
||||
std::int64_t now_unix,
|
||||
std::int64_t retention_sec) {
|
||||
auto found = backend_->get_by_slug(slug);
|
||||
if (!found.has_value()) return PurgeResult::NotFound;
|
||||
if (found->status() != TenantStatus::Tombstone) return PurgeResult::NotTombstone;
|
||||
if (now_unix - found->tombstoned_unix() < retention_sec) return PurgeResult::RetentionHold;
|
||||
if (confirm != "PURGE:" + found->id()) return PurgeResult::BadConfirm;
|
||||
if (!backend_->remove(found->id())) return PurgeResult::NotFound;
|
||||
Invalidate(slug);
|
||||
return PurgeResult::Ok;
|
||||
}
|
||||
|
||||
std::vector<Tenant> list(std::size_t limit) { return backend_->list(limit); }
|
||||
|
||||
void invalidate(const std::string& slug) { Invalidate(slug); }
|
||||
|
||||
std::size_t cache_size() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return cache_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
void CachePut(const Tenant& tenant) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (cache_.find(tenant.slug()) == cache_.end()) {
|
||||
order_.push_back(tenant.slug());
|
||||
while (order_.size() > Caps::kSlugCacheMax) {
|
||||
cache_.erase(order_.front());
|
||||
order_.pop_front();
|
||||
}
|
||||
}
|
||||
cache_.insert_or_assign(tenant.slug(), tenant);
|
||||
}
|
||||
|
||||
void Invalidate(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
cache_.erase(slug);
|
||||
}
|
||||
|
||||
std::unique_ptr<store::CatalogStore> backend_;
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<std::string, Tenant> cache_;
|
||||
std::deque<std::string> order_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
// ConfigOverlay layers per-tenant config over global defaults. Lookup order:
|
||||
// tenant value, global value, caller fallback. Bounded tenants and keys per
|
||||
// tenant; typed getters return the fallback on missing or malformed values.
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class ConfigOverlay {
|
||||
public:
|
||||
void set_global(const std::string& key, const std::string& value) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
global_[key] = value;
|
||||
}
|
||||
|
||||
bool set_tenant(const std::string& slug, const std::string& key, const std::string& value) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = tenants_.find(slug);
|
||||
if (it == tenants_.end()) {
|
||||
if (tenants_.size() >= Caps::kConfigTenantsMax) return false;
|
||||
it = tenants_.emplace(slug, std::unordered_map<std::string, std::string>{}).first;
|
||||
}
|
||||
if (it->second.find(key) == it->second.end() &&
|
||||
it->second.size() >= Caps::kConfigKeysPerTenantMax) {
|
||||
return false;
|
||||
}
|
||||
it->second[key] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string get(const std::string& slug,
|
||||
const std::string& key,
|
||||
const std::string& fallback = "") const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = tenants_.find(slug);
|
||||
if (it != tenants_.end()) {
|
||||
auto jt = it->second.find(key);
|
||||
if (jt != it->second.end()) return jt->second;
|
||||
}
|
||||
auto gt = global_.find(key);
|
||||
return gt == global_.end() ? fallback : gt->second;
|
||||
}
|
||||
|
||||
std::int64_t get_int(const std::string& slug, const std::string& key, std::int64_t fallback) const {
|
||||
std::string raw = get(slug, key, "");
|
||||
if (raw.empty()) return fallback;
|
||||
try {
|
||||
std::size_t pos = 0;
|
||||
std::int64_t v = std::stoll(raw, &pos);
|
||||
return pos == raw.size() ? v : fallback;
|
||||
} catch (...) {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
bool get_bool(const std::string& slug, const std::string& key, bool fallback) const {
|
||||
std::string raw = get(slug, key, "");
|
||||
if (raw == "true" || raw == "1" || raw == "yes") return true;
|
||||
if (raw == "false" || raw == "0" || raw == "no") return false;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
bool clear_tenant(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return tenants_.erase(slug) > 0;
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<std::string, std::string> global_;
|
||||
std::unordered_map<std::string, std::unordered_map<std::string, std::string>> tenants_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
// Per-request tenant context: uuid plus slug plus strategy. Attached to the
|
||||
// request by TenantMiddleware. data_tenant() renders the legacy tenant string
|
||||
// carried by molo::data::Context.
|
||||
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/strategy.h"
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class TenantContext {
|
||||
public:
|
||||
TenantContext(std::string uuid, std::string slug, Strategy strategy)
|
||||
: uuid_(std::move(uuid)), slug_(std::move(slug)), strategy_(strategy) {}
|
||||
|
||||
static TenantContext FromTenant(const Tenant& tenant) {
|
||||
return TenantContext(tenant.id(), tenant.slug(), tenant.strategy());
|
||||
}
|
||||
|
||||
const std::string& uuid() const { return uuid_; }
|
||||
const std::string& slug() const { return slug_; }
|
||||
Strategy strategy() const { return strategy_; }
|
||||
|
||||
std::string data_tenant() const { return "tenant:" + slug_; }
|
||||
|
||||
private:
|
||||
std::string uuid_;
|
||||
std::string slug_;
|
||||
Strategy strategy_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,51 @@
|
||||
#pragma once
|
||||
// FeatureFlags holds global flag defaults with per-tenant overrides.
|
||||
// Bounded at kFlagsMax definitions; unknown flags read as false.
|
||||
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class FeatureFlags {
|
||||
public:
|
||||
bool define(const std::string& name, bool default_value) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (defaults_.find(name) == defaults_.end() && defaults_.size() >= Caps::kFlagsMax) {
|
||||
return false;
|
||||
}
|
||||
defaults_[name] = default_value;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool set_tenant(const std::string& slug, const std::string& name, bool value) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (defaults_.find(name) == defaults_.end()) return false;
|
||||
overrides_[slug + '\x1f' + name] = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool enabled(const std::string& slug, const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto ov = overrides_.find(slug + '\x1f' + name);
|
||||
if (ov != overrides_.end()) return ov->second;
|
||||
auto def = defaults_.find(name);
|
||||
return def == defaults_.end() ? false : def->second;
|
||||
}
|
||||
|
||||
std::size_t count() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return defaults_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<std::string, bool> defaults_;
|
||||
std::unordered_map<std::string, bool> overrides_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
// TenantMetrics counts requests and errors per tenant with a bounded label
|
||||
// set: the first kMetricTenantsMax slugs keep their own label, every later
|
||||
// tenant folds into "other" so cardinality can never explode.
|
||||
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class TenantMetrics {
|
||||
public:
|
||||
struct Counters {
|
||||
std::uint64_t requests = 0;
|
||||
std::uint64_t errors = 0;
|
||||
};
|
||||
|
||||
std::string label_for(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (slug == kOther) return kOther;
|
||||
if (labels_.find(slug) != labels_.end()) return slug;
|
||||
if (labels_.size() >= Caps::kMetricTenantsMax) return kOther;
|
||||
labels_.insert(slug);
|
||||
return slug;
|
||||
}
|
||||
|
||||
void record_request(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
counts_[LabelLocked(slug)].requests += 1;
|
||||
}
|
||||
|
||||
void record_error(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
counts_[LabelLocked(slug)].errors += 1;
|
||||
}
|
||||
|
||||
std::map<std::string, Counters> snapshot() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return std::map<std::string, Counters>(counts_.begin(), counts_.end());
|
||||
}
|
||||
|
||||
private:
|
||||
static const char* kOther;
|
||||
|
||||
std::string LabelLocked(const std::string& slug) {
|
||||
if (slug == kOther) return kOther;
|
||||
if (labels_.find(slug) != labels_.end()) return slug;
|
||||
if (labels_.size() >= Caps::kMetricTenantsMax) return kOther;
|
||||
labels_.insert(slug);
|
||||
return slug;
|
||||
}
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_set<std::string> labels_;
|
||||
std::unordered_map<std::string, Counters> counts_;
|
||||
};
|
||||
|
||||
inline const char* TenantMetrics::kOther = "other";
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
// TenantMiddleware resolves the tenant, strips the /t/<slug> path prefix and
|
||||
// attaches a TenantContext plus the legacy data tenant string to the request
|
||||
// as extensions. Category Security: register it first in that category so it
|
||||
// runs right after observability and before all other security middleware.
|
||||
// Unknown maps to 404 tenant_unknown, suspended to 403 tenant_suspended,
|
||||
// conflicting sources to 400 tenant_conflict.
|
||||
|
||||
#include <string>
|
||||
|
||||
#include "tenancy/adapters/http.h"
|
||||
#include "tenancy/catalog.h"
|
||||
#include "tenancy/context.h"
|
||||
#include "tenancy/resolver.h"
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class TenantMiddleware : public adapters::MiddlewareBase {
|
||||
public:
|
||||
TenantMiddleware(Catalog& catalog, Resolver resolver)
|
||||
: catalog_(catalog), resolver_(std::move(resolver)) {}
|
||||
|
||||
adapters::Category category() const override { return adapters::Category::Security; }
|
||||
std::string name() const override { return "tenant"; }
|
||||
|
||||
adapters::Task<adapters::HttpResponse> handle(adapters::HttpRequest& req,
|
||||
adapters::Next next) override {
|
||||
ResolveRequest rreq{req.header("host"), req.path(), req.header("x-tenant")};
|
||||
ResolveOutcome outcome = resolver_.Resolve(rreq, catalog_);
|
||||
if (outcome.status == ResolveStatus::Conflict) {
|
||||
co_return adapters::HttpResponse::FromError(
|
||||
adapters::HttpError::TenantConflict(outcome.detail));
|
||||
}
|
||||
if (outcome.status == ResolveStatus::Unknown || !outcome.tenant.has_value()) {
|
||||
co_return adapters::HttpResponse::FromError(
|
||||
adapters::HttpError::TenantUnknown(outcome.detail));
|
||||
}
|
||||
const Tenant& tenant = *outcome.tenant;
|
||||
if (tenant.status() == TenantStatus::Suspended) {
|
||||
co_return adapters::HttpResponse::FromError(
|
||||
adapters::HttpError::TenantSuspended("tenant suspended: " + tenant.slug()));
|
||||
}
|
||||
if (tenant.status() == TenantStatus::Tombstone) {
|
||||
co_return adapters::HttpResponse::FromError(
|
||||
adapters::HttpError::TenantUnknown("tenant removed: " + tenant.slug()));
|
||||
}
|
||||
req.set_path(Resolver::StripTenantPrefix(req.path()).first);
|
||||
TenantContext ctx = TenantContext::FromTenant(tenant);
|
||||
req.set_ext("tenancy.context", ctx);
|
||||
req.set_ext("tenancy.data_tenant", ctx.data_tenant());
|
||||
adapters::HttpResponse resp = co_await next(req);
|
||||
co_return resp;
|
||||
}
|
||||
|
||||
private:
|
||||
Catalog& catalog_;
|
||||
Resolver resolver_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
// OrmScope is the shared_schema scoping helper. ApplySelect/ApplyUpdate inject
|
||||
// a tenant_id predicate unless the caller is privileged or the statement is
|
||||
// already scoped. KeyPrefix/ScopedChannel render the tenant:<id>: prefix used
|
||||
// for cache keys and pubsub channels.
|
||||
|
||||
#include <cctype>
|
||||
#include <string>
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class OrmScope {
|
||||
public:
|
||||
static std::string TenantColumn() { return "tenant_id"; }
|
||||
|
||||
static std::string KeyPrefix(const std::string& slug) { return "tenant:" + slug + ":"; }
|
||||
|
||||
static std::string ScopedChannel(const std::string& slug, const std::string& channel) {
|
||||
return "tenant:" + slug + ":" + channel;
|
||||
}
|
||||
|
||||
static std::string FilterClause(const std::string& slug) {
|
||||
return "tenant_id = '" + Escape(slug) + "'";
|
||||
}
|
||||
|
||||
static std::string ApplySelect(const std::string& sql,
|
||||
const std::string& slug,
|
||||
bool privileged) {
|
||||
return ApplyWhere(sql, slug, privileged);
|
||||
}
|
||||
|
||||
static std::string ApplyUpdate(const std::string& sql,
|
||||
const std::string& slug,
|
||||
bool privileged) {
|
||||
return ApplyWhere(sql, slug, privileged);
|
||||
}
|
||||
|
||||
static std::string InsertWithTenant(const std::string& table,
|
||||
const std::string& columns,
|
||||
const std::string& placeholders,
|
||||
const std::string& slug) {
|
||||
return "INSERT INTO " + table + " (tenant_id, " + columns + ") VALUES ('" +
|
||||
Escape(slug) + "', " + placeholders + ")";
|
||||
}
|
||||
|
||||
private:
|
||||
static std::string Escape(const std::string& raw) {
|
||||
std::string out;
|
||||
for (char c : raw) {
|
||||
if (c == '\'') out += '\'';
|
||||
out += c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
static std::size_t FindKeyword(const std::string& sql,
|
||||
const std::string& keyword,
|
||||
std::size_t from) {
|
||||
for (std::size_t i = from; i + keyword.size() <= sql.size(); ++i) {
|
||||
bool match = true;
|
||||
for (std::size_t k = 0; k < keyword.size(); ++k) {
|
||||
if (std::tolower(static_cast<unsigned char>(sql[i + k])) != keyword[k]) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (match) return i;
|
||||
}
|
||||
return std::string::npos;
|
||||
}
|
||||
|
||||
static std::string ApplyWhere(const std::string& sql,
|
||||
const std::string& slug,
|
||||
bool privileged) {
|
||||
if (privileged) return sql;
|
||||
if (FindKeyword(sql, "tenant_id", 0) != std::string::npos) return sql;
|
||||
std::size_t where = FindKeyword(sql, "where", 0);
|
||||
if (where != std::string::npos) {
|
||||
std::string out = sql;
|
||||
out.insert(where + 5, " " + FilterClause(slug) + " AND");
|
||||
return out;
|
||||
}
|
||||
std::size_t tail = sql.size();
|
||||
for (const char* kw : {"group by", "order by", "limit", "offset"}) {
|
||||
std::size_t pos = FindKeyword(sql, kw, 0);
|
||||
if (pos != std::string::npos && pos < tail) tail = pos;
|
||||
}
|
||||
std::string out = sql;
|
||||
out.insert(tail, " WHERE " + FilterClause(slug));
|
||||
return out;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,160 @@
|
||||
#pragma once
|
||||
// PoolFactory mirrors the Pool<Conn> checkout discipline per tenant: acquire
|
||||
// asserts an empty scope then sets it to the tenant slug (SET LOCAL
|
||||
// app.current_tenant on pg, attached file on sqlite); the RAII Lease resets
|
||||
// the scope on release. Registry capped at kPoolTenantsMax, reusable slots at
|
||||
// kPoolSlotsMax. A dirty slot on acquire throws instead of leaking a tenant.
|
||||
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <unordered_set>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/adapters/db.h"
|
||||
#include "tenancy/caps.h"
|
||||
#include "tenancy/tenant_id.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class PoolFactory {
|
||||
public:
|
||||
using Backend = adapters::db::Backend;
|
||||
|
||||
class Lease {
|
||||
public:
|
||||
Lease() : factory_(nullptr), slot_(0) {}
|
||||
~Lease() { release(); }
|
||||
|
||||
Lease(Lease&& other) noexcept
|
||||
: factory_(std::exchange(other.factory_, nullptr)),
|
||||
slot_(other.slot_),
|
||||
slug_(std::move(other.slug_)),
|
||||
backend_(other.backend_) {}
|
||||
Lease& operator=(Lease&& other) noexcept {
|
||||
if (this != &other) {
|
||||
release();
|
||||
factory_ = std::exchange(other.factory_, nullptr);
|
||||
slot_ = other.slot_;
|
||||
slug_ = std::move(other.slug_);
|
||||
backend_ = other.backend_;
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
Lease(const Lease&) = delete;
|
||||
Lease& operator=(const Lease&) = delete;
|
||||
|
||||
bool active() const { return factory_ != nullptr; }
|
||||
const std::string& slug() const { return slug_; }
|
||||
Backend backend() const { return backend_; }
|
||||
|
||||
std::string guc() const {
|
||||
if (factory_ == nullptr) return "";
|
||||
return factory_->SlotGuc(slot_);
|
||||
}
|
||||
|
||||
void release() {
|
||||
if (factory_ != nullptr) {
|
||||
factory_->ReleaseSlot(slot_);
|
||||
factory_ = nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
friend class PoolFactory;
|
||||
Lease(PoolFactory* factory, std::size_t slot, std::string slug, Backend backend)
|
||||
: factory_(factory), slot_(slot), slug_(std::move(slug)), backend_(backend) {}
|
||||
|
||||
PoolFactory* factory_;
|
||||
std::size_t slot_;
|
||||
std::string slug_;
|
||||
Backend backend_ = Backend::Postgres;
|
||||
};
|
||||
|
||||
Lease acquire(const std::string& slug, Backend backend) {
|
||||
if (!TenantId::TryParse(slug).has_value()) {
|
||||
throw adapters::db::DbError(ToDbBackend(backend), "invalid_tenant",
|
||||
"invalid tenant slug: " + slug);
|
||||
}
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (tenants_.find(slug) == tenants_.end()) {
|
||||
if (tenants_.size() >= Caps::kPoolTenantsMax) {
|
||||
throw adapters::db::DbError(ToDbBackend(backend), "too_many_tenants",
|
||||
"tenant registry cap reached");
|
||||
}
|
||||
tenants_.insert(slug);
|
||||
}
|
||||
std::size_t slot = slots_.size();
|
||||
for (std::size_t i = 0; i < slots_.size(); ++i) {
|
||||
if (!slots_[i].busy) {
|
||||
slot = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (slot == slots_.size()) {
|
||||
if (slots_.size() >= Caps::kPoolSlotsMax) {
|
||||
throw adapters::db::DbError(ToDbBackend(backend), "pool_exhausted",
|
||||
"no free pool slot");
|
||||
}
|
||||
slots_.push_back(Slot{});
|
||||
}
|
||||
if (!slots_[slot].guc.empty()) {
|
||||
throw adapters::db::DbError(ToDbBackend(backend), "scope_dirty",
|
||||
"slot scope not reset, refusing tenant " + slug);
|
||||
}
|
||||
slots_[slot].busy = true;
|
||||
slots_[slot].guc = slug;
|
||||
slots_[slot].backend = backend;
|
||||
++active_;
|
||||
return Lease(this, slot, slug, backend);
|
||||
}
|
||||
|
||||
std::size_t active_count() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return active_;
|
||||
}
|
||||
std::size_t tenant_count() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return tenants_.size();
|
||||
}
|
||||
std::size_t slot_count() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return slots_.size();
|
||||
}
|
||||
|
||||
void DebugDirtySlotForTest(std::size_t slot, std::string guc) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (slot >= slots_.size()) throw std::out_of_range("slot");
|
||||
slots_[slot].guc = std::move(guc);
|
||||
}
|
||||
|
||||
private:
|
||||
struct Slot {
|
||||
bool busy = false;
|
||||
std::string guc;
|
||||
Backend backend = Backend::Postgres;
|
||||
};
|
||||
|
||||
static adapters::db::Backend ToDbBackend(Backend b) { return b; }
|
||||
|
||||
void ReleaseSlot(std::size_t slot) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
slots_[slot].guc.clear();
|
||||
slots_[slot].busy = false;
|
||||
--active_;
|
||||
}
|
||||
|
||||
std::string SlotGuc(std::size_t slot) const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return slots_[slot].guc;
|
||||
}
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::vector<Slot> slots_;
|
||||
std::unordered_set<std::string> tenants_;
|
||||
std::size_t active_ = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,78 @@
|
||||
#pragma once
|
||||
// Provisioner creates and retires tenants. Backend hooks (schema, database,
|
||||
// file creation) run inside provision; a failing hook rolls the catalog entry
|
||||
// back so no half provisioned tenant survives. Purge delegates to the catalog
|
||||
// gates and only then runs the drop hook.
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/catalog.h"
|
||||
#include "tenancy/strategy.h"
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class Provisioner {
|
||||
public:
|
||||
using Hook = std::function<bool(const Tenant&)>;
|
||||
|
||||
struct Hooks {
|
||||
Hook on_create;
|
||||
Hook on_drop;
|
||||
};
|
||||
|
||||
Provisioner(Catalog& catalog, Hooks hooks = {}) : catalog_(catalog), hooks_(std::move(hooks)) {}
|
||||
|
||||
std::optional<Tenant> provision(const std::string& slug,
|
||||
Strategy strategy,
|
||||
std::int64_t now_unix) {
|
||||
auto tenant = catalog_.create(slug, strategy, now_unix);
|
||||
if (!tenant.has_value()) return std::nullopt;
|
||||
if (hooks_.on_create && !hooks_.on_create(*tenant)) {
|
||||
RollbackEntry(*tenant, now_unix);
|
||||
return std::nullopt;
|
||||
}
|
||||
return tenant;
|
||||
}
|
||||
|
||||
bool rollback(const std::string& slug, std::int64_t now_unix) {
|
||||
auto found = catalog_.find_by_slug(slug);
|
||||
if (!found.has_value()) return false;
|
||||
return RollbackEntry(*found, now_unix);
|
||||
}
|
||||
|
||||
bool suspend(const std::string& slug) { return catalog_.suspend(slug); }
|
||||
|
||||
bool tombstone(const std::string& slug, std::int64_t now_unix) {
|
||||
return catalog_.tombstone(slug, now_unix);
|
||||
}
|
||||
|
||||
PurgeResult purge(const std::string& slug,
|
||||
const std::string& confirm,
|
||||
std::int64_t now_unix,
|
||||
std::int64_t retention_sec) {
|
||||
auto found = catalog_.find_by_slug(slug);
|
||||
PurgeResult gated = catalog_.purge(slug, confirm, now_unix, retention_sec);
|
||||
if (gated == PurgeResult::Ok && hooks_.on_drop && found.has_value()) {
|
||||
hooks_.on_drop(*found);
|
||||
}
|
||||
return gated;
|
||||
}
|
||||
|
||||
private:
|
||||
bool RollbackEntry(const Tenant& tenant, std::int64_t now_unix) {
|
||||
if (hooks_.on_drop) hooks_.on_drop(tenant);
|
||||
catalog_.tombstone(tenant.slug(), now_unix);
|
||||
return catalog_.purge(tenant.slug(), "PURGE:" + tenant.id(), now_unix, 0) ==
|
||||
PurgeResult::Ok;
|
||||
}
|
||||
|
||||
Catalog& catalog_;
|
||||
Hooks hooks_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,112 @@
|
||||
#pragma once
|
||||
// Quota enforces per-tenant request rate (token bucket: rate plus burst,
|
||||
// 429 with retry_after on excess) and storage (507 insufficient_storage past
|
||||
// the byte cap). Clock is injected in millis for deterministic tests.
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
struct QuotaLimits {
|
||||
double requests_per_minute = Caps::kRequestsPerMinuteDefault;
|
||||
double burst = Caps::kRequestBurstDefault;
|
||||
std::int64_t storage_bytes = Caps::kStorageBytesDefault;
|
||||
};
|
||||
|
||||
class Quota {
|
||||
public:
|
||||
using Limits = QuotaLimits;
|
||||
|
||||
struct Verdict {
|
||||
bool allowed = true;
|
||||
int status = 200;
|
||||
std::int64_t retry_after_sec = 0;
|
||||
};
|
||||
|
||||
using Clock = std::function<std::int64_t()>;
|
||||
|
||||
explicit Quota(Limits limits = QuotaLimits{}, Clock clock = SystemClock)
|
||||
: limits_(limits), clock_(std::move(clock)) {}
|
||||
|
||||
static std::int64_t SystemClock() {
|
||||
return std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
std::chrono::steady_clock::now().time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
Verdict check_request(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
Bucket* bp = FindBucket(slug);
|
||||
if (bp == nullptr) return Verdict{false, 429, 60};
|
||||
Bucket& b = *bp;
|
||||
std::int64_t now = clock_();
|
||||
double rate_per_ms = limits_.requests_per_minute / 60000.0;
|
||||
double capacity = limits_.burst > 0 ? limits_.burst : 1.0;
|
||||
if (b.last_ms < 0) {
|
||||
b.tokens = capacity;
|
||||
} else if (now > b.last_ms) {
|
||||
b.tokens += static_cast<double>(now - b.last_ms) * rate_per_ms;
|
||||
if (b.tokens > capacity) b.tokens = capacity;
|
||||
}
|
||||
b.last_ms = now;
|
||||
if (b.tokens >= 1.0) {
|
||||
b.tokens -= 1.0;
|
||||
return Verdict{true, 200, 0};
|
||||
}
|
||||
double deficit = 1.0 - b.tokens;
|
||||
std::int64_t wait_ms =
|
||||
rate_per_ms > 0 ? static_cast<std::int64_t>(deficit / rate_per_ms) : 60000;
|
||||
return Verdict{false, 429, wait_ms / 1000 + 1};
|
||||
}
|
||||
|
||||
Verdict add_storage(const std::string& slug, std::int64_t bytes) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
Bucket* bp = FindBucket(slug);
|
||||
if (bp == nullptr) return Verdict{false, 507, 0};
|
||||
Bucket& b = *bp;
|
||||
if (b.storage_used + bytes > limits_.storage_bytes) {
|
||||
return Verdict{false, 507, 0};
|
||||
}
|
||||
b.storage_used += bytes;
|
||||
return Verdict{true, 200, 0};
|
||||
}
|
||||
|
||||
std::int64_t storage_used(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = buckets_.find(slug);
|
||||
return it == buckets_.end() ? 0 : it->second.storage_used;
|
||||
}
|
||||
|
||||
void reset(const std::string& slug) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
buckets_.erase(slug);
|
||||
}
|
||||
|
||||
private:
|
||||
struct Bucket {
|
||||
double tokens = 0.0;
|
||||
std::int64_t last_ms = -1;
|
||||
std::int64_t storage_used = 0;
|
||||
};
|
||||
|
||||
Bucket* FindBucket(const std::string& slug) {
|
||||
auto it = buckets_.find(slug);
|
||||
if (it != buckets_.end()) return &it->second;
|
||||
if (buckets_.size() >= Caps::kPoolTenantsMax) return nullptr;
|
||||
return &buckets_.emplace(slug, Bucket{}).first->second;
|
||||
}
|
||||
|
||||
Limits limits_;
|
||||
Clock clock_;
|
||||
std::mutex mu_;
|
||||
std::unordered_map<std::string, Bucket> buckets_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,113 @@
|
||||
#pragma once
|
||||
// Resolver maps a request to a tenant from three sources: the X-Tenant
|
||||
// header, the /t/<slug> path prefix, and the host subdomain in the form
|
||||
// <slug>.<base domain> for a configured base. Matrix: exactly one distinct
|
||||
// slug resolves; two distinct slugs conflict; none resolves to the dev
|
||||
// default only when dev mode is on, else unknown.
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/adapters/http.h"
|
||||
#include "tenancy/catalog.h"
|
||||
#include "tenancy/tenant.h"
|
||||
#include "tenancy/tenant_id.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
struct ResolveRequest {
|
||||
std::string host;
|
||||
std::string path;
|
||||
std::string tenant_header;
|
||||
};
|
||||
|
||||
enum class ResolveStatus { Resolved, Conflict, Unknown };
|
||||
|
||||
struct ResolveOutcome {
|
||||
ResolveStatus status = ResolveStatus::Unknown;
|
||||
std::optional<Tenant> tenant;
|
||||
bool dev_default = false;
|
||||
std::string detail;
|
||||
};
|
||||
|
||||
struct ResolverOptions {
|
||||
bool dev_mode = false;
|
||||
std::string dev_default_slug = "dev";
|
||||
std::vector<std::string> base_domains = {"localhost"};
|
||||
};
|
||||
|
||||
class Resolver {
|
||||
public:
|
||||
using Options = ResolverOptions;
|
||||
|
||||
explicit Resolver(Options opts = ResolverOptions{}) : opts_(std::move(opts)) {}
|
||||
|
||||
static std::pair<std::string, std::string> StripTenantPrefix(const std::string& path) {
|
||||
if (path == "/t" || path.compare(0, 3, "/t/") != 0) return {path, ""};
|
||||
std::string rest = path.substr(3);
|
||||
std::size_t slash = rest.find('/');
|
||||
std::string slug = slash == std::string::npos ? rest : rest.substr(0, slash);
|
||||
if (!TenantId::TryParse(slug).has_value()) return {path, ""};
|
||||
std::string stripped = slash == std::string::npos ? "/" : rest.substr(slash);
|
||||
if (stripped.empty()) stripped = "/";
|
||||
return {stripped, slug};
|
||||
}
|
||||
|
||||
static std::string SlugFromHost(const std::string& host,
|
||||
const std::vector<std::string>& base_domains) {
|
||||
std::string bare = host;
|
||||
std::size_t colon = bare.find(':');
|
||||
if (colon != std::string::npos) bare = bare.substr(0, colon);
|
||||
bare = adapters::Lower(bare);
|
||||
for (const std::string& base : base_domains) {
|
||||
std::string suffix = "." + adapters::Lower(base);
|
||||
if (bare.size() <= suffix.size()) continue;
|
||||
if (bare.compare(bare.size() - suffix.size(), suffix.size(), suffix) != 0) continue;
|
||||
std::string label = bare.substr(0, bare.size() - suffix.size());
|
||||
if (label.find('.') != std::string::npos) continue;
|
||||
if (!TenantId::TryParse(label).has_value()) continue;
|
||||
return label;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
ResolveOutcome Resolve(const ResolveRequest& req, Catalog& catalog) const {
|
||||
std::string from_header =
|
||||
TenantId::TryParse(req.tenant_header).has_value() ? req.tenant_header : "";
|
||||
std::string from_path = StripTenantPrefix(req.path).second;
|
||||
std::string from_host = SlugFromHost(req.host, opts_.base_domains);
|
||||
|
||||
std::string chosen;
|
||||
for (const std::string* cand : {&from_header, &from_path, &from_host}) {
|
||||
if (cand->empty()) continue;
|
||||
if (chosen.empty()) {
|
||||
chosen = *cand;
|
||||
} else if (chosen != *cand) {
|
||||
return ResolveOutcome{ResolveStatus::Conflict, std::nullopt, false,
|
||||
"tenant sources disagree"};
|
||||
}
|
||||
}
|
||||
|
||||
bool dev_default = false;
|
||||
if (chosen.empty()) {
|
||||
if (!opts_.dev_mode) return ResolveOutcome{ResolveStatus::Unknown, std::nullopt,
|
||||
false, "no tenant source"};
|
||||
chosen = opts_.dev_default_slug;
|
||||
dev_default = true;
|
||||
}
|
||||
|
||||
auto tenant = catalog.find_by_slug(chosen);
|
||||
if (!tenant.has_value()) {
|
||||
return ResolveOutcome{ResolveStatus::Unknown, std::nullopt, false,
|
||||
"unknown tenant: " + chosen};
|
||||
}
|
||||
return ResolveOutcome{ResolveStatus::Resolved, tenant, dev_default, ""};
|
||||
}
|
||||
|
||||
private:
|
||||
Options opts_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
// RlsPolicy renders Postgres row level security DDL for shared_schema tables.
|
||||
// The policy reads app.current_tenant, which PoolFactory sets on every pinned
|
||||
// checkout and resets on release. Table names are caller validated.
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class RlsPolicy {
|
||||
public:
|
||||
static std::string SettingName() { return "app.current_tenant"; }
|
||||
|
||||
static std::string EnableRls(const std::string& table) {
|
||||
return "ALTER TABLE " + table + " ENABLE ROW LEVEL SECURITY";
|
||||
}
|
||||
|
||||
static std::string PolicyDdl(const std::string& table) {
|
||||
return "CREATE POLICY tenant_isolation ON " + table +
|
||||
" USING (tenant_id = current_setting('app.current_tenant', true)) " +
|
||||
"WITH CHECK (tenant_id = current_setting('app.current_tenant', true))";
|
||||
}
|
||||
|
||||
static std::string DropPolicy(const std::string& table) {
|
||||
return "DROP POLICY IF EXISTS tenant_isolation ON " + table;
|
||||
}
|
||||
|
||||
static std::string SetLocal(const std::string& slug) {
|
||||
return "SET LOCAL app.current_tenant = '" + slug + "'";
|
||||
}
|
||||
|
||||
static std::string ResetLocal() { return "RESET app.current_tenant"; }
|
||||
|
||||
static std::string TenantIndexDdl(const std::string& table) {
|
||||
return "CREATE INDEX IF NOT EXISTS " + table +
|
||||
"_tenant_idx ON " + table + " (tenant_id)";
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
// Abstract tenant catalog storage. MemoryCatalog serves dev and tests;
|
||||
// DbCatalog persists the same records in the tenants table.
|
||||
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace molo::tenancy::store {
|
||||
|
||||
class CatalogStore {
|
||||
public:
|
||||
virtual ~CatalogStore() = default;
|
||||
virtual bool upsert(const Tenant& tenant) = 0;
|
||||
virtual std::optional<Tenant> get_by_id(const std::string& id) = 0;
|
||||
virtual std::optional<Tenant> get_by_slug(const std::string& slug) = 0;
|
||||
virtual bool remove(const std::string& id) = 0;
|
||||
virtual std::vector<Tenant> list(std::size_t limit) = 0;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy::store
|
||||
@@ -0,0 +1,119 @@
|
||||
#pragma once
|
||||
// DbCatalog persists tenant records in a tenants table through the
|
||||
// Connection::exec seam only. SQL uses positional ? placeholders accepted by
|
||||
// both backends. Catalog reads run with an empty data tenant string: the
|
||||
// catalog itself is never tenant scoped.
|
||||
|
||||
#include <cstddef>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/adapters/db.h"
|
||||
#include "tenancy/store/catalog_store.h"
|
||||
#include "tenancy/strategy.h"
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace molo::tenancy::store {
|
||||
|
||||
class DbCatalog : public CatalogStore {
|
||||
public:
|
||||
explicit DbCatalog(adapters::db::Connection& conn) : conn_(conn) {}
|
||||
|
||||
void ensure_schema() {
|
||||
adapters::db::Context ctx("tenancy-catalog", "", 30);
|
||||
conn_.exec(ctx, adapters::db::BoundStatement::Raw(
|
||||
"CREATE TABLE IF NOT EXISTS tenants (id TEXT PRIMARY KEY, "
|
||||
"slug TEXT UNIQUE NOT NULL, strategy TEXT NOT NULL, "
|
||||
"status TEXT NOT NULL, storage_bytes BIGINT NOT NULL, "
|
||||
"created_unix BIGINT NOT NULL, tombstoned_unix BIGINT NOT NULL)"));
|
||||
}
|
||||
|
||||
bool upsert(const Tenant& tenant) override {
|
||||
adapters::db::Context ctx("tenancy-catalog", "", 30);
|
||||
adapters::db::Result updated = conn_.exec(
|
||||
ctx, adapters::db::BoundStatement::Raw(
|
||||
"UPDATE tenants SET slug=?, strategy=?, status=?, storage_bytes=?, "
|
||||
"created_unix=?, tombstoned_unix=? WHERE id=?",
|
||||
{adapters::db::MakeString(tenant.slug()),
|
||||
adapters::db::MakeString(ToString(tenant.strategy())),
|
||||
adapters::db::MakeString(ToString(tenant.status())),
|
||||
adapters::db::MakeInt(tenant.storage_bytes()),
|
||||
adapters::db::MakeInt(tenant.created_unix()),
|
||||
adapters::db::MakeInt(tenant.tombstoned_unix()),
|
||||
adapters::db::MakeString(tenant.id())}));
|
||||
if (updated.affected > 0) return true;
|
||||
adapters::db::Result inserted = conn_.exec(
|
||||
ctx, adapters::db::BoundStatement::Raw(
|
||||
"INSERT INTO tenants (id, slug, strategy, status, storage_bytes, "
|
||||
"created_unix, tombstoned_unix) VALUES (?,?,?,?,?,?,?)",
|
||||
{adapters::db::MakeString(tenant.id()),
|
||||
adapters::db::MakeString(tenant.slug()),
|
||||
adapters::db::MakeString(ToString(tenant.strategy())),
|
||||
adapters::db::MakeString(ToString(tenant.status())),
|
||||
adapters::db::MakeInt(tenant.storage_bytes()),
|
||||
adapters::db::MakeInt(tenant.created_unix()),
|
||||
adapters::db::MakeInt(tenant.tombstoned_unix())}));
|
||||
return inserted.affected > 0;
|
||||
}
|
||||
|
||||
std::optional<Tenant> get_by_id(const std::string& id) override {
|
||||
return SelectOne(
|
||||
"SELECT id, slug, strategy, status, storage_bytes, created_unix, "
|
||||
"tombstoned_unix FROM tenants WHERE id=?",
|
||||
adapters::db::MakeString(id));
|
||||
}
|
||||
|
||||
std::optional<Tenant> get_by_slug(const std::string& slug) override {
|
||||
return SelectOne(
|
||||
"SELECT id, slug, strategy, status, storage_bytes, created_unix, "
|
||||
"tombstoned_unix FROM tenants WHERE slug=?",
|
||||
adapters::db::MakeString(slug));
|
||||
}
|
||||
|
||||
bool remove(const std::string& id) override {
|
||||
adapters::db::Context ctx("tenancy-catalog", "", 30);
|
||||
adapters::db::Result r = conn_.exec(
|
||||
ctx, adapters::db::BoundStatement::Raw("DELETE FROM tenants WHERE id=?",
|
||||
{adapters::db::MakeString(id)}));
|
||||
return r.affected > 0;
|
||||
}
|
||||
|
||||
std::vector<Tenant> list(std::size_t limit) override {
|
||||
adapters::db::Context ctx("tenancy-catalog", "", 30);
|
||||
adapters::db::Result r = conn_.exec(
|
||||
ctx, adapters::db::BoundStatement::Raw(
|
||||
"SELECT id, slug, strategy, status, storage_bytes, created_unix, "
|
||||
"tombstoned_unix FROM tenants ORDER BY id LIMIT ?",
|
||||
{adapters::db::MakeInt(static_cast<std::int64_t>(limit))}));
|
||||
std::vector<Tenant> out;
|
||||
for (const auto& row : r.rows) out.push_back(FromRow(row));
|
||||
return out;
|
||||
}
|
||||
|
||||
private:
|
||||
std::optional<Tenant> SelectOne(const std::string& sql, adapters::db::Value param) {
|
||||
adapters::db::Context ctx("tenancy-catalog", "", 30);
|
||||
adapters::db::Result r = conn_.exec(
|
||||
ctx, adapters::db::BoundStatement::Raw(sql, {std::move(param)}));
|
||||
if (r.rows.empty()) return std::nullopt;
|
||||
return FromRow(r.rows.front());
|
||||
}
|
||||
|
||||
static Tenant FromRow(const adapters::db::Row& row) {
|
||||
auto get = [&row](const std::string& key) -> adapters::db::Value {
|
||||
auto it = row.find(key);
|
||||
return it == row.end() ? adapters::db::Value{nullptr} : it->second;
|
||||
};
|
||||
return Tenant(adapters::db::AsString(get("id")), adapters::db::AsString(get("slug")),
|
||||
ParseStrategy(adapters::db::AsString(get("strategy"))),
|
||||
ParseStatus(adapters::db::AsString(get("status"))),
|
||||
adapters::db::AsInt(get("storage_bytes")),
|
||||
adapters::db::AsInt(get("created_unix")),
|
||||
adapters::db::AsInt(get("tombstoned_unix")));
|
||||
}
|
||||
|
||||
adapters::db::Connection& conn_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy::store
|
||||
@@ -0,0 +1,81 @@
|
||||
#pragma once
|
||||
// In-memory CatalogStore. Mutex guarded, bounded by kCatalogTenantsMax.
|
||||
// New ids past the cap are rejected; updates to existing ids still succeed.
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
#include "tenancy/store/catalog_store.h"
|
||||
#include "tenancy/tenant.h"
|
||||
|
||||
namespace molo::tenancy::store {
|
||||
|
||||
class MemoryCatalog : public CatalogStore {
|
||||
public:
|
||||
bool upsert(const Tenant& tenant) override {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = by_id_.find(tenant.id());
|
||||
if (it == by_id_.end() && by_id_.size() >= Caps::kCatalogTenantsMax) return false;
|
||||
if (it != by_id_.end() && it->second.slug() != tenant.slug()) {
|
||||
slug_to_id_.erase(it->second.slug());
|
||||
}
|
||||
by_id_.insert_or_assign(tenant.id(), tenant);
|
||||
slug_to_id_[tenant.slug()] = tenant.id();
|
||||
return true;
|
||||
}
|
||||
|
||||
std::optional<Tenant> get_by_id(const std::string& id) override {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return std::nullopt;
|
||||
return it->second;
|
||||
}
|
||||
|
||||
std::optional<Tenant> get_by_slug(const std::string& slug) override {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = slug_to_id_.find(slug);
|
||||
if (it == slug_to_id_.end()) return std::nullopt;
|
||||
auto jt = by_id_.find(it->second);
|
||||
if (jt == by_id_.end()) return std::nullopt;
|
||||
return jt->second;
|
||||
}
|
||||
|
||||
bool remove(const std::string& id) override {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return false;
|
||||
slug_to_id_.erase(it->second.slug());
|
||||
by_id_.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
std::vector<Tenant> list(std::size_t limit) override {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
std::vector<Tenant> out;
|
||||
for (const auto& [id, tenant] : by_id_) {
|
||||
if (out.size() >= limit) break;
|
||||
out.push_back(tenant);
|
||||
}
|
||||
std::sort(out.begin(), out.end(),
|
||||
[](const Tenant& a, const Tenant& b) { return a.id() < b.id(); });
|
||||
return out;
|
||||
}
|
||||
|
||||
std::size_t size() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return by_id_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<std::string, Tenant> by_id_;
|
||||
std::unordered_map<std::string, std::string> slug_to_id_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy::store
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
// Tenant isolation strategy. SharedSchema keeps one schema with a tenant_id
|
||||
// column plus RLS; SchemaPerTenant isolates by schema; DatabasePerTenant by
|
||||
// database (pg) ; FilePerTenant by SQLite file (bridge).
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
enum class Strategy {
|
||||
SharedSchema,
|
||||
SchemaPerTenant,
|
||||
DatabasePerTenant,
|
||||
FilePerTenant,
|
||||
};
|
||||
|
||||
inline std::string ToString(Strategy s) {
|
||||
switch (s) {
|
||||
case Strategy::SharedSchema:
|
||||
return "shared_schema";
|
||||
case Strategy::SchemaPerTenant:
|
||||
return "schema_per_tenant";
|
||||
case Strategy::DatabasePerTenant:
|
||||
return "database_per_tenant";
|
||||
case Strategy::FilePerTenant:
|
||||
return "file_per_tenant";
|
||||
}
|
||||
return "shared_schema";
|
||||
}
|
||||
|
||||
inline std::optional<Strategy> TryParseStrategy(std::string_view raw) {
|
||||
if (raw == "shared_schema") return Strategy::SharedSchema;
|
||||
if (raw == "schema_per_tenant") return Strategy::SchemaPerTenant;
|
||||
if (raw == "database_per_tenant") return Strategy::DatabasePerTenant;
|
||||
if (raw == "file_per_tenant") return Strategy::FilePerTenant;
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
inline Strategy ParseStrategy(std::string_view raw) {
|
||||
auto parsed = TryParseStrategy(raw);
|
||||
return parsed.has_value() ? *parsed : Strategy::SharedSchema;
|
||||
}
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
// Tenant record: identity, isolation strategy, lifecycle status and usage.
|
||||
// Tombstone is a terminal marker: a tombstoned tenant serves nothing and can
|
||||
// only be purged after the retention gate.
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/strategy.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
enum class TenantStatus { Active, Suspended, Tombstone };
|
||||
|
||||
inline std::string ToString(TenantStatus s) {
|
||||
switch (s) {
|
||||
case TenantStatus::Active:
|
||||
return "active";
|
||||
case TenantStatus::Suspended:
|
||||
return "suspended";
|
||||
case TenantStatus::Tombstone:
|
||||
return "tombstone";
|
||||
}
|
||||
return "active";
|
||||
}
|
||||
|
||||
inline TenantStatus ParseStatus(const std::string& raw) {
|
||||
if (raw == "suspended") return TenantStatus::Suspended;
|
||||
if (raw == "tombstone") return TenantStatus::Tombstone;
|
||||
return TenantStatus::Active;
|
||||
}
|
||||
|
||||
class Tenant {
|
||||
public:
|
||||
Tenant(std::string id,
|
||||
std::string slug,
|
||||
Strategy strategy,
|
||||
TenantStatus status,
|
||||
std::int64_t storage_bytes,
|
||||
std::int64_t created_unix,
|
||||
std::int64_t tombstoned_unix)
|
||||
: id_(std::move(id)),
|
||||
slug_(std::move(slug)),
|
||||
strategy_(strategy),
|
||||
status_(status),
|
||||
storage_bytes_(storage_bytes),
|
||||
created_unix_(created_unix),
|
||||
tombstoned_unix_(tombstoned_unix) {}
|
||||
|
||||
const std::string& id() const { return id_; }
|
||||
const std::string& slug() const { return slug_; }
|
||||
Strategy strategy() const { return strategy_; }
|
||||
TenantStatus status() const { return status_; }
|
||||
std::int64_t storage_bytes() const { return storage_bytes_; }
|
||||
std::int64_t created_unix() const { return created_unix_; }
|
||||
std::int64_t tombstoned_unix() const { return tombstoned_unix_; }
|
||||
|
||||
bool is_active() const { return status_ == TenantStatus::Active; }
|
||||
|
||||
void suspend() {
|
||||
if (status_ == TenantStatus::Active) status_ = TenantStatus::Suspended;
|
||||
}
|
||||
void mark_tombstone(std::int64_t now_unix) {
|
||||
status_ = TenantStatus::Tombstone;
|
||||
tombstoned_unix_ = now_unix;
|
||||
}
|
||||
void add_storage(std::int64_t bytes) { storage_bytes_ += bytes; }
|
||||
|
||||
private:
|
||||
std::string id_;
|
||||
std::string slug_;
|
||||
Strategy strategy_;
|
||||
TenantStatus status_;
|
||||
std::int64_t storage_bytes_;
|
||||
std::int64_t created_unix_;
|
||||
std::int64_t tombstoned_unix_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,78 @@
|
||||
#pragma once
|
||||
// TenantBuckets is a named token bucket registry for tenant scoped rate
|
||||
// limits (per route, per key, per operation). Named buckets carry their own
|
||||
// capacity and refill rate; entries are tenant plus key pairs. Time is caller
|
||||
// supplied millis so behavior stays deterministic in tests.
|
||||
|
||||
#include <cstdint>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class TenantBuckets {
|
||||
public:
|
||||
struct Spec {
|
||||
double capacity = 100.0;
|
||||
double refill_per_sec = 10.0;
|
||||
};
|
||||
|
||||
bool configure(const std::string& bucket, Spec spec) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
if (specs_.find(bucket) == specs_.end() && specs_.size() >= Caps::kRateBucketsMax) {
|
||||
return false;
|
||||
}
|
||||
specs_[bucket] = spec;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool take(const std::string& bucket,
|
||||
const std::string& key,
|
||||
std::int64_t now_ms,
|
||||
double count = 1.0) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
auto spec = specs_.find(bucket);
|
||||
if (spec == specs_.end()) return false;
|
||||
std::string entry = bucket + '\x1f' + key;
|
||||
auto it = entries_.find(entry);
|
||||
if (it == entries_.end()) {
|
||||
if (entries_.size() >= Caps::kBucketEntriesMax) return false;
|
||||
it = entries_.emplace(entry, Entry{spec->second.capacity, now_ms}).first;
|
||||
}
|
||||
Entry& e = it->second;
|
||||
if (now_ms > e.last_ms) {
|
||||
e.tokens += static_cast<double>(now_ms - e.last_ms) / 1000.0 * spec->second.refill_per_sec;
|
||||
if (e.tokens > spec->second.capacity) e.tokens = spec->second.capacity;
|
||||
e.last_ms = now_ms;
|
||||
}
|
||||
if (e.tokens < count) return false;
|
||||
e.tokens -= count;
|
||||
return true;
|
||||
}
|
||||
|
||||
void reset(const std::string& bucket, const std::string& key) {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
entries_.erase(bucket + '\x1f' + key);
|
||||
}
|
||||
|
||||
std::size_t entries() const {
|
||||
std::lock_guard<std::mutex> lock(mu_);
|
||||
return entries_.size();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Entry {
|
||||
double tokens = 0.0;
|
||||
std::int64_t last_ms = 0;
|
||||
};
|
||||
|
||||
mutable std::mutex mu_;
|
||||
std::unordered_map<std::string, Spec> specs_;
|
||||
std::unordered_map<std::string, Entry> entries_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
// Validated tenant slug. Lowercase DNS-safe: [a-z0-9-], 1..63 chars,
|
||||
// must start and end with an alphanumeric.
|
||||
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
#include "tenancy/caps.h"
|
||||
|
||||
namespace molo::tenancy {
|
||||
|
||||
class TenantId {
|
||||
public:
|
||||
static std::optional<TenantId> TryParse(std::string_view raw) {
|
||||
if (raw.empty() || raw.size() > Caps::kSlugMaxLen) return std::nullopt;
|
||||
for (char c : raw) {
|
||||
bool ok = (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-';
|
||||
if (!ok) return std::nullopt;
|
||||
}
|
||||
auto alnum = [](char c) {
|
||||
return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9');
|
||||
};
|
||||
if (!alnum(raw.front()) || !alnum(raw.back())) return std::nullopt;
|
||||
return TenantId(std::string(raw));
|
||||
}
|
||||
|
||||
const std::string& slug() const { return slug_; }
|
||||
|
||||
std::uint64_t hash() const {
|
||||
std::uint64_t h = 1469598103934665603ULL;
|
||||
for (unsigned char c : slug_) {
|
||||
h ^= static_cast<std::uint64_t>(c);
|
||||
h *= 1099511628211ULL;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
bool operator==(const TenantId& other) const { return slug_ == other.slug_; }
|
||||
bool operator!=(const TenantId& other) const { return !(*this == other); }
|
||||
bool operator<(const TenantId& other) const { return slug_ < other.slug_; }
|
||||
|
||||
private:
|
||||
explicit TenantId(std::string slug) : slug_(std::move(slug)) {}
|
||||
std::string slug_;
|
||||
};
|
||||
|
||||
} // namespace molo::tenancy
|
||||
|
||||
namespace std {
|
||||
template <>
|
||||
struct hash<molo::tenancy::TenantId> {
|
||||
std::size_t operator()(const molo::tenancy::TenantId& id) const noexcept {
|
||||
return static_cast<std::size_t>(id.hash());
|
||||
}
|
||||
};
|
||||
} // namespace std
|
||||
Reference in New Issue
Block a user