Эх сурвалжийг харах

feat(functions): parse function descriptors and resolve HTTP routes

The `on` block a script exports is the function's whole trigger
declaration, so parsing it is the boundary between user input and the
runtime. Two rules shape this unit:

`id` lives in the source, never derived from the file path. A rename or a
move must carry the function's policy with it, which only works if
identity is declared rather than positional.

Parsing never throws. A script author's typo is data, not an exception -
the caller gets {ok, descriptor, error} and reports the first problem by
name. Unknown keys are ignored so a script written for a later server
still loads here.

Route resolution keeps 404 and 405 apart: collapsing them would let a GET
reach a function that declared `method: 'POST'`, and would lose the
`Allow:` header a 405 owes the client. A non-HTTP descriptor opens no
route whatever its other fields say, so a stale `route` on a cron
function is inert.

The test target compiles the source directly rather than linking
vectorapi_core: this unit has no database dependency, so it still builds
on the Void dev host where smartbotic-db-client cannot compile.

40 tests.
fszontagh 1 сар өмнө
parent
commit
4d83f3d586

+ 3 - 0
.gitignore

@@ -19,3 +19,6 @@ compile_commands.json
 # Client debs vendored into the Docker build when the pinned version has
 # dropped out of the apt repo index (build.sh populates this).
 packaging/vendor/*.deb
+
+# Agent worktrees and local session state
+.claude/

+ 2 - 0
src/CMakeLists.txt

@@ -31,6 +31,8 @@ add_library(vectorapi_core STATIC
     handlers/settings.cpp
     handlers/project_settings.cpp
     handlers/relations.cpp
+    functions/descriptor.cpp
+    functions/net_guard.cpp
 )
 target_include_directories(vectorapi_core PUBLIC
     ${CMAKE_CURRENT_SOURCE_DIR}

+ 413 - 0
src/functions/descriptor.cpp

@@ -0,0 +1,413 @@
+#include "functions/descriptor.hpp"
+
+#include <algorithm>
+#include <cctype>
+#include <set>
+
+namespace svapi::functions {
+namespace {
+
+std::string upper(std::string s) {
+    for (char& c : s) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
+    return s;
+}
+
+std::string trim(const std::string& s) {
+    const auto notSpace = [](unsigned char c) { return !std::isspace(c); };
+    const auto first = std::find_if(s.begin(), s.end(), notSpace);
+    const auto last = std::find_if(s.rbegin(), s.rend(), notSpace).base();
+    return first < last ? std::string(first, last) : std::string();
+}
+
+ParseResult fail(std::string message) {
+    ParseResult r;
+    r.ok = false;
+    r.error = std::move(message);
+    return r;
+}
+
+/// Split on '/' keeping interior empty fields (so "/a//b" cannot match "/a/b"),
+/// then drop the one empty field a leading and a trailing slash each produce.
+std::vector<std::string> segments(const std::string& s) {
+    std::vector<std::string> out;
+    std::string cur;
+    for (const char c : s) {
+        if (c == '/') {
+            out.push_back(cur);
+            cur.clear();
+        } else {
+            cur.push_back(c);
+        }
+    }
+    out.push_back(cur);
+    if (!out.empty() && out.front().empty()) out.erase(out.begin());
+    if (!out.empty() && out.back().empty()) out.pop_back();
+    return out;
+}
+
+bool isParamSegment(const std::string& seg) { return !seg.empty() && seg.front() == ':'; }
+
+// ------------------------------------------------------------------- cron
+
+struct CronField {
+    const char* name;
+    int min;
+    int max;
+    /// Three-letter aliases, lowest value first ("jan" = 1, "sun" = 0), or null
+    /// for the numeric-only fields.
+    const char* const* names;
+    int namesBase;
+};
+
+const char* const kMonthNames[] = {"jan", "feb", "mar", "apr", "may", "jun",
+                                   "jul", "aug", "sep", "oct", "nov", "dec", nullptr};
+const char* const kDowNames[] = {"sun", "mon", "tue", "wed", "thu", "fri", "sat", nullptr};
+
+const CronField kCronFields[5] = {
+    {"minute", 0, 59, nullptr, 0},
+    {"hour", 0, 23, nullptr, 0},
+    {"day-of-month", 1, 31, nullptr, 0},
+    {"month", 1, 12, kMonthNames, 1},
+    // 7 is Sunday as well, which every cron implementation accepts.
+    {"day-of-week", 0, 7, kDowNames, 0},
+};
+
+/// Resolve one endpoint of a cron range: digits, or a three-letter alias where
+/// the field has them. Returns false when it is neither, or out of range.
+bool cronValue(const std::string& tok, const CronField& f, int& out) {
+    if (tok.empty()) return false;
+    const bool numeric = std::all_of(tok.begin(), tok.end(),
+                                     [](unsigned char c) { return std::isdigit(c) != 0; });
+    if (numeric) {
+        try {
+            out = std::stoi(tok);
+        } catch (const std::exception&) {
+            return false; // absurdly long digit run
+        }
+    } else if (f.names != nullptr) {
+        const std::string low = [&] {
+            std::string s = tok;
+            for (char& c : s) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
+            return s;
+        }();
+        out = -1;
+        for (int i = 0; f.names[i] != nullptr; ++i) {
+            if (low == f.names[i]) {
+                out = f.namesBase + i;
+                break;
+            }
+        }
+        if (out < 0) return false;
+    } else {
+        return false;
+    }
+    return out >= f.min && out <= f.max;
+}
+
+/// Shape check for one comma list of a cron field: "*", "5", "1-5", "*/2",
+/// "1-5/2", "0,30". No schedule is computed here - that is the scheduler's job.
+bool cronFieldValid(const std::string& field, const CronField& f) {
+    if (field.empty()) return false;
+    std::size_t pos = 0;
+    while (pos <= field.size()) {
+        const std::size_t comma = field.find(',', pos);
+        const std::string item =
+            field.substr(pos, comma == std::string::npos ? std::string::npos : comma - pos);
+        if (item.empty()) return false;
+
+        std::string base = item;
+        const std::size_t slash = item.find('/');
+        if (slash != std::string::npos) {
+            base = item.substr(0, slash);
+            const std::string step = item.substr(slash + 1);
+            if (step.empty() || step.find('/') != std::string::npos) return false;
+            if (!std::all_of(step.begin(), step.end(),
+                             [](unsigned char c) { return std::isdigit(c) != 0; }))
+                return false;
+            // Length-capped before converting: parsing must never throw, and no
+            // real step needs more than two digits.
+            if (step.size() > 2) return false;
+            if (std::stoi(step) < 1) return false; // "*/0" would never fire
+        }
+
+        if (base != "*") {
+            const std::size_t dash = base.find('-', 1); // 1: no negative endpoints
+            if (dash == std::string::npos) {
+                int v = 0;
+                if (!cronValue(base, f, v)) return false;
+            } else {
+                int lo = 0;
+                int hi = 0;
+                if (!cronValue(base.substr(0, dash), f, lo)) return false;
+                if (!cronValue(base.substr(dash + 1), f, hi)) return false;
+                if (lo > hi) return false;
+            }
+        }
+
+        if (comma == std::string::npos) break;
+        pos = comma + 1;
+        if (pos == field.size()) return false; // trailing comma
+    }
+    return true;
+}
+
+/// Validate a 5-field cron expression's shape. Returns an empty string when the
+/// expression is well formed, otherwise the first problem found.
+std::string cronError(const std::string& schedule) {
+    std::vector<std::string> fields;
+    std::string cur;
+    for (const char c : schedule) {
+        if (std::isspace(static_cast<unsigned char>(c)) != 0) {
+            if (!cur.empty()) fields.push_back(cur);
+            cur.clear();
+        } else {
+            cur.push_back(c);
+        }
+    }
+    if (!cur.empty()) fields.push_back(cur);
+
+    if (fields.size() != 5)
+        return "cron 'schedule' must have exactly 5 fields (minute hour day-of-month month "
+               "day-of-week), got " +
+               std::to_string(fields.size());
+    for (std::size_t i = 0; i < 5; ++i) {
+        if (!cronFieldValid(fields[i], kCronFields[i]))
+            return std::string("cron 'schedule' field ") + std::to_string(i + 1) + " (" +
+                   kCronFields[i].name + ") is not valid: '" + fields[i] + "'";
+    }
+    return {};
+}
+
+// ------------------------------------------------------------------- http
+
+/// Returns an empty string when `route` is a usable pattern.
+std::string routeError(const std::string& route) {
+    if (route.empty()) return "http 'route' is required and must not be empty";
+    if (route.front() != '/') return "http 'route' must start with '/': '" + route + "'";
+    std::set<std::string> seen;
+    for (const std::string& seg : segments(route)) {
+        if (!isParamSegment(seg)) continue;
+        const std::string name = seg.substr(1);
+        if (name.empty()) return "http 'route' has an unnamed ':' parameter: '" + route + "'";
+        if (!seen.insert(name).second)
+            return "http 'route' declares parameter ':" + name + "' twice: '" + route + "'";
+    }
+    return {};
+}
+
+/// Accept a single string or an array of strings; normalise to upper case and
+/// drop duplicates while keeping declaration order. An empty result means the
+/// key was absent, which is "any method".
+std::string parseMethods(const nlohmann::json& on, std::vector<std::string>& out) {
+    if (!on.contains("method")) return {};
+    const nlohmann::json& m = on.at("method");
+
+    std::vector<std::string> raw;
+    if (m.is_string()) {
+        raw.push_back(m.get<std::string>());
+    } else if (m.is_array()) {
+        if (m.empty())
+            return "'method' must not be an empty array (omit the key to accept any method)";
+        for (const nlohmann::json& e : m) {
+            if (!e.is_string()) return "'method' array must contain only strings";
+            raw.push_back(e.get<std::string>());
+        }
+    } else {
+        return "'method' must be a string or an array of strings";
+    }
+
+    std::set<std::string> seen;
+    for (const std::string& r : raw) {
+        const std::string norm = upper(trim(r));
+        if (norm.empty()) return "'method' must not contain an empty value";
+        if (!std::all_of(norm.begin(), norm.end(),
+                         [](unsigned char c) { return std::isalpha(c) != 0; }))
+            return "'method' value is not an HTTP method: '" + r + "'";
+        if (seen.insert(norm).second) out.push_back(norm);
+    }
+    return {};
+}
+
+} // namespace
+
+bool FunctionDescriptor::acceptsMethod(const std::string& method) const {
+    if (methods.empty()) return true; // no declaration = every method
+    const std::string norm = upper(method);
+    return std::find(methods.begin(), methods.end(), norm) != methods.end();
+}
+
+nlohmann::json FunctionDescriptor::toJson() const {
+    nlohmann::json j = nlohmann::json::object();
+    j["id"] = id;
+    switch (type) {
+    case TriggerType::Http:
+        j["type"] = "http";
+        j["route"] = route;
+        if (!methods.empty()) j["method"] = methods;
+        break;
+    case TriggerType::Cron:
+        j["type"] = "cron";
+        j["schedule"] = schedule;
+        break;
+    case TriggerType::Db:
+        j["type"] = "db";
+        j["table"] = table;
+        j["event"] = event == DbEvent::Insert ? "INSERT"
+                     : event == DbEvent::Update ? "UPDATE"
+                                                : "DELETE";
+        break;
+    }
+    if (timeoutMs > 0) j["timeoutMs"] = timeoutMs;
+    // Written out explicitly: the default depends on the trigger type, so an
+    // omitted key would not survive a type change on reload.
+    j["singleFlight"] = singleFlight;
+    return j;
+}
+
+ParseResult parseDescriptor(const nlohmann::json& on) {
+    if (!on.is_object()) return fail("the exported 'on' must be an object");
+
+    FunctionDescriptor d;
+
+    // Identity first, so the error a script author sees names the thing that
+    // matters most. An id is never inferred from the file path.
+    if (!on.contains("id")) return fail("'id' is required: the function's identity, not its path");
+    if (!on.at("id").is_string()) return fail("'id' must be a string");
+    d.id = trim(on.at("id").get<std::string>());
+    if (d.id.empty()) return fail("'id' must not be empty");
+
+    if (on.contains("type")) {
+        if (!on.at("type").is_string()) return fail("'type' must be a string");
+        const std::string t = on.at("type").get<std::string>();
+        if (t == "http") {
+            d.type = TriggerType::Http;
+        } else if (t == "cron") {
+            d.type = TriggerType::Cron;
+        } else if (t == "db") {
+            d.type = TriggerType::Db;
+        } else {
+            return fail("'type' must be one of http, cron, db: '" + t + "'");
+        }
+    }
+
+    switch (d.type) {
+    case TriggerType::Http: {
+        if (!on.contains("route")) return fail("http 'route' is required");
+        if (!on.at("route").is_string()) return fail("http 'route' must be a string");
+        d.route = on.at("route").get<std::string>();
+        if (const std::string e = routeError(d.route); !e.empty()) return fail(e);
+        if (const std::string e = parseMethods(on, d.methods); !e.empty()) return fail(e);
+        break;
+    }
+    case TriggerType::Cron: {
+        if (!on.contains("schedule")) return fail("cron 'schedule' is required");
+        if (!on.at("schedule").is_string()) return fail("cron 'schedule' must be a string");
+        d.schedule = on.at("schedule").get<std::string>();
+        if (const std::string e = cronError(d.schedule); !e.empty()) return fail(e);
+        break;
+    }
+    case TriggerType::Db: {
+        if (!on.contains("table")) return fail("db 'table' is required");
+        if (!on.at("table").is_string()) return fail("db 'table' must be a string");
+        d.table = trim(on.at("table").get<std::string>());
+        if (d.table.empty()) return fail("db 'table' must not be empty");
+        if (!on.contains("event")) return fail("db 'event' is required");
+        if (!on.at("event").is_string()) return fail("db 'event' must be a string");
+        const std::string raw = on.at("event").get<std::string>();
+        const std::string ev = upper(trim(raw));
+        if (ev == "INSERT") {
+            d.event = DbEvent::Insert;
+        } else if (ev == "UPDATE") {
+            d.event = DbEvent::Update;
+        } else if (ev == "DELETE") {
+            d.event = DbEvent::Delete;
+        } else {
+            return fail("db 'event' must be one of INSERT, UPDATE, DELETE: '" + raw + "'");
+        }
+        break;
+    }
+    }
+
+    if (on.contains("timeoutMs")) {
+        const nlohmann::json& t = on.at("timeoutMs");
+        if (!t.is_number_integer()) return fail("'timeoutMs' must be an integer number of ms");
+        d.timeoutMs = t.get<long long>();
+        if (d.timeoutMs <= 0) return fail("'timeoutMs' must be greater than 0");
+    }
+
+    // Cron defaults to single flight: a schedule firing again while the last
+    // run is still going is almost never what the author meant. HTTP requests
+    // are concurrent by nature, so they default to off.
+    d.singleFlight = d.type == TriggerType::Cron;
+    if (on.contains("singleFlight")) {
+        if (!on.at("singleFlight").is_boolean()) return fail("'singleFlight' must be a boolean");
+        d.singleFlight = on.at("singleFlight").get<bool>();
+    }
+
+    // Any other key is ignored on purpose: a script written for a newer server
+    // must still load here.
+    ParseResult r;
+    r.ok = true;
+    r.descriptor = std::move(d);
+    return r;
+}
+
+bool matchRoute(const std::string& pattern, const std::string& path, RouteParams& params) {
+    params.clear();
+    const std::vector<std::string> pseg = segments(pattern);
+    const std::vector<std::string> xseg = segments(path);
+    if (pseg.size() != xseg.size()) return false;
+
+    RouteParams captured;
+    for (std::size_t i = 0; i < pseg.size(); ++i) {
+        if (isParamSegment(pseg[i])) {
+            // An empty segment would bind a parameter to nothing, which no
+            // handler expects; "/u/" must not satisfy "/u/:handle".
+            if (xseg[i].empty()) return false;
+            captured[pseg[i].substr(1)] = xseg[i];
+        } else if (pseg[i] != xseg[i]) {
+            return false;
+        }
+    }
+    params = std::move(captured);
+    return true;
+}
+
+RouteMatch matchHttpRoute(const std::vector<FunctionDescriptor>& descriptors,
+                          const std::string& method, const std::string& path) {
+    RouteMatch out;
+    std::set<std::string> allowed;
+    bool routeExists = false;
+
+    for (const FunctionDescriptor& d : descriptors) {
+        if (d.type != TriggerType::Http) continue; // a stale route field opens nothing
+        RouteParams params;
+        if (!matchRoute(d.route, path, params)) continue;
+        routeExists = true;
+        if (d.acceptsMethod(method)) {
+            out.status = RouteMatchStatus::Matched;
+            out.descriptor = &d; // first declaration wins: dispatch stays deterministic
+            out.params = std::move(params);
+            return out;
+        }
+        // Only reachable for a descriptor that declared methods, since an empty
+        // list accepts everything and would have matched above.
+        allowed.insert(d.methods.begin(), d.methods.end());
+    }
+
+    if (!routeExists) return out; // NotFound, no Allow header to offer
+    out.status = RouteMatchStatus::MethodNotAllowed;
+    out.allowedMethods.assign(allowed.begin(), allowed.end());
+    return out;
+}
+
+std::string allowHeaderValue(const std::vector<std::string>& methods) {
+    std::string out;
+    for (const std::string& m : methods) {
+        if (!out.empty()) out += ", ";
+        out += m;
+    }
+    return out;
+}
+
+} // namespace svapi::functions

+ 103 - 0
src/functions/descriptor.hpp

@@ -0,0 +1,103 @@
+#pragma once
+#include <map>
+#include <nlohmann/json.hpp>
+#include <string>
+#include <vector>
+
+namespace svapi::functions {
+
+/// What makes a function run. Slice 1 dispatches only Http, but the whole
+/// vocabulary is parsed now so a script written against a later server is
+/// rejected with a clear message rather than silently treated as an HTTP route.
+enum class TriggerType { Http, Cron, Db };
+
+enum class DbEvent { Insert, Update, Delete };
+
+/// Captured path parameters, keyed by the `:name` in the pattern. Ordered so
+/// two matches of the same route compare equal regardless of segment order.
+using RouteParams = std::map<std::string, std::string>;
+
+/// The validated `on` object a script exports:
+///   export const on = { id: 'kb-search', type: 'http', route: '/kb/:topic', method: 'GET' };
+///
+/// `id` is the function's identity and lives in the source, never derived from
+/// the file path - a rename must carry the policy with it (design doc,
+/// "Identity and policy"). Everything else is trigger configuration.
+struct FunctionDescriptor {
+    std::string id;
+    TriggerType type = TriggerType::Http;
+
+    // Http
+    std::string route;
+    /// Normalised to upper case, deduplicated, declaration order preserved.
+    /// EMPTY MEANS ANY METHOD - it is not "no method allowed".
+    std::vector<std::string> methods;
+
+    // Cron. Validated for shape only; nothing here schedules anything.
+    std::string schedule;
+
+    // Db
+    std::string table;
+    DbEvent event = DbEvent::Insert;
+
+    // Common
+    /// 0 means "not declared"; the runner then applies its configured default.
+    /// A declared value is still clamped to the configured maximum elsewhere.
+    long long timeoutMs = 0;
+    bool singleFlight = false;
+
+    /// True when this descriptor would serve `method`. Case-insensitive, and
+    /// true for every method when none were declared.
+    bool acceptsMethod(const std::string& method) const;
+
+    /// The form stored on the registry row. Round-trips through parseDescriptor.
+    nlohmann::json toJson() const;
+};
+
+/// Parsing never throws on user input: a script author's typo is data, not an
+/// exception. `error` names the first problem found, in declaration-check order.
+struct ParseResult {
+    bool ok = false;
+    FunctionDescriptor descriptor;
+    std::string error;
+};
+
+/// Validate the `on` object exported by a script (or read back from the
+/// registry). Unknown keys are ignored so a newer script still loads on an
+/// older server. Pure: no I/O, no global state.
+ParseResult parseDescriptor(const nlohmann::json& on);
+
+/// Match one route pattern against one request path. Both are split on '/' with
+/// leading and trailing slashes ignored; segment counts must then be equal. A
+/// `:name` segment captures into `params`, any other segment compares
+/// byte-exactly (case-sensitively). `params` is cleared first, so it is empty
+/// whenever the function returns false.
+bool matchRoute(const std::string& pattern, const std::string& path, RouteParams& params);
+
+/// Why route resolution ended the way it did. NotFound and MethodNotAllowed are
+/// kept apart on purpose: collapsing them would let a GET reach a function that
+/// declared `method: 'POST'`, and would lose the `Allow:` header a 405 owes the
+/// client.
+enum class RouteMatchStatus { NotFound, MethodNotAllowed, Matched };
+
+struct RouteMatch {
+    RouteMatchStatus status = RouteMatchStatus::NotFound;
+    /// Only set when status == Matched; the referenced descriptor is borrowed
+    /// from the container passed to matchHttpRoute and must outlive the match.
+    const FunctionDescriptor* descriptor = nullptr;
+    RouteParams params;
+    /// Only set when status == MethodNotAllowed: the sorted, deduplicated union
+    /// of the methods every function on this path declared.
+    std::vector<std::string> allowedMethods;
+};
+
+/// Resolve `method` + `path` against the project's HTTP descriptors. Non-HTTP
+/// descriptors are skipped whatever their other fields say. Among several
+/// candidates the first in `descriptors` wins, so dispatch stays deterministic.
+RouteMatch matchHttpRoute(const std::vector<FunctionDescriptor>& descriptors,
+                          const std::string& method, const std::string& path);
+
+/// Render an `Allow:` header value ("GET, PUT"). Empty for an empty list.
+std::string allowHeaderValue(const std::vector<std::string>& methods);
+
+} // namespace svapi::functions

+ 19 - 0
tests/CMakeLists.txt

@@ -81,3 +81,22 @@ gtest_discover_tests(test_outbound_http)
 add_executable(test_principal test_principal.cpp)
 target_link_libraries(test_principal PRIVATE vectorapi_core GTest::gtest_main)
 gtest_discover_tests(test_principal)
+
+# The two function-runtime units below are pure: no database client, no I/O. They
+# compile their sources directly instead of linking vectorapi_core, so these two
+# targets still build and run on a host where smartbotic-db-client cannot compile
+# (see CLAUDE.md, "The Void dev host can no longer build the C++ natively").
+add_executable(test_functions_descriptor
+    test_functions_descriptor.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/descriptor.cpp)
+target_include_directories(test_functions_descriptor PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_functions_descriptor PRIVATE
+    nlohmann_json::nlohmann_json GTest::gtest_main)
+gtest_discover_tests(test_functions_descriptor)
+
+add_executable(test_functions_net_guard
+    test_functions_net_guard.cpp
+    ${CMAKE_SOURCE_DIR}/src/functions/net_guard.cpp)
+target_include_directories(test_functions_net_guard PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_link_libraries(test_functions_net_guard PRIVATE GTest::gtest_main)
+gtest_discover_tests(test_functions_net_guard)

+ 377 - 0
tests/test_functions_descriptor.cpp

@@ -0,0 +1,377 @@
+// Unit tests for the pure half of the function runtime: descriptor parsing and
+// HTTP route matching. No database, no network - this target deliberately does
+// not link vectorapi_core so it also builds where the DB client cannot.
+#include <gtest/gtest.h>
+
+#include <nlohmann/json.hpp>
+
+#include "functions/descriptor.hpp"
+
+using nlohmann::json;
+using namespace svapi::functions;
+
+namespace {
+
+FunctionDescriptor parseOk(const json& on) {
+    const ParseResult r = parseDescriptor(on);
+    EXPECT_TRUE(r.ok) << r.error;
+    return r.descriptor;
+}
+
+std::string parseErr(const json& on) {
+    const ParseResult r = parseDescriptor(on);
+    EXPECT_FALSE(r.ok) << "expected a rejection";
+    EXPECT_FALSE(r.error.empty());
+    return r.error;
+}
+
+} // namespace
+
+// ---------------------------------------------------------------- identity
+
+TEST(Descriptor, MissingIdIsAnError) {
+    // A path fallback would let a rename silently create a second principal
+    // carrying the project's default policy, so this is never tolerated.
+    const std::string err = parseErr(json{{"type", "http"}, {"route", "/kb"}});
+    EXPECT_NE(err.find("id"), std::string::npos);
+}
+
+TEST(Descriptor, EmptyOrNonStringIdIsAnError) {
+    parseErr(json{{"id", ""}, {"type", "http"}, {"route", "/kb"}});
+    parseErr(json{{"id", 42}, {"type", "http"}, {"route", "/kb"}});
+    parseErr(json{{"id", "  "}, {"type", "http"}, {"route", "/kb"}});
+}
+
+TEST(Descriptor, NonObjectOnIsAnError) {
+    parseErr(json("http"));
+    parseErr(json::array({1, 2}));
+    parseErr(json(nullptr));
+}
+
+TEST(Descriptor, ParsingIsPureAndRepeatable) {
+    // The registry re-parses every row on each reload; two parses of one body
+    // must agree exactly, and parsing one body must not perturb the next.
+    const json a = json{{"id", "a"}, {"type", "http"}, {"route", "/a"}, {"method", "post"}};
+    const json b = json{{"id", "b"}, {"type", "cron"}, {"schedule", "*/5 * * * *"}};
+    const FunctionDescriptor a1 = parseOk(a);
+    const FunctionDescriptor b1 = parseOk(b);
+    const FunctionDescriptor a2 = parseOk(a);
+    EXPECT_EQ(a1.toJson(), a2.toJson());
+    EXPECT_EQ(b1.id, "b");
+    EXPECT_EQ(a2.methods, (std::vector<std::string>{"POST"}));
+}
+
+// -------------------------------------------------------------------- type
+
+TEST(Descriptor, TypeDefaultsToHttp) {
+    const FunctionDescriptor d = parseOk(json{{"id", "x"}, {"route", "/x"}});
+    EXPECT_EQ(d.type, TriggerType::Http);
+}
+
+TEST(Descriptor, UnknownTypeIsAnError) {
+    const std::string err = parseErr(json{{"id", "x"}, {"type", "queue"}});
+    EXPECT_NE(err.find("queue"), std::string::npos);
+}
+
+// -------------------------------------------------------------------- http
+
+TEST(Descriptor, HttpNeedsARoute) {
+    parseErr(json{{"id", "x"}, {"type", "http"}});
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", ""}});
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", 7}});
+}
+
+TEST(Descriptor, RouteMustStartWithASlash) {
+    const std::string err = parseErr(json{{"id", "x"}, {"type", "http"}, {"route", "kb/:topic"}});
+    EXPECT_NE(err.find("'/'"), std::string::npos);
+}
+
+TEST(Descriptor, RouteParamsMustBeNamedAndUnique) {
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", "/kb/:"}});
+    parseErr(json{{"id", "x"}, {"type", "http"}, {"route", "/kb/:a/:a"}});
+    const FunctionDescriptor d =
+        parseOk(json{{"id", "x"}, {"type", "http"}, {"route", "/kb/:a/:b"}});
+    EXPECT_EQ(d.route, "/kb/:a/:b");
+}
+
+TEST(Descriptor, AbsentMethodMeansAnyMethod) {
+    const FunctionDescriptor d = parseOk(json{{"id", "x"}, {"route", "/x"}});
+    EXPECT_TRUE(d.methods.empty());
+    EXPECT_TRUE(d.acceptsMethod("GET"));
+    EXPECT_TRUE(d.acceptsMethod("DELETE"));
+}
+
+TEST(Descriptor, MethodNormalisesFromAString) {
+    const FunctionDescriptor d = parseOk(json{{"id", "x"}, {"route", "/x"}, {"method", "post"}});
+    EXPECT_EQ(d.methods, (std::vector<std::string>{"POST"}));
+    EXPECT_TRUE(d.acceptsMethod("post"));
+    EXPECT_FALSE(d.acceptsMethod("GET"));
+}
+
+TEST(Descriptor, MethodNormalisesFromAnArrayAndDeduplicates) {
+    const FunctionDescriptor d = parseOk(
+        json{{"id", "x"}, {"route", "/x"}, {"method", json::array({"get", "POST", "Get"})}});
+    EXPECT_EQ(d.methods, (std::vector<std::string>{"GET", "POST"}));
+}
+
+TEST(Descriptor, BadMethodShapesAreRejected) {
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", json::array()}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", json::array({"GET", 7})}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", ""}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", 7}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"method", "GET POST"}});
+}
+
+TEST(Descriptor, HttpIgnoresCronAndDbFields) {
+    const FunctionDescriptor d =
+        parseOk(json{{"id", "x"}, {"type", "http"}, {"route", "/x"}, {"schedule", "nonsense"}});
+    EXPECT_TRUE(d.schedule.empty());
+    EXPECT_TRUE(d.table.empty());
+}
+
+// -------------------------------------------------------------------- cron
+
+TEST(Descriptor, CronNeedsAFiveFieldSchedule) {
+    parseErr(json{{"id", "x"}, {"type", "cron"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * * * *"}});
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "*/5 * * * *"}}).schedule,
+              "*/5 * * * *");
+}
+
+TEST(Descriptor, CronFieldRangesAreChecked) {
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "60 * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* 24 * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * 0 * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * 13 *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * * 8"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "*/0 * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "5-1 * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "a * * * *"}});
+    parseErr(json{{"id", "x"}, {"type", "cron"}, {"schedule", "0, * * * *"}});
+    parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "0,30 1-5/2 */2 JAN-DEC mon"}});
+    parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "  0 3 * * 0  "}});
+    parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "0 3 * * 7"}});
+}
+
+TEST(Descriptor, CronDefaultsToSingleFlight) {
+    // Overlapping runs of one schedule are almost never what the author meant,
+    // so cron opts in by default while HTTP (concurrent by nature) does not.
+    EXPECT_TRUE(
+        parseOk(json{{"id", "x"}, {"type", "cron"}, {"schedule", "* * * * *"}}).singleFlight);
+    EXPECT_FALSE(parseOk(json{{"id", "x"}, {"route", "/x"}}).singleFlight);
+    EXPECT_FALSE(parseOk(json{{"id", "x"},
+                              {"type", "cron"},
+                              {"schedule", "* * * * *"},
+                              {"singleFlight", false}})
+                     .singleFlight);
+    EXPECT_TRUE(parseOk(json{{"id", "x"}, {"route", "/x"}, {"singleFlight", true}}).singleFlight);
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"singleFlight", "yes"}});
+}
+
+// ---------------------------------------------------------------------- db
+
+TEST(Descriptor, DbNeedsATableAndAnEvent) {
+    parseErr(json{{"id", "x"}, {"type", "db"}, {"event", "INSERT"}});
+    parseErr(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}});
+    parseErr(json{{"id", "x"}, {"type", "db"}, {"table", ""}, {"event", "INSERT"}});
+    const FunctionDescriptor d =
+        parseOk(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}, {"event", "update"}});
+    EXPECT_EQ(d.table, "kb");
+    EXPECT_EQ(d.event, DbEvent::Update);
+}
+
+TEST(Descriptor, DbEventMustBeOneOfTheThree) {
+    const std::string err =
+        parseErr(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}, {"event", "UPSERT"}});
+    EXPECT_NE(err.find("UPSERT"), std::string::npos);
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"type", "db"}, {"table", "kb"}, {"event", "DELETE"}}).event,
+              DbEvent::Delete);
+}
+
+// ------------------------------------------------------------------ common
+
+TEST(Descriptor, TimeoutMsMustBeAPositiveInteger) {
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", 1500}}).timeoutMs, 1500);
+    EXPECT_EQ(parseOk(json{{"id", "x"}, {"route", "/x"}}).timeoutMs, 0); // 0 = unset
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", 0}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", -1}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", "1500"}});
+    parseErr(json{{"id", "x"}, {"route", "/x"}, {"timeoutMs", 1.5}});
+}
+
+TEST(Descriptor, UnknownKeysAreIgnored) {
+    // Forward compatibility: a newer script must still load on an older server.
+    const FunctionDescriptor d = parseOk(json{{"id", "x"},
+                                              {"route", "/x"},
+                                              {"method", "GET"},
+                                              {"retries", 3},
+                                              {"labels", json::array({"a"})},
+                                              {"futureThing", json::object()}});
+    EXPECT_EQ(d.id, "x");
+    EXPECT_EQ(d.route, "/x");
+}
+
+TEST(Descriptor, TheFirstProblemIsNamed) {
+    const ParseResult r = parseDescriptor(json{{"type", "http"}, {"route", "bad"}});
+    ASSERT_FALSE(r.ok);
+    EXPECT_NE(r.error.find("id"), std::string::npos);
+    EXPECT_EQ(r.error.find("route"), std::string::npos);
+}
+
+TEST(Descriptor, RoundTripsThroughJson) {
+    // The descriptor is stored on the registry row, so what we write back must
+    // parse to the same thing on reload.
+    const FunctionDescriptor d = parseOk(json{{"id", "kb-search"},
+                                              {"route", "/kb/:topic"},
+                                              {"method", json::array({"GET", "HEAD"})},
+                                              {"timeoutMs", 2000}});
+    const ParseResult again = parseDescriptor(d.toJson());
+    ASSERT_TRUE(again.ok) << again.error;
+    EXPECT_EQ(again.descriptor.toJson(), d.toJson());
+}
+
+// ------------------------------------------------------------- matchRoute
+
+TEST(MatchRoute, CapturesAParam) {
+    RouteParams p;
+    ASSERT_TRUE(matchRoute("/u/:handle", "/u/alice", p));
+    EXPECT_EQ(p, (RouteParams{{"handle", "alice"}}));
+}
+
+TEST(MatchRoute, SegmentCountsMustMatch) {
+    RouteParams p{{"stale", "value"}};
+    EXPECT_FALSE(matchRoute("/u/:handle", "/u/alice/x", p));
+    EXPECT_TRUE(p.empty()) << "params must be cleared on no match";
+    EXPECT_FALSE(matchRoute("/u/:handle", "/u", p));
+    EXPECT_FALSE(matchRoute("/u/:handle/x", "/u/alice", p));
+}
+
+TEST(MatchRoute, LiteralsCompareCaseSensitively) {
+    RouteParams p;
+    ASSERT_TRUE(matchRoute("/about", "/about", p));
+    EXPECT_TRUE(p.empty());
+    EXPECT_FALSE(matchRoute("/about", "/About", p));
+}
+
+TEST(MatchRoute, LeadingAndTrailingSlashesAreIgnored) {
+    RouteParams p;
+    EXPECT_TRUE(matchRoute("/about", "about", p));
+    EXPECT_TRUE(matchRoute("about/", "/about", p));
+    ASSERT_TRUE(matchRoute("/u/:handle/", "/u/alice", p));
+    EXPECT_EQ(p, (RouteParams{{"handle", "alice"}}));
+}
+
+TEST(MatchRoute, RootMatchesRoot) {
+    RouteParams p;
+    EXPECT_TRUE(matchRoute("/", "/", p));
+    EXPECT_TRUE(matchRoute("/", "", p));
+    EXPECT_FALSE(matchRoute("/", "/a", p));
+    EXPECT_FALSE(matchRoute("/a", "/", p));
+}
+
+TEST(MatchRoute, MultipleParamsAndMixedSegments) {
+    RouteParams p;
+    ASSERT_TRUE(matchRoute("/kb/:topic/doc/:id", "/kb/hu/doc/42", p));
+    EXPECT_EQ(p, (RouteParams{{"id", "42"}, {"topic", "hu"}}));
+    EXPECT_FALSE(matchRoute("/kb/:topic/doc/:id", "/kb/hu/docs/42", p));
+}
+
+TEST(MatchRoute, AParamDoesNotMatchAnEmptySegment) {
+    RouteParams p;
+    EXPECT_FALSE(matchRoute("/u/:handle", "/u/", p));
+}
+
+// --------------------------------------------- 404 vs 405 (method-aware)
+
+namespace {
+
+std::vector<FunctionDescriptor> table() {
+    std::vector<FunctionDescriptor> v;
+    v.push_back(parseOk(json{{"id", "get-user"}, {"route", "/u/:handle"}, {"method", "GET"}}));
+    v.push_back(parseOk(json{{"id", "put-user"}, {"route", "/u/:handle"}, {"method", "put"}}));
+    v.push_back(parseOk(json{{"id", "any-about"}, {"route", "/about"}}));
+    v.push_back(parseOk(
+        json{{"id", "post-kb"}, {"route", "/kb"}, {"method", json::array({"POST", "PATCH"})}}));
+    v.push_back(parseOk(json{{"id", "cron-job"}, {"type", "cron"}, {"schedule", "* * * * *"}}));
+    return v;
+}
+
+} // namespace
+
+TEST(MatchHttp, UnknownRouteIsNotFound) {
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "GET", "/nope");
+    EXPECT_EQ(m.status, RouteMatchStatus::NotFound);
+    EXPECT_EQ(m.descriptor, nullptr);
+    EXPECT_TRUE(m.allowedMethods.empty());
+}
+
+TEST(MatchHttp, MatchedRouteCarriesTheParams) {
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "GET", "/u/alice");
+    ASSERT_EQ(m.status, RouteMatchStatus::Matched);
+    ASSERT_NE(m.descriptor, nullptr);
+    EXPECT_EQ(m.descriptor->id, "get-user");
+    EXPECT_EQ(m.params, (RouteParams{{"handle", "alice"}}));
+}
+
+TEST(MatchHttp, WrongMethodOnAKnownRouteIs405WithTheUnionOfMethods) {
+    // The bug class this guards: a GET reaching a function that declared POST.
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "DELETE", "/u/alice");
+    ASSERT_EQ(m.status, RouteMatchStatus::MethodNotAllowed);
+    EXPECT_EQ(m.descriptor, nullptr);
+    EXPECT_TRUE(m.params.empty());
+    EXPECT_EQ(m.allowedMethods, (std::vector<std::string>{"GET", "PUT"}));
+    EXPECT_EQ(allowHeaderValue(m.allowedMethods), "GET, PUT");
+}
+
+TEST(MatchHttp, MultiMethodDescriptorContributesEveryMethodToAllow) {
+    const auto t = table();
+    const RouteMatch m = matchHttpRoute(t, "GET", "/kb");
+    ASSERT_EQ(m.status, RouteMatchStatus::MethodNotAllowed);
+    EXPECT_EQ(m.allowedMethods, (std::vector<std::string>{"PATCH", "POST"}));
+}
+
+TEST(MatchHttp, AMethodlessDescriptorTakesEveryMethod) {
+    const auto t = table();
+    for (const char* verb : {"GET", "POST", "DELETE", "OPTIONS"}) {
+        const RouteMatch m = matchHttpRoute(t, verb, "/about");
+        ASSERT_EQ(m.status, RouteMatchStatus::Matched) << verb;
+        EXPECT_EQ(m.descriptor->id, "any-about");
+    }
+}
+
+TEST(MatchHttp, NonHttpDescriptorsNeverMatch) {
+    const auto t = table();
+    EXPECT_EQ(matchHttpRoute(t, "GET", "/cron-job").status, RouteMatchStatus::NotFound);
+    FunctionDescriptor cron =
+        parseOk(json{{"id", "c"}, {"type", "cron"}, {"schedule", "* * * * *"}});
+    cron.route = "/about"; // a stale field must not open a route
+    const std::vector<FunctionDescriptor> only{cron};
+    EXPECT_EQ(matchHttpRoute(only, "GET", "/about").status, RouteMatchStatus::NotFound);
+}
+
+TEST(MatchHttp, TheCallerGivenMethodIsCaseInsensitive) {
+    const auto t = table();
+    EXPECT_EQ(matchHttpRoute(t, "get", "/u/alice").status, RouteMatchStatus::Matched);
+}
+
+TEST(MatchHttp, FirstDeclarationWinsAmongstEqualCandidates) {
+    // Deterministic dispatch matters more than being clever about it; the
+    // registry rejects duplicate ids, but two ids may still claim one route.
+    std::vector<FunctionDescriptor> v;
+    v.push_back(parseOk(json{{"id", "first"}, {"route", "/dup"}, {"method", "GET"}}));
+    v.push_back(parseOk(json{{"id", "second"}, {"route", "/dup"}, {"method", "GET"}}));
+    const RouteMatch m = matchHttpRoute(v, "GET", "/dup");
+    ASSERT_EQ(m.status, RouteMatchStatus::Matched);
+    EXPECT_EQ(m.descriptor->id, "first");
+}
+
+TEST(MatchHttp, EmptyTableIsNotFound) {
+    const std::vector<FunctionDescriptor> none;
+    EXPECT_EQ(matchHttpRoute(none, "GET", "/x").status, RouteMatchStatus::NotFound);
+}
+
+TEST(MatchHttp, AllowHeaderOfNothingIsEmpty) { EXPECT_EQ(allowHeaderValue({}), ""); }