|
|
@@ -0,0 +1,883 @@
|
|
|
+#include "runner/host_context.hpp"
|
|
|
+
|
|
|
+#include "collection_registry.hpp"
|
|
|
+#include "db_errors.hpp"
|
|
|
+#include "embedding_cache.hpp"
|
|
|
+#include "embeddings.hpp"
|
|
|
+#include "errors.hpp"
|
|
|
+#include "filters.hpp"
|
|
|
+#include "outbound_http.hpp"
|
|
|
+#include "principal.hpp"
|
|
|
+#include "project_settings.hpp"
|
|
|
+#include "server.hpp"
|
|
|
+#include "settings.hpp"
|
|
|
+#include "settings_store.hpp"
|
|
|
+#include "vector_search.hpp"
|
|
|
+
|
|
|
+// Generated from runner/src/host_prelude.js at configure time. The .js file is
|
|
|
+// the editable copy; nothing reads it at runtime, so the binary has no file
|
|
|
+// dependency and a deployed runner cannot be made to execute a different
|
|
|
+// prelude by swapping a file next to it.
|
|
|
+#include "host_prelude_js.hpp"
|
|
|
+
|
|
|
+#include <httplib.h>
|
|
|
+#include <quickjs.h>
|
|
|
+
|
|
|
+#include <arpa/inet.h>
|
|
|
+#include <netdb.h>
|
|
|
+#include <sys/socket.h>
|
|
|
+
|
|
|
+#include <algorithm>
|
|
|
+#include <cctype>
|
|
|
+#include <chrono>
|
|
|
+#include <cstdint>
|
|
|
+#include <functional>
|
|
|
+#include <limits>
|
|
|
+#include <map>
|
|
|
+#include <optional>
|
|
|
+#include <unordered_map>
|
|
|
+#include <utility>
|
|
|
+
|
|
|
+namespace svapi::runner {
|
|
|
+namespace {
|
|
|
+
|
|
|
+/// Same bounds the execution core puts on console capture, for the same reason:
|
|
|
+/// ctx.log is otherwise an unmetered allocation channel, and the lines travel
|
|
|
+/// back over HTTP to whoever invoked the function.
|
|
|
+constexpr size_t kMaxLogLines = 1000;
|
|
|
+constexpr size_t kMaxLogBytes = 64u * 1024;
|
|
|
+
|
|
|
+/// What one outbound call gets when the run carries no explicit budget. Never
|
|
|
+/// unbounded: a provider that never answers would pin a pooled runtime for as
|
|
|
+/// long as the socket stays open.
|
|
|
+constexpr int64_t kDefaultOutboundTimeoutMs = 10000;
|
|
|
+
|
|
|
+int64_t nowMs() {
|
|
|
+ using namespace std::chrono;
|
|
|
+ return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
|
|
|
+}
|
|
|
+
|
|
|
+bool isAddressLiteral(const std::string& host) {
|
|
|
+ unsigned char buf[16];
|
|
|
+ return inet_pton(AF_INET, host.c_str(), buf) == 1 ||
|
|
|
+ inet_pton(AF_INET6, host.c_str(), buf) == 1;
|
|
|
+}
|
|
|
+
|
|
|
+// --- the C++/JS value boundary ---------------------------------------------
|
|
|
+
|
|
|
+JSValue toJs(JSContext* ctx, const nlohmann::json& j) {
|
|
|
+ const std::string text = j.dump();
|
|
|
+ return JS_ParseJSON(ctx, text.c_str(), text.size(), "<host>");
|
|
|
+}
|
|
|
+
|
|
|
+std::string toText(JSContext* ctx, JSValueConst v) {
|
|
|
+ const char* s = JS_ToCString(ctx, v);
|
|
|
+ if (!s) {
|
|
|
+ JS_FreeValue(ctx, JS_GetException(ctx));
|
|
|
+ return std::string();
|
|
|
+ }
|
|
|
+ std::string out(s);
|
|
|
+ JS_FreeCString(ctx, s);
|
|
|
+ return out;
|
|
|
+}
|
|
|
+
|
|
|
+/// A JS argument as JSON. `undefined` becomes null rather than failing, because
|
|
|
+/// the prelude passes every optional field through and most are absent.
|
|
|
+nlohmann::json fromJs(JSContext* ctx, JSValueConst v) {
|
|
|
+ JSValue json = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
|
|
|
+ if (JS_IsException(json)) {
|
|
|
+ JS_FreeValue(ctx, JS_GetException(ctx));
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ return nullptr;
|
|
|
+ }
|
|
|
+ if (JS_IsUndefined(json)) {
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ return nullptr;
|
|
|
+ }
|
|
|
+ const std::string text = toText(ctx, json);
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ nlohmann::json out = nlohmann::json::parse(text, nullptr, false);
|
|
|
+ return out.is_discarded() ? nlohmann::json(nullptr) : out;
|
|
|
+}
|
|
|
+
|
|
|
+/// An ApiError as a catchable JS Error carrying the slug and status, so a
|
|
|
+/// function can branch on `e.code` instead of matching message text. `details`
|
|
|
+/// is forwarded too: it is how relation impacts on a blocked delete reach the
|
|
|
+/// script rather than being flattened into a sentence.
|
|
|
+JSValue throwApiError(JSContext* ctx, const ApiError& e) {
|
|
|
+ JSValue err = JS_NewError(ctx);
|
|
|
+ JS_SetPropertyStr(ctx, err, "message", JS_NewString(ctx, e.what()));
|
|
|
+ JS_SetPropertyStr(ctx, err, "code", JS_NewString(ctx, e.slug.c_str()));
|
|
|
+ JS_SetPropertyStr(ctx, err, "status", JS_NewInt32(ctx, httpStatus(e.code)));
|
|
|
+ if (!e.details.empty()) JS_SetPropertyStr(ctx, err, "details", toJs(ctx, e.details));
|
|
|
+ return JS_Throw(ctx, err);
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace
|
|
|
+
|
|
|
+/// The pure seams, in a named namespace so the test can reach them: the policy
|
|
|
+/// decision and the request/response shaping, split out of the native bindings
|
|
|
+/// so each is testable without an engine, a resolver or a database. Not in the
|
|
|
+/// public header - they are an implementation detail of the bindings, not part
|
|
|
+/// of the `ctx` contract.
|
|
|
+namespace hostdetail {
|
|
|
+
|
|
|
+/// Where ctx.fetch may connect, and to which address.
|
|
|
+struct EgressDecision {
|
|
|
+ bool allowed = false;
|
|
|
+ std::string pinnedAddress; ///< the address the guard approved, to connect to
|
|
|
+ std::string reason; ///< why not, when !allowed
|
|
|
+};
|
|
|
+
|
|
|
+/// Injected so the classification rules are testable without a resolver.
|
|
|
+using Resolver = std::function<std::vector<std::string>(const std::string&)>;
|
|
|
+
|
|
|
+/// The op a builder call needs granted.
|
|
|
+///
|
|
|
+/// Deliberately op-for-op what the HTTP handlers ask for: documents.cpp takes
|
|
|
+/// List for a listing and Read for a point get, vectors.cpp takes Search for
|
|
|
+/// /search and Insert for a vector write. If this table drifted, a function
|
|
|
+/// would reach data through a weaker grant than the equivalent HTTP call needs,
|
|
|
+/// which is exactly the divergence Principal exists to prevent.
|
|
|
+std::optional<KeyOp> keyOpForDbOp(const std::string& op) {
|
|
|
+ if (op == "find") return KeyOp::List;
|
|
|
+ if (op == "get") return KeyOp::Read;
|
|
|
+ if (op == "insert") return KeyOp::Insert;
|
|
|
+ if (op == "update") return KeyOp::Update;
|
|
|
+ if (op == "patch") return KeyOp::Update;
|
|
|
+ if (op == "delete") return KeyOp::Delete;
|
|
|
+ if (op == "search") return KeyOp::Search;
|
|
|
+ if (op == "store") return KeyOp::Insert;
|
|
|
+ return std::nullopt;
|
|
|
+}
|
|
|
+
|
|
|
+/// Names the collection and the op, because the author of a refused function
|
|
|
+/// has to know WHICH grant to ask an admin for. "forbidden" on its own sends
|
|
|
+/// them guessing through a policy they cannot see.
|
|
|
+std::string deniedMessage(const std::string& collection, const std::string& op,
|
|
|
+ const std::string& why) {
|
|
|
+ return "collection '" + collection + "', operation '" + op + "': " + why;
|
|
|
+}
|
|
|
+
|
|
|
+/// The builder's accumulated state as database query options. Shaped here, in a
|
|
|
+/// pure function, rather than inside the native binding: the filter grammar and
|
|
|
+/// the paging arguments are where a mistake is silent, and this is testable
|
|
|
+/// without an engine or a database.
|
|
|
+smartbotic::database::Client::QueryOptions queryOptionsFrom(const nlohmann::json& payload) {
|
|
|
+ smartbotic::database::Client::QueryOptions opts;
|
|
|
+ if (!payload.is_object())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "the query must be an object");
|
|
|
+
|
|
|
+ nlohmann::json filters = payload.value("filters", nlohmann::json::array());
|
|
|
+ if (!filters.is_array())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ "filters must be an array of \"field:op:value\" strings");
|
|
|
+ for (const auto& f : filters) {
|
|
|
+ if (!f.is_string())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ "each filter must be a \"field:op:value\" string");
|
|
|
+ // THE shared parser. Same grammar, same operator set, same errors as
|
|
|
+ // ?filter= on /documents, and the database evaluates the result - so a
|
|
|
+ // function and an HTTP call can never disagree about what a filter means.
|
|
|
+ opts.filters.push_back(parseFilter(f.get<std::string>()));
|
|
|
+ }
|
|
|
+
|
|
|
+ // is_number_integer() rather than is_number_unsigned(): a value that
|
|
|
+ // travelled through JSON arrives unsigned, but one built in C++ (a test,
|
|
|
+ // or a future caller) does not, and the two must agree. A float or a
|
|
|
+ // negative value is still refused, as ?limit= refuses them over HTTP.
|
|
|
+ auto unsignedField = [&payload](const char* name) -> uint32_t {
|
|
|
+ if (!payload.contains(name) || payload.at(name).is_null()) return 0;
|
|
|
+ const nlohmann::json& v = payload.at(name);
|
|
|
+ if (!v.is_number_integer())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ std::string(name) + " must be a non-negative integer");
|
|
|
+ const int64_t wide = v.get<int64_t>();
|
|
|
+ if (wide < 0 || wide > std::numeric_limits<uint32_t>::max())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ std::string(name) + " must be a non-negative integer");
|
|
|
+ return static_cast<uint32_t>(wide);
|
|
|
+ };
|
|
|
+ opts.limit = unsignedField("limit");
|
|
|
+ opts.offset = unsignedField("offset");
|
|
|
+
|
|
|
+ if (payload.contains("sort") && !payload.at("sort").is_null()) {
|
|
|
+ const nlohmann::json& sort = payload.at("sort");
|
|
|
+ if (!sort.is_string())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "sort must be a field name");
|
|
|
+ opts.sortField = sort.get<std::string>();
|
|
|
+ }
|
|
|
+ if (payload.contains("desc") && !payload.at("desc").is_null()) {
|
|
|
+ const nlohmann::json& desc = payload.at("desc");
|
|
|
+ if (!desc.is_boolean())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "desc must be a boolean");
|
|
|
+ opts.sortDescending = desc.get<bool>();
|
|
|
+ }
|
|
|
+ return opts;
|
|
|
+}
|
|
|
+
|
|
|
+/// How long one outbound call may take: what is left of the run's budget,
|
|
|
+/// narrowed by whatever the caller asked for. A caller can ask for less and
|
|
|
+/// never for more, so one slow provider cannot outlive the run waiting on it.
|
|
|
+/// A non-positive result means the budget is gone and nothing should connect.
|
|
|
+int64_t outboundTimeoutMs(int64_t deadline_ms, int64_t elapsed_ms, int64_t requested_ms) {
|
|
|
+ int64_t budget = deadline_ms > 0 ? deadline_ms - elapsed_ms : kDefaultOutboundTimeoutMs;
|
|
|
+ if (requested_ms > 0 && requested_ms < budget) budget = requested_ms;
|
|
|
+ return budget;
|
|
|
+}
|
|
|
+
|
|
|
+/// Where ctx.fetch is allowed to connect, and to which address.
|
|
|
+///
|
|
|
+/// `resolve` is injected so the two rules that matter - classify EVERY address,
|
|
|
+/// fail closed - are testable without a resolver.
|
|
|
+///
|
|
|
+/// On the TOCTOU gap the design addendum asks to close: ssrfBlockReason() is the
|
|
|
+/// mandated gate for a literal, where there is no name and therefore no
|
|
|
+/// rebinding window at all. For a NAME it cannot be the gate, because it
|
|
|
+/// discards the addresses it approved and the caller would have to resolve
|
|
|
+/// again - which is the rebinding window. So a name is resolved exactly once
|
|
|
+/// here and classified with blockReasonForAddresses(), which net_guard.hpp
|
|
|
+/// documents as ssrfBlockReason's own classification half. One classifier, one
|
|
|
+/// lookup, and the address the connection pins was the address that was checked.
|
|
|
+EgressDecision decideEgress(const functions::HttpUrlParts& parts,
|
|
|
+ const functions::SsrfPolicy& policy, const Resolver& resolve) {
|
|
|
+ EgressDecision d;
|
|
|
+ if (isAddressLiteral(parts.host)) {
|
|
|
+ if (auto why = functions::ssrfBlockReason(parts.host, policy)) {
|
|
|
+ d.reason = *why;
|
|
|
+ return d;
|
|
|
+ }
|
|
|
+ d.allowed = true;
|
|
|
+ d.pinnedAddress = parts.host;
|
|
|
+ return d;
|
|
|
+ }
|
|
|
+
|
|
|
+ const std::vector<std::string> addresses = resolve(parts.host);
|
|
|
+ if (auto why = functions::blockReasonForAddresses(parts.host, addresses, policy)) {
|
|
|
+ d.reason = *why;
|
|
|
+ return d;
|
|
|
+ }
|
|
|
+ d.allowed = true;
|
|
|
+ // Any approved address would do; the first keeps the resolver's own
|
|
|
+ // ordering, which is what an unpinned client would have used.
|
|
|
+ d.pinnedAddress = addresses.front();
|
|
|
+ return d;
|
|
|
+}
|
|
|
+
|
|
|
+std::vector<std::string> resolveWithGetaddrinfo(const std::string& host) {
|
|
|
+ std::vector<std::string> out;
|
|
|
+ addrinfo hints{};
|
|
|
+ hints.ai_family = AF_UNSPEC;
|
|
|
+ hints.ai_socktype = SOCK_STREAM;
|
|
|
+ addrinfo* res = nullptr;
|
|
|
+ if (getaddrinfo(host.c_str(), nullptr, &hints, &res) != 0) return out;
|
|
|
+ for (addrinfo* p = res; p != nullptr; p = p->ai_next) {
|
|
|
+ char buf[INET6_ADDRSTRLEN] = {0};
|
|
|
+ const void* addr = nullptr;
|
|
|
+ if (p->ai_family == AF_INET)
|
|
|
+ addr = &reinterpret_cast<sockaddr_in*>(p->ai_addr)->sin_addr;
|
|
|
+ else if (p->ai_family == AF_INET6)
|
|
|
+ addr = &reinterpret_cast<sockaddr_in6*>(p->ai_addr)->sin6_addr;
|
|
|
+ if (addr != nullptr && inet_ntop(p->ai_family, addr, buf, sizeof(buf)) != nullptr)
|
|
|
+ out.emplace_back(buf);
|
|
|
+ }
|
|
|
+ freeaddrinfo(res);
|
|
|
+ return out;
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace hostdetail
|
|
|
+
|
|
|
+// ---------------------------------------------------------------------------
|
|
|
+
|
|
|
+struct HostContext::Impl {
|
|
|
+ DbGateway& db;
|
|
|
+ HostContextConfig config;
|
|
|
+ CollectionRegistry registry;
|
|
|
+
|
|
|
+ /// Principal::projects is a non-owning pointer, so the list it points at
|
|
|
+ /// has to outlive every authorize() call: it lives here, not on the stack.
|
|
|
+ std::vector<std::string> projects;
|
|
|
+ std::string principalId;
|
|
|
+
|
|
|
+ int64_t startedMs = nowMs();
|
|
|
+
|
|
|
+ std::vector<std::string> log;
|
|
|
+ size_t logBytes = 0;
|
|
|
+ bool logTruncated = false;
|
|
|
+ std::vector<std::string> blocked;
|
|
|
+
|
|
|
+ /// The registry row per collection, read once per run. A row cannot
|
|
|
+ /// meaningfully change mid-run, and the HTTP path pays this read once per
|
|
|
+ /// request too.
|
|
|
+ std::unordered_map<std::string, std::optional<CollectionMeta>> metaCache;
|
|
|
+
|
|
|
+ /// Pinned for the whole run so a settings hot-reload cannot change the
|
|
|
+ /// egress rules between two fetches of the same function.
|
|
|
+ std::shared_ptr<const functions::SsrfPolicy> ssrf = functions::currentSsrfPolicy();
|
|
|
+
|
|
|
+ bool settingsLoaded = false;
|
|
|
+ Settings global;
|
|
|
+ std::optional<ProjectSettings> projectEmbedding;
|
|
|
+
|
|
|
+ Impl(DbGateway& gateway, HostContextConfig cfg)
|
|
|
+ : db(gateway), config(std::move(cfg)), registry(gateway) {
|
|
|
+ projects.push_back(config.project);
|
|
|
+ // A separate namespace from key ids, so a function cannot spend a key's
|
|
|
+ // rate-limit budget (and the other way round).
|
|
|
+ principalId = "fn:" + config.project + "/" + config.functionId;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// A function is never admin: admin is a key-level flag, and a policy is a
|
|
|
+ /// KeyScope. The scope pointer is ALWAYS set, which is what makes an empty
|
|
|
+ /// policy grant nothing - a null scope would mean unscoped full access.
|
|
|
+ Principal principal() const {
|
|
|
+ return Principal{principalId, &projects, false, &config.policy};
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The one authorization check. requireCapabilityCore() decides; this only
|
|
|
+ /// re-labels the refusal so the message names what was refused.
|
|
|
+ void authorize(const std::string& collection, KeyOp op) {
|
|
|
+ try {
|
|
|
+ requireCapabilityCore(principal(), config.project, collection, op);
|
|
|
+ } catch (const ApiError& e) {
|
|
|
+ throw ApiError(e.code, e.slug,
|
|
|
+ hostdetail::deniedMessage(collection, keyOpToString(op), e.what()),
|
|
|
+ e.details);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ void addLog(std::string line) {
|
|
|
+ if (log.size() >= kMaxLogLines || logBytes >= kMaxLogBytes) {
|
|
|
+ if (!logTruncated) {
|
|
|
+ logTruncated = true;
|
|
|
+ log.emplace_back("[log output truncated]");
|
|
|
+ }
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ logBytes += line.size();
|
|
|
+ log.push_back(std::move(line));
|
|
|
+ }
|
|
|
+
|
|
|
+ int64_t elapsedMs() const { return nowMs() - startedMs; }
|
|
|
+
|
|
|
+ // --- collections --------------------------------------------------------
|
|
|
+
|
|
|
+ const CollectionMeta& meta(const std::string& collection) {
|
|
|
+ auto it = metaCache.find(collection);
|
|
|
+ if (it == metaCache.end())
|
|
|
+ it = metaCache.emplace(collection, registry.get(config.project, collection)).first;
|
|
|
+ if (!it->second)
|
|
|
+ throw ApiError(ErrCode::NotFound, "not_found", "no such collection '" + collection + "'");
|
|
|
+ return *it->second;
|
|
|
+ }
|
|
|
+
|
|
|
+ const CollectionMeta& vectorMeta(const std::string& collection) {
|
|
|
+ const CollectionMeta& m = meta(collection);
|
|
|
+ if (m.kind != "vector")
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "not_vector",
|
|
|
+ "collection '" + collection + "' is not a vector collection");
|
|
|
+ return m;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The global settings document plus this project's overrides, read once.
|
|
|
+ ///
|
|
|
+ /// Read directly rather than through SettingsStore because the seam gives
|
|
|
+ /// the runner a DbGateway and nothing else - and because SettingsStore's
|
|
|
+ /// bootstrap() WRITES (it seeds the document), which a runner must never do
|
|
|
+ /// to the configuration it is merely reading. The precedence itself still
|
|
|
+ /// comes from the one pure resolveEmbedding().
|
|
|
+ void loadSettings() {
|
|
|
+ if (settingsLoaded) return;
|
|
|
+ settingsLoaded = true;
|
|
|
+ const std::string coll = qualify("default", kSettingsCollection);
|
|
|
+ if (auto doc = db.client().get(coll, "current")) global = Settings::fromJson(*doc);
|
|
|
+ if (auto doc = db.client().get(coll, projectSettingsDocId(config.project)))
|
|
|
+ projectEmbedding = ProjectSettings::fromJson(*doc);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Embed `text` for a vector op. Mirrors handlers/vectors.cpp: the same
|
|
|
+ /// cache, keyed the same way, so a function and an HTTP call that embed the
|
|
|
+ /// same string cost one provider call between them.
|
|
|
+ std::vector<float> embed(const CollectionMeta& m, const std::string& text) {
|
|
|
+ loadSettings();
|
|
|
+ ResolvedEmbedding cfg =
|
|
|
+ resolveEmbedding(global, projectEmbedding ? &*projectEmbedding : nullptr, m);
|
|
|
+
|
|
|
+ EmbeddingCache::Key key{cfg.apiBase, cfg.model, text};
|
|
|
+ if (auto hit = embeddingCache().get(key)) return *hit;
|
|
|
+
|
|
|
+ // The provider call is outbound work, so it answers to the run's budget
|
|
|
+ // like ctx.fetch does. Seconds, because that is the client's unit.
|
|
|
+ const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), 0);
|
|
|
+ if (budget <= 0)
|
|
|
+ throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
|
|
|
+ "the run's time budget is exhausted; not calling the embedding provider");
|
|
|
+ const uint32_t readSec = std::min<uint32_t>(
|
|
|
+ global.embeddingReadTimeoutSec, static_cast<uint32_t>((budget + 999) / 1000));
|
|
|
+
|
|
|
+ EmbeddingClient emb(cfg.apiBase, cfg.apiKey, global.embeddingConnectTimeoutSec,
|
|
|
+ std::max<uint32_t>(readSec, 1), global.embeddingClientPoolSize);
|
|
|
+ std::vector<float> v = emb.embed(cfg.model, text);
|
|
|
+ embeddingCache().put(key, v);
|
|
|
+ return v;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The query vector for a search or a store, from `vecField` or `textField`.
|
|
|
+ /// Same shape and same dimension check as handlers/vectors.cpp.
|
|
|
+ std::vector<float> resolveVector(const CollectionMeta& m, const nlohmann::json& payload,
|
|
|
+ const char* vecField, const char* textField) {
|
|
|
+ std::vector<float> v;
|
|
|
+ if (payload.contains(vecField) && payload.at(vecField).is_array()) {
|
|
|
+ v = payload.at(vecField).get<std::vector<float>>();
|
|
|
+ } else if (payload.contains(textField) && payload.at(textField).is_string()) {
|
|
|
+ v = embed(m, payload.at(textField).get<std::string>());
|
|
|
+ } else {
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation",
|
|
|
+ std::string("provide '") + vecField + "' or '" + textField + "'");
|
|
|
+ }
|
|
|
+ if (v.size() != m.vectorDimension)
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "dimension_mismatch",
|
|
|
+ "expected dimension " + std::to_string(m.vectorDimension) + ", got " +
|
|
|
+ std::to_string(v.size()));
|
|
|
+ return v;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// `__hostDb(collection, op, payload)`.
|
|
|
+ ///
|
|
|
+ /// Order is load bearing: authorize, then validate the arguments, then
|
|
|
+ /// touch the database. Authorizing last would let an unauthorized call be
|
|
|
+ /// told whether a collection exists; validating after the registry read
|
|
|
+ /// would spend a round trip on a request that was malformed anyway.
|
|
|
+ nlohmann::json dbCall(const std::string& collection, const std::string& op,
|
|
|
+ const nlohmann::json& payload) {
|
|
|
+ auto keyOp = hostdetail::keyOpForDbOp(op);
|
|
|
+ if (!keyOp)
|
|
|
+ throw ApiError(ErrCode::BadRequest, "validation",
|
|
|
+ "unknown collection operation '" + op + "'");
|
|
|
+ authorize(collection, *keyOp);
|
|
|
+
|
|
|
+ if (op == "find") return find(collection, payload);
|
|
|
+ if (op == "get") return get(collection, payload);
|
|
|
+ if (op == "insert") return insert(collection, payload);
|
|
|
+ if (op == "update") return update(collection, payload);
|
|
|
+ if (op == "patch") return patch(collection, payload);
|
|
|
+ if (op == "delete") return remove(collection, payload);
|
|
|
+ if (op == "search") return search(collection, payload);
|
|
|
+ return store(collection, payload);
|
|
|
+ }
|
|
|
+
|
|
|
+ std::string documentId(const nlohmann::json& payload) {
|
|
|
+ if (!payload.is_object() || !payload.contains("id") || !payload.at("id").is_string())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "a document id is required");
|
|
|
+ std::string id = payload.at("id").get<std::string>();
|
|
|
+ if (id.empty())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "a document id is required");
|
|
|
+ return id;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// The document a write carries. No `{"data":...}` unwrapping here: that
|
|
|
+ /// shape exists because an HTTP body has no other way to say "this is the
|
|
|
+ /// document", while `.insert(doc)` already passes the document itself. `id`
|
|
|
+ /// is stripped because it is the document's identity, not a field - the
|
|
|
+ /// same reason documentBody() strips it on the HTTP side.
|
|
|
+ nlohmann::json documentFrom(const nlohmann::json& payload) {
|
|
|
+ if (!payload.is_object() || !payload.contains("doc") || !payload.at("doc").is_object())
|
|
|
+ throw ApiError(ErrCode::Unprocessable, "validation", "the document must be an object");
|
|
|
+ nlohmann::json out = payload.at("doc");
|
|
|
+ out.erase("id");
|
|
|
+ return out;
|
|
|
+ }
|
|
|
+
|
|
|
+ nlohmann::json find(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ auto opts = hostdetail::queryOptionsFrom(payload);
|
|
|
+ meta(collection);
|
|
|
+ nlohmann::json out = nlohmann::json::array();
|
|
|
+ for (const auto& doc : db.client().find(qualify(config.project, collection), opts))
|
|
|
+ out.push_back(doc);
|
|
|
+ return out;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Null for a missing document rather than a 404: a script that asks for a
|
|
|
+ /// document by id and tests the answer is ordinary JavaScript, and the
|
|
|
+ /// alternative is wrapping every .get() in try/catch. The authorization and
|
|
|
+ /// the data are identical to the HTTP route; only the shape of "absent"
|
|
|
+ /// differs, and only because the HTTP route has a status code to spend.
|
|
|
+ nlohmann::json get(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ const std::string id = documentId(payload);
|
|
|
+ meta(collection);
|
|
|
+ auto doc = db.client().get(qualify(config.project, collection), id);
|
|
|
+ return doc ? *doc : nlohmann::json(nullptr);
|
|
|
+ }
|
|
|
+
|
|
|
+ nlohmann::json insert(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ nlohmann::json doc = documentFrom(payload);
|
|
|
+ // An explicit id is honoured, exactly as POST /documents honours
|
|
|
+ // body.id, so a function can write an idempotent row.
|
|
|
+ std::string id;
|
|
|
+ if (payload.at("doc").is_object() && payload.at("doc").contains("id") &&
|
|
|
+ payload.at("doc").at("id").is_string())
|
|
|
+ id = payload.at("doc").at("id").get<std::string>();
|
|
|
+ meta(collection);
|
|
|
+ std::string newId;
|
|
|
+ try {
|
|
|
+ newId = db.client().insert(qualify(config.project, collection), doc, id);
|
|
|
+ } catch (const smartbotic::database::Client::Error& e) {
|
|
|
+ throw apiErrorFor(e);
|
|
|
+ }
|
|
|
+ if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
|
|
|
+ return nlohmann::json{{"id", newId}};
|
|
|
+ }
|
|
|
+
|
|
|
+ nlohmann::json update(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ const std::string id = documentId(payload);
|
|
|
+ nlohmann::json doc = documentFrom(payload);
|
|
|
+ meta(collection);
|
|
|
+ smartbotic::database::Client::Failure failure;
|
|
|
+ if (!db.client().update(qualify(config.project, collection), id, doc, failure))
|
|
|
+ throw apiErrorFor(failure, "no such document");
|
|
|
+ return nlohmann::json{{"id", id}};
|
|
|
+ }
|
|
|
+
|
|
|
+ nlohmann::json patch(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ const std::string id = documentId(payload);
|
|
|
+ nlohmann::json fields = documentFrom(payload);
|
|
|
+ meta(collection);
|
|
|
+ smartbotic::database::Client::Failure failure;
|
|
|
+ const uint64_t v = db.client().patch(qualify(config.project, collection), id, fields, failure);
|
|
|
+ if (v == 0) throw apiErrorFor(failure, "no such document");
|
|
|
+ return nlohmann::json{{"id", id}, {"version", v}};
|
|
|
+ }
|
|
|
+
|
|
|
+ nlohmann::json remove(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ const std::string id = documentId(payload);
|
|
|
+ meta(collection);
|
|
|
+ const std::string c = qualify(config.project, collection);
|
|
|
+ smartbotic::database::Client::Failure failure;
|
|
|
+ if (!db.client().remove(c, id, failure)) {
|
|
|
+ // A restrict relation is the one refusal the script can act on, so
|
|
|
+ // it arrives as the impact list on the error rather than a sentence
|
|
|
+ // - same payload the HTTP route answers with.
|
|
|
+ if (failure.code == smartbotic::database::Client::ErrorCode::FailedPrecondition) {
|
|
|
+ auto why = db.client().describeDelete(c, id);
|
|
|
+ if (why.success && why.wouldBeBlocked)
|
|
|
+ throw ApiError(ErrCode::Conflict, "relation_restricted",
|
|
|
+ "delete blocked by a relation",
|
|
|
+ {{"impacts", impactsJson(config.project, why)}});
|
|
|
+ }
|
|
|
+ throw apiErrorFor(failure, "no such document");
|
|
|
+ }
|
|
|
+ return nlohmann::json{{"deleted", id}};
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Vector search. The filter-then-rank intersection is the same algorithm
|
|
|
+ /// and the same scan cap as handlers/vectors.cpp, because the two must
|
|
|
+ /// return the same rows with the same scores for the same query. It is
|
|
|
+ /// duplicated rather than shared only because it currently lives inside
|
|
|
+ /// that route's lambda; extracting it is a separate, mechanical change.
|
|
|
+ nlohmann::json search(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ auto filters = hostdetail::queryOptionsFrom(payload).filters;
|
|
|
+ const CollectionMeta& m = vectorMeta(collection);
|
|
|
+ std::vector<float> q = resolveVector(m, payload, "query_vector", "query_text");
|
|
|
+
|
|
|
+ // Same default as POST /search, so a function and an HTTP call that
|
|
|
+ // omit top_k get the same number of hits.
|
|
|
+ uint32_t topK = 5;
|
|
|
+ if (payload.contains("top_k") && payload.at("top_k").is_number_integer()) {
|
|
|
+ const int64_t wide = payload.at("top_k").get<int64_t>();
|
|
|
+ if (wide > 0 && wide <= std::numeric_limits<uint32_t>::max())
|
|
|
+ topK = static_cast<uint32_t>(wide);
|
|
|
+ }
|
|
|
+ float minScore = 0.0f;
|
|
|
+ if (payload.contains("min_score") && payload.at("min_score").is_number())
|
|
|
+ minScore = payload.at("min_score").get<float>();
|
|
|
+
|
|
|
+ const std::string c = qualify(config.project, collection);
|
|
|
+ // The shared implementation, not a copy: a filter must mean the same
|
|
|
+ // thing here as it does on the HTTP route, scan cap included.
|
|
|
+ const std::vector<smartbotic::database::Client::SimilarityResult> results =
|
|
|
+ vectorSearch(db.client(), c, q, topK, minScore, filters);
|
|
|
+
|
|
|
+ // An array, not {results:[...]}: the design's own example reads the
|
|
|
+ // return value as the hits.
|
|
|
+ nlohmann::json out = nlohmann::json::array();
|
|
|
+ for (const auto& r : results)
|
|
|
+ out.push_back({{"id", r.id}, {"score", r.score}, {"data", r.data}});
|
|
|
+ return out;
|
|
|
+ }
|
|
|
+
|
|
|
+ nlohmann::json store(const std::string& collection, const nlohmann::json& payload) {
|
|
|
+ const CollectionMeta& m = vectorMeta(collection);
|
|
|
+ std::vector<float> vec = resolveVector(m, payload, "vector", "text");
|
|
|
+
|
|
|
+ nlohmann::json doc = nlohmann::json::object();
|
|
|
+ if (payload.contains("metadata") && payload.at("metadata").is_object())
|
|
|
+ doc = payload.at("metadata");
|
|
|
+ doc.erase("id");
|
|
|
+ if (payload.contains("text") && payload.at("text").is_string())
|
|
|
+ doc["text"] = payload.at("text");
|
|
|
+ doc["_vector"] = vec;
|
|
|
+
|
|
|
+ std::string id;
|
|
|
+ if (payload.contains("id") && payload.at("id").is_string())
|
|
|
+ id = payload.at("id").get<std::string>();
|
|
|
+ std::string newId;
|
|
|
+ try {
|
|
|
+ newId = db.client().insert(qualify(config.project, collection), doc, id);
|
|
|
+ } catch (const smartbotic::database::Client::Error& e) {
|
|
|
+ throw apiErrorFor(e);
|
|
|
+ }
|
|
|
+ if (newId.empty()) throw ApiError(ErrCode::Unavailable, "db_error", "insert failed");
|
|
|
+ return nlohmann::json{{"id", newId}};
|
|
|
+ }
|
|
|
+
|
|
|
+ // --- egress -------------------------------------------------------------
|
|
|
+
|
|
|
+ /// `__hostFetch(url, options)`.
|
|
|
+ nlohmann::json fetch(const std::string& url, const nlohmann::json& options) {
|
|
|
+ auto parts = functions::parseHttpUrl(url);
|
|
|
+ if (!parts) {
|
|
|
+ // Fail closed, and say so out loud: file:, gopher: and a bare
|
|
|
+ // hostname are all refused here, and an author who cannot see why
|
|
|
+ // would otherwise read it as a network failure.
|
|
|
+ const std::string reason = "refused '" + url + "': not an absolute http(s) URL";
|
|
|
+ blocked.push_back(reason);
|
|
|
+ throw ApiError(ErrCode::Forbidden, "egress_blocked", reason);
|
|
|
+ }
|
|
|
+
|
|
|
+ auto decision = hostdetail::decideEgress(*parts, *ssrf, hostdetail::resolveWithGetaddrinfo);
|
|
|
+ if (!decision.allowed) {
|
|
|
+ blocked.push_back(decision.reason);
|
|
|
+ throw ApiError(ErrCode::Forbidden, "egress_blocked", decision.reason);
|
|
|
+ }
|
|
|
+
|
|
|
+ int64_t requested = 0;
|
|
|
+ if (options.contains("timeoutMs") && options.at("timeoutMs").is_number_integer())
|
|
|
+ requested = std::max<int64_t>(options.at("timeoutMs").get<int64_t>(), 0);
|
|
|
+ const int64_t budget = hostdetail::outboundTimeoutMs(config.deadlineMs, elapsedMs(), requested);
|
|
|
+ // Checked BEFORE connecting, so an exhausted budget costs no socket.
|
|
|
+ // Not an egress refusal: nothing about the destination was wrong.
|
|
|
+ if (budget <= 0)
|
|
|
+ throw ApiError(ErrCode::Unavailable, "deadline_exceeded",
|
|
|
+ "the run's time budget is exhausted; not connecting to '" + parts->host + "'");
|
|
|
+
|
|
|
+ // The client is built on the NAME, so SNI, certificate verification and
|
|
|
+ // the Host header are all the name the policy approved, and the address
|
|
|
+ // map is what actually gets connected to. That pair is how the
|
|
|
+ // classify-then-connect gap closes: no second resolution happens.
|
|
|
+ //
|
|
|
+ // httplib reads no http_proxy/https_proxy environment variable and
|
|
|
+ // set_proxy() is never called here, so a proxy cannot reroute an
|
|
|
+ // approved destination to an unapproved one.
|
|
|
+ const bool bracketed = parts->host.find(':') != std::string::npos;
|
|
|
+ const std::string origin = parts->scheme + "://" +
|
|
|
+ (bracketed ? "[" + parts->host + "]" : parts->host) + ":" +
|
|
|
+ std::to_string(parts->port);
|
|
|
+ httplib::Client cli(origin);
|
|
|
+ applyOutboundDefaults(cli);
|
|
|
+ cli.set_hostname_addr_map({{parts->host, decision.pinnedAddress}});
|
|
|
+ const time_t sec = static_cast<time_t>((budget + 999) / 1000);
|
|
|
+ cli.set_connection_timeout(sec, 0);
|
|
|
+ cli.set_read_timeout(sec, 0);
|
|
|
+ cli.set_write_timeout(sec, 0);
|
|
|
+
|
|
|
+ httplib::Request req;
|
|
|
+ req.method = "GET";
|
|
|
+ if (options.contains("method") && options.at("method").is_string()) {
|
|
|
+ req.method = options.at("method").get<std::string>();
|
|
|
+ std::transform(req.method.begin(), req.method.end(), req.method.begin(),
|
|
|
+ [](unsigned char c) { return std::toupper(c); });
|
|
|
+ }
|
|
|
+ // The fragment is a client-side notion and has no business on the wire.
|
|
|
+ req.path = parts->path.substr(0, parts->path.find('#'));
|
|
|
+ if (req.path.empty()) req.path = "/";
|
|
|
+ if (options.contains("headers") && options.at("headers").is_object())
|
|
|
+ for (auto it = options.at("headers").begin(); it != options.at("headers").end(); ++it)
|
|
|
+ if (it.value().is_string()) req.headers.emplace(it.key(), it.value().get<std::string>());
|
|
|
+ if (options.contains("body") && options.at("body").is_string()) {
|
|
|
+ req.body = options.at("body").get<std::string>();
|
|
|
+ if (req.headers.find("Content-Type") == req.headers.end())
|
|
|
+ req.headers.emplace("Content-Type", "application/json");
|
|
|
+ }
|
|
|
+
|
|
|
+ auto result = cli.send(req);
|
|
|
+ if (!result)
|
|
|
+ throw ApiError(ErrCode::Unavailable, "fetch_failed",
|
|
|
+ "request to '" + parts->host + "' failed: " + httplib::to_string(result.error()));
|
|
|
+
|
|
|
+ nlohmann::json headers = nlohmann::json::object();
|
|
|
+ for (const auto& [name, value] : result->headers) headers[name] = value;
|
|
|
+ return nlohmann::json{{"status", result->status},
|
|
|
+ {"ok", result->status >= 200 && result->status < 300},
|
|
|
+ {"headers", headers},
|
|
|
+ {"body", result->body}};
|
|
|
+ }
|
|
|
+
|
|
|
+ // --- the native bindings ------------------------------------------------
|
|
|
+ //
|
|
|
+ // Static members of Impl rather than free functions, because the seam
|
|
|
+ // header declares Impl a PRIVATE nested type of HostContext: only code
|
|
|
+ // inside that scope may name it.
|
|
|
+
|
|
|
+ /// The Impl behind a binding, carried as the function's own data rather
|
|
|
+ /// than in a global or the context opaque - the core already uses the
|
|
|
+ /// context opaque for its RunState, and a global would make two concurrent
|
|
|
+ /// runs in one process share an identity.
|
|
|
+ static Impl* implFrom(JSContext* ctx, JSValueConst* data) {
|
|
|
+ uint64_t bits = 0;
|
|
|
+ if (JS_ToBigUint64(ctx, &bits, data[0]) != 0) return nullptr;
|
|
|
+ return reinterpret_cast<Impl*>(static_cast<uintptr_t>(bits));
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Every binding body funnels through here. A C++ exception escaping into
|
|
|
+ /// QuickJS's C frames is undefined behaviour, so NOTHING may propagate out:
|
|
|
+ /// an ApiError becomes a catchable JS Error and anything else becomes an
|
|
|
+ /// internal one.
|
|
|
+ template <typename Fn>
|
|
|
+ static JSValue guarded(JSContext* ctx, Fn&& body) {
|
|
|
+ try {
|
|
|
+ return body();
|
|
|
+ } catch (const ApiError& e) {
|
|
|
+ return throwApiError(ctx, e);
|
|
|
+ } catch (const std::exception& e) {
|
|
|
+ return throwApiError(ctx, ApiError(ErrCode::Internal, "internal", e.what()));
|
|
|
+ } catch (...) {
|
|
|
+ return throwApiError(ctx,
|
|
|
+ ApiError(ErrCode::Internal, "internal", "unknown host failure"));
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ static JSValue hostDb(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int,
|
|
|
+ JSValueConst* data) {
|
|
|
+ return guarded(ctx, [&]() -> JSValue {
|
|
|
+ Impl* impl = implFrom(ctx, data);
|
|
|
+ if (!impl || argc < 3)
|
|
|
+ throw ApiError(ErrCode::Internal, "internal",
|
|
|
+ "__hostDb called with a bad argument list");
|
|
|
+ const std::string collection = toText(ctx, argv[0]);
|
|
|
+ const std::string op = toText(ctx, argv[1]);
|
|
|
+ return toJs(ctx, impl->dbCall(collection, op, fromJs(ctx, argv[2])));
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ static JSValue hostFetch(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int,
|
|
|
+ JSValueConst* data) {
|
|
|
+ return guarded(ctx, [&]() -> JSValue {
|
|
|
+ Impl* impl = implFrom(ctx, data);
|
|
|
+ if (!impl || argc < 1)
|
|
|
+ throw ApiError(ErrCode::Internal, "internal",
|
|
|
+ "__hostFetch called with a bad argument list");
|
|
|
+ const std::string url = toText(ctx, argv[0]);
|
|
|
+ nlohmann::json options = argc > 1 ? fromJs(ctx, argv[1]) : nlohmann::json::object();
|
|
|
+ if (!options.is_object()) options = nlohmann::json::object();
|
|
|
+ return toJs(ctx, impl->fetch(url, options));
|
|
|
+ });
|
|
|
+ }
|
|
|
+
|
|
|
+ static JSValue hostLog(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int,
|
|
|
+ JSValueConst* data) {
|
|
|
+ return guarded(ctx, [&]() -> JSValue {
|
|
|
+ Impl* impl = implFrom(ctx, data);
|
|
|
+ if (impl && argc >= 1) impl->addLog(toText(ctx, argv[0]));
|
|
|
+ return JS_UNDEFINED;
|
|
|
+ });
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+namespace {
|
|
|
+
|
|
|
+/// A trigger field, or an empty object when the trigger does not carry it. A
|
|
|
+/// cron or event run has no HTTP shape at all, and `ctx.query.q` must then read
|
|
|
+/// as undefined rather than throwing on undefined.query.
|
|
|
+nlohmann::json triggerObject(const nlohmann::json& trigger, const char* field) {
|
|
|
+ if (trigger.is_object() && trigger.contains(field) && trigger.at(field).is_object())
|
|
|
+ return trigger.at(field);
|
|
|
+ return nlohmann::json::object();
|
|
|
+}
|
|
|
+
|
|
|
+std::string triggerString(const nlohmann::json& trigger, const char* field) {
|
|
|
+ if (trigger.is_object() && trigger.contains(field) && trigger.at(field).is_string())
|
|
|
+ return trigger.at(field).get<std::string>();
|
|
|
+ return std::string();
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace
|
|
|
+
|
|
|
+// ---------------------------------------------------------------------------
|
|
|
+
|
|
|
+HostContext::HostContext(DbGateway& db, HostContextConfig config)
|
|
|
+ : impl_(std::make_unique<Impl>(db, std::move(config))) {}
|
|
|
+
|
|
|
+HostContext::~HostContext() = default;
|
|
|
+
|
|
|
+const std::vector<std::string>& HostContext::logLines() const { return impl_->log; }
|
|
|
+const std::vector<std::string>& HostContext::blockedEgress() const { return impl_->blocked; }
|
|
|
+
|
|
|
+std::string_view hostPreludeSource() { return generated::kHostPreludeJs; }
|
|
|
+
|
|
|
+bool HostContext::install(const JsBindingTarget& target, std::string& error) {
|
|
|
+ auto* ctx = static_cast<JSContext*>(target.js_context);
|
|
|
+ auto* ctxObject = static_cast<JSValue*>(target.ctx_object);
|
|
|
+ if (ctx == nullptr || ctxObject == nullptr) {
|
|
|
+ error = "host bindings need both a context and a ctx object";
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ // The data fields first: plain values, shaped in C++ where the shaping is
|
|
|
+ // testable, leaving the prelude with nothing to do but the builder.
|
|
|
+ const nlohmann::json& trigger = impl_->config.trigger;
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "method",
|
|
|
+ JS_NewString(ctx, triggerString(trigger, "method").c_str()));
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "path",
|
|
|
+ JS_NewString(ctx, triggerString(trigger, "path").c_str()));
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "params", toJs(ctx, triggerObject(trigger, "params")));
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "query", toJs(ctx, triggerObject(trigger, "query")));
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "headers", toJs(ctx, triggerObject(trigger, "headers")));
|
|
|
+ // The body is whatever arrived, including a JSON array or a bare string.
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "body",
|
|
|
+ toJs(ctx, trigger.is_object() ? trigger.value("body", nlohmann::json())
|
|
|
+ : nlohmann::json()));
|
|
|
+ JS_SetPropertyStr(ctx, *ctxObject, "env",
|
|
|
+ toJs(ctx, impl_->config.env.is_object() ? impl_->config.env
|
|
|
+ : nlohmann::json::object()));
|
|
|
+
|
|
|
+ // The bindings are passed INTO the prelude rather than set on globalThis,
|
|
|
+ // so user code cannot reach them and skip the builder's argument checks.
|
|
|
+ JSValue cookie = JS_NewBigUint64(ctx, static_cast<uint64_t>(reinterpret_cast<uintptr_t>(impl_.get())));
|
|
|
+ JSValueConst data[1] = {cookie};
|
|
|
+ JSValue db = JS_NewCFunctionData(ctx, Impl::hostDb, 3, 0, 1, data);
|
|
|
+ JSValue fetch = JS_NewCFunctionData(ctx, Impl::hostFetch, 2, 0, 1, data);
|
|
|
+ JSValue log = JS_NewCFunctionData(ctx, Impl::hostLog, 1, 0, 1, data);
|
|
|
+ JS_FreeValue(ctx, cookie);
|
|
|
+
|
|
|
+ const std::string_view prelude = hostPreludeSource();
|
|
|
+ JSValue factory = JS_Eval(ctx, prelude.data(), prelude.size(), "<host-prelude>",
|
|
|
+ JS_EVAL_TYPE_GLOBAL);
|
|
|
+ bool ok = true;
|
|
|
+ if (JS_IsException(factory)) {
|
|
|
+ // A broken prelude is our bug, never the tenant's, so it fails the run
|
|
|
+ // before any user code executes rather than surfacing as a missing
|
|
|
+ // ctx.collections halfway through.
|
|
|
+ JSValue exc = JS_GetException(ctx);
|
|
|
+ error = "the host prelude failed to evaluate: " + toText(ctx, exc);
|
|
|
+ JS_FreeValue(ctx, exc);
|
|
|
+ ok = false;
|
|
|
+ } else {
|
|
|
+ JSValueConst args[4] = {*ctxObject, db, fetch, log};
|
|
|
+ JSValue applied = JS_Call(ctx, factory, JS_UNDEFINED, 4, args);
|
|
|
+ if (JS_IsException(applied)) {
|
|
|
+ JSValue exc = JS_GetException(ctx);
|
|
|
+ error = "the host prelude failed to install: " + toText(ctx, exc);
|
|
|
+ JS_FreeValue(ctx, exc);
|
|
|
+ ok = false;
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, applied);
|
|
|
+ }
|
|
|
+
|
|
|
+ JS_FreeValue(ctx, factory);
|
|
|
+ JS_FreeValue(ctx, db);
|
|
|
+ JS_FreeValue(ctx, fetch);
|
|
|
+ JS_FreeValue(ctx, log);
|
|
|
+ return ok;
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace svapi::runner
|