|
|
@@ -0,0 +1,688 @@
|
|
|
+#include "runner/js_runtime.hpp"
|
|
|
+
|
|
|
+#include <algorithm>
|
|
|
+#include <atomic>
|
|
|
+#include <chrono>
|
|
|
+#include <cstring>
|
|
|
+#include <stdexcept>
|
|
|
+#include <utility>
|
|
|
+
|
|
|
+#include "quickjs.h"
|
|
|
+
|
|
|
+namespace svapi::runner {
|
|
|
+namespace {
|
|
|
+
|
|
|
+int64_t nowMs() {
|
|
|
+ using namespace std::chrono;
|
|
|
+ return duration_cast<milliseconds>(steady_clock::now().time_since_epoch()).count();
|
|
|
+}
|
|
|
+
|
|
|
+/// Console capture is bounded: a function in a loop could otherwise turn
|
|
|
+/// console.log into an unmetered allocation channel, and the run result travels
|
|
|
+/// over HTTP to whoever invoked it.
|
|
|
+constexpr size_t kMaxConsoleLines = 1000;
|
|
|
+constexpr size_t kMaxConsoleBytes = 64u * 1024;
|
|
|
+
|
|
|
+/// How many pending jobs a timed-out run may be flushed with before the runtime
|
|
|
+/// is declared poisoned. Flushing happens with the deadline already expired, so
|
|
|
+/// each job is interrupted at its first bytecode op; the cap only bounds a
|
|
|
+/// module that keeps re-enqueueing from that interrupted frame.
|
|
|
+constexpr int kPoisonFlushBudget = 256;
|
|
|
+
|
|
|
+/// Per-run state, hung off the context. One context per run means this is
|
|
|
+/// created and destroyed with the run, which is exactly the lifetime we want.
|
|
|
+struct RunState {
|
|
|
+ std::vector<std::string> console;
|
|
|
+ size_t console_bytes = 0;
|
|
|
+ bool console_truncated = false;
|
|
|
+
|
|
|
+ void add(std::string line) {
|
|
|
+ if (console.size() >= kMaxConsoleLines || console_bytes >= kMaxConsoleBytes) {
|
|
|
+ if (!console_truncated) {
|
|
|
+ console_truncated = true;
|
|
|
+ console.emplace_back("[console output truncated]");
|
|
|
+ }
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ console_bytes += line.size();
|
|
|
+ console.push_back(std::move(line));
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+/// Shared with the interrupt handler, which QuickJS may call from inside any JS
|
|
|
+/// frame - including one running under JS_ExecutePendingJob.
|
|
|
+struct RuntimeState {
|
|
|
+ std::atomic<int64_t> deadline_ms{0}; // 0 = no run in progress, no deadline
|
|
|
+ std::atomic<bool> interrupted{false};
|
|
|
+};
|
|
|
+
|
|
|
+int interruptHandler(JSRuntime*, void* opaque) {
|
|
|
+ auto* state = static_cast<RuntimeState*>(opaque);
|
|
|
+ const int64_t deadline = state->deadline_ms.load(std::memory_order_relaxed);
|
|
|
+ if (deadline == 0 || nowMs() < deadline) return 0;
|
|
|
+ state->interrupted.store(true, std::memory_order_relaxed);
|
|
|
+ return 1; // unwinds the whole JS stack with an uncatchable-ish InternalError
|
|
|
+}
|
|
|
+
|
|
|
+std::string toText(JSContext* ctx, JSValueConst v) {
|
|
|
+ const char* s = JS_ToCString(ctx, v);
|
|
|
+ if (!s) {
|
|
|
+ JS_FreeValue(ctx, JS_GetException(ctx)); // stringification itself can throw
|
|
|
+ return "<unprintable>";
|
|
|
+ }
|
|
|
+ std::string out(s);
|
|
|
+ JS_FreeCString(ctx, s);
|
|
|
+ return out;
|
|
|
+}
|
|
|
+
|
|
|
+/// Format a thrown value the way an operator wants to read it: the message
|
|
|
+/// first, then the stack if QuickJS attached one.
|
|
|
+std::string formatThrown(JSContext* ctx, JSValue exc) {
|
|
|
+ std::string text;
|
|
|
+ if (JS_IsNull(exc) || JS_IsUndefined(exc)) {
|
|
|
+ // QuickJS throws a bare null when it could not even allocate the Error
|
|
|
+ // object, which in practice only happens under the memory limit.
|
|
|
+ text = "out of memory";
|
|
|
+ } else {
|
|
|
+ text = toText(ctx, exc);
|
|
|
+ if (JS_IsObject(exc)) {
|
|
|
+ JSValue stack = JS_GetPropertyStr(ctx, exc, "stack");
|
|
|
+ if (!JS_IsUndefined(stack) && !JS_IsException(stack)) {
|
|
|
+ std::string st = toText(ctx, stack);
|
|
|
+ if (!st.empty()) text += "\n" + st;
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, stack);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, exc);
|
|
|
+ return text;
|
|
|
+}
|
|
|
+
|
|
|
+std::string takeException(JSContext* ctx) { return formatThrown(ctx, JS_GetException(ctx)); }
|
|
|
+
|
|
|
+/// Values cross the boundary as JSON, which is also the only shape the registry
|
|
|
+/// and the HTTP protocol can carry. Non-serialisable values (functions,
|
|
|
+/// undefined) come back as null rather than failing the run.
|
|
|
+bool fromJs(JSContext* ctx, JSValueConst v, nlohmann::json& out, std::string& error) {
|
|
|
+ JSValue json = JS_JSONStringify(ctx, v, JS_UNDEFINED, JS_UNDEFINED);
|
|
|
+ if (JS_IsException(json)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ if (JS_IsUndefined(json)) { // undefined, a function, a symbol
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ out = nullptr;
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ const std::string text = toText(ctx, json);
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ out = nlohmann::json::parse(text, nullptr, false);
|
|
|
+ if (out.is_discarded()) {
|
|
|
+ error = "the returned value is not representable as JSON";
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ return true;
|
|
|
+}
|
|
|
+
|
|
|
+JSValue toJs(JSContext* ctx, const nlohmann::json& j) {
|
|
|
+ const std::string text = j.dump();
|
|
|
+ return JS_ParseJSON(ctx, text.c_str(), text.size(), "<ctx>");
|
|
|
+}
|
|
|
+
|
|
|
+/// console.log/warn/error. The level travels as a prefix because the protocol
|
|
|
+/// carries one flat `console[]` array and a timeout diagnosis usually hinges on
|
|
|
+/// whether the last line was an error.
|
|
|
+JSValue consoleWrite(JSContext* ctx, JSValueConst, int argc, JSValueConst* argv, int magic) {
|
|
|
+ auto* state = static_cast<RunState*>(JS_GetContextOpaque(ctx));
|
|
|
+ if (!state) return JS_UNDEFINED;
|
|
|
+
|
|
|
+ std::string line;
|
|
|
+ if (magic == 1) line = "[warn] ";
|
|
|
+ if (magic == 2) line = "[error] ";
|
|
|
+ for (int i = 0; i < argc; i++) {
|
|
|
+ if (i > 0) line += ' ';
|
|
|
+ // Objects as JSON, primitives as text: "[object Object]" in a log is
|
|
|
+ // worse than useless when debugging a function.
|
|
|
+ if (JS_IsObject(argv[i]) && !JS_IsFunction(ctx, argv[i])) {
|
|
|
+ JSValue json = JS_JSONStringify(ctx, argv[i], JS_UNDEFINED, JS_UNDEFINED);
|
|
|
+ if (!JS_IsException(json) && !JS_IsUndefined(json)) {
|
|
|
+ line += toText(ctx, json);
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (JS_IsException(json)) JS_FreeValue(ctx, JS_GetException(ctx));
|
|
|
+ JS_FreeValue(ctx, json);
|
|
|
+ }
|
|
|
+ line += toText(ctx, argv[i]);
|
|
|
+ }
|
|
|
+ state->add(std::move(line));
|
|
|
+ return JS_UNDEFINED;
|
|
|
+}
|
|
|
+
|
|
|
+void installConsole(JSContext* ctx) {
|
|
|
+ JSValue global = JS_GetGlobalObject(ctx);
|
|
|
+ JSValue console = JS_NewObject(ctx);
|
|
|
+ JS_SetPropertyStr(ctx, console, "log",
|
|
|
+ JS_NewCFunctionMagic(ctx, consoleWrite, "log", 1, JS_CFUNC_generic_magic, 0));
|
|
|
+ JS_SetPropertyStr(ctx, console, "info",
|
|
|
+ JS_NewCFunctionMagic(ctx, consoleWrite, "info", 1, JS_CFUNC_generic_magic, 0));
|
|
|
+ JS_SetPropertyStr(ctx, console, "debug",
|
|
|
+ JS_NewCFunctionMagic(ctx, consoleWrite, "debug", 1, JS_CFUNC_generic_magic, 0));
|
|
|
+ JS_SetPropertyStr(ctx, console, "warn",
|
|
|
+ JS_NewCFunctionMagic(ctx, consoleWrite, "warn", 1, JS_CFUNC_generic_magic, 1));
|
|
|
+ JS_SetPropertyStr(ctx, console, "error",
|
|
|
+ JS_NewCFunctionMagic(ctx, consoleWrite, "error", 1, JS_CFUNC_generic_magic, 2));
|
|
|
+ JS_SetPropertyStr(ctx, global, "console", console);
|
|
|
+ JS_FreeValue(ctx, global);
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace
|
|
|
+
|
|
|
+struct JsRuntime::Impl {
|
|
|
+ JSRuntime* rt = nullptr;
|
|
|
+ JsLimits limits;
|
|
|
+ RuntimeState state;
|
|
|
+ bool poisoned = false;
|
|
|
+
|
|
|
+ /// Fresh context for one run or one descriptor read. Nothing a tenant can
|
|
|
+ /// reach survives this object, which is the whole point.
|
|
|
+ JSContext* newContext(RunState* run_state) {
|
|
|
+ JSContext* ctx = JS_NewContext(rt);
|
|
|
+ if (!ctx) return nullptr;
|
|
|
+ JS_SetContextOpaque(ctx, run_state);
|
|
|
+ installConsole(ctx);
|
|
|
+ return ctx;
|
|
|
+ }
|
|
|
+
|
|
|
+ void armDeadline(int64_t budget_ms) {
|
|
|
+ state.interrupted.store(false, std::memory_order_relaxed);
|
|
|
+ state.deadline_ms.store(nowMs() + budget_ms, std::memory_order_relaxed);
|
|
|
+ }
|
|
|
+
|
|
|
+ void disarmDeadline() { state.deadline_ms.store(0, std::memory_order_relaxed); }
|
|
|
+
|
|
|
+ bool expired() const {
|
|
|
+ const int64_t deadline = state.deadline_ms.load(std::memory_order_relaxed);
|
|
|
+ return deadline != 0 && nowMs() >= deadline;
|
|
|
+ }
|
|
|
+
|
|
|
+ bool interrupted() const { return state.interrupted.load(std::memory_order_relaxed); }
|
|
|
+
|
|
|
+ size_t mallocBytes() const {
|
|
|
+ JSMemoryUsage usage{};
|
|
|
+ JS_ComputeMemoryUsage(rt, &usage);
|
|
|
+ return static_cast<size_t>(usage.malloc_size);
|
|
|
+ }
|
|
|
+
|
|
|
+ /// An allocation failure may surface either as an InternalError carrying
|
|
|
+ /// "out of memory" or, when even that Error could not be allocated, as a
|
|
|
+ /// bare null. Neither is reliable on its own, so corroborate with the
|
|
|
+ /// allocator: close to the ceiling, an error is a memory error.
|
|
|
+ bool looksLikeOom(const std::string& error) const {
|
|
|
+ if (error.find("out of memory") != std::string::npos) return true;
|
|
|
+ return nearMemoryCeiling();
|
|
|
+ }
|
|
|
+
|
|
|
+ bool nearMemoryCeiling() const {
|
|
|
+ if (limits.memory_limit_bytes == 0) return false;
|
|
|
+ return mallocBytes() >= limits.memory_limit_bytes / 10 * 9;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Run queued microtasks until the queue drains or the deadline passes.
|
|
|
+ /// The C++ clock check only stops the LOOP; what stops a single job that
|
|
|
+ /// never returns is the interrupt handler firing inside it.
|
|
|
+ void drainJobs(std::string& job_error) {
|
|
|
+ while (JS_IsJobPending(rt)) {
|
|
|
+ if (expired() || interrupted()) return;
|
|
|
+ JSContext* job_ctx = nullptr;
|
|
|
+ const int rc = JS_ExecutePendingJob(rt, &job_ctx);
|
|
|
+ if (rc == 0) return;
|
|
|
+ if (rc < 0 && job_ctx && job_error.empty()) job_error = takeException(job_ctx);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Resolve `value` to a settled, non-promise value, draining microtasks as
|
|
|
+ /// needed. Consumes `value`.
|
|
|
+ JSValue await(JSContext* ctx, JSValue value, std::string& error) {
|
|
|
+ for (;;) {
|
|
|
+ std::string job_error;
|
|
|
+ drainJobs(job_error);
|
|
|
+
|
|
|
+ const JSPromiseStateEnum st = JS_PromiseState(ctx, value);
|
|
|
+ if (st == JS_PROMISE_NOT_A_PROMISE) {
|
|
|
+ if (!job_error.empty() && error.empty()) error = job_error;
|
|
|
+ return value;
|
|
|
+ }
|
|
|
+ if (st == JS_PROMISE_FULFILLED) {
|
|
|
+ JSValue inner = JS_PromiseResult(ctx, value);
|
|
|
+ JS_FreeValue(ctx, value);
|
|
|
+ value = inner; // a promise resolving to a promise must be followed
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (st == JS_PROMISE_REJECTED) {
|
|
|
+ JS_PromiseMarkAsHandled(ctx, value);
|
|
|
+ JSValue reason = JS_PromiseResult(ctx, value);
|
|
|
+ JS_FreeValue(ctx, value);
|
|
|
+ error = formatThrown(ctx, reason);
|
|
|
+ return JS_UNDEFINED;
|
|
|
+ }
|
|
|
+ // Still pending with nothing left to run: either we ran out of time
|
|
|
+ // or the function returned a promise nobody will ever settle.
|
|
|
+ JS_PromiseMarkAsHandled(ctx, value);
|
|
|
+ JS_FreeValue(ctx, value);
|
|
|
+ if (error.empty()) {
|
|
|
+ error = interrupted() || expired()
|
|
|
+ ? "wall-time limit exceeded"
|
|
|
+ : (job_error.empty() ? "the returned promise never settled" : job_error);
|
|
|
+ }
|
|
|
+ return JS_UNDEFINED;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /// Instantiate and evaluate module bytecode in `ctx`. Returns the module
|
|
|
+ /// definition, or nullptr with `error` set.
|
|
|
+ JSModuleDef* evaluateModule(JSContext* ctx, const JsBytecode& bytecode, std::string& error) {
|
|
|
+ JSValue obj = JS_ReadObject(ctx, bytecode.bytes.data(), bytecode.bytes.size(),
|
|
|
+ JS_READ_OBJ_BYTECODE);
|
|
|
+ if (JS_IsException(obj)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ JS_FreeValue(ctx, obj);
|
|
|
+ return nullptr;
|
|
|
+ }
|
|
|
+ if (!JS_IsModule(obj)) {
|
|
|
+ JS_FreeValue(ctx, obj);
|
|
|
+ error = "the compiled artifact is not an ES module";
|
|
|
+ return nullptr;
|
|
|
+ }
|
|
|
+ if (JS_ResolveModule(ctx, obj) < 0) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ JS_FreeValue(ctx, obj);
|
|
|
+ return nullptr;
|
|
|
+ }
|
|
|
+ auto* module = static_cast<JSModuleDef*>(JS_VALUE_GET_PTR(obj));
|
|
|
+
|
|
|
+ // JS_EvalFunction consumes obj and, because a module may top-level
|
|
|
+ // await, hands back a promise rather than a finished evaluation.
|
|
|
+ JSValue eval_result = JS_EvalFunction(ctx, obj);
|
|
|
+ if (JS_IsException(eval_result)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ JS_FreeValue(ctx, eval_result);
|
|
|
+ return nullptr;
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, await(ctx, eval_result, error));
|
|
|
+ if (!error.empty()) return nullptr;
|
|
|
+ return module;
|
|
|
+ }
|
|
|
+
|
|
|
+ /// After a timed-out run the job queue still holds this tenant's
|
|
|
+ /// microtasks, and that queue belongs to the RUNTIME, not the context a
|
|
|
+ /// fresh run would get. Try to flush it with the deadline still expired;
|
|
|
+ /// if anything survives, the runtime can never be reused.
|
|
|
+ void settleAfterRun() {
|
|
|
+ if (!JS_IsJobPending(rt)) return;
|
|
|
+ // Flush with the deadline forced into the past, so the interrupt
|
|
|
+ // handler aborts every leftover job at its first bytecode op. Without
|
|
|
+ // this a single leftover job spinning in a loop would hang the flush.
|
|
|
+ state.deadline_ms.store(nowMs() - 1, std::memory_order_relaxed);
|
|
|
+ for (int i = 0; i < kPoisonFlushBudget && JS_IsJobPending(rt); i++) {
|
|
|
+ JSContext* job_ctx = nullptr;
|
|
|
+ if (JS_ExecutePendingJob(rt, &job_ctx) < 0 && job_ctx) {
|
|
|
+ JS_FreeValue(job_ctx, JS_GetException(job_ctx));
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (JS_IsJobPending(rt)) poisoned = true;
|
|
|
+ disarmDeadline();
|
|
|
+ }
|
|
|
+};
|
|
|
+
|
|
|
+JsRuntime::JsRuntime(JsLimits limits) : impl_(std::make_unique<Impl>()) {
|
|
|
+ impl_->limits = limits;
|
|
|
+ impl_->rt = JS_NewRuntime();
|
|
|
+ if (!impl_->rt) throw std::runtime_error("JS_NewRuntime failed");
|
|
|
+ JS_SetMemoryLimit(impl_->rt, limits.memory_limit_bytes);
|
|
|
+ JS_SetMaxStackSize(impl_->rt, limits.max_stack_bytes);
|
|
|
+ JS_SetInterruptHandler(impl_->rt, interruptHandler, &impl_->state);
|
|
|
+}
|
|
|
+
|
|
|
+JsRuntime::~JsRuntime() {
|
|
|
+ if (impl_ && impl_->rt) {
|
|
|
+ // JS_FreeRuntime is the only call that clears leftover jobs, which is
|
|
|
+ // why a poisoned runtime is destroyed rather than cleaned up.
|
|
|
+ impl_->disarmDeadline();
|
|
|
+ JS_FreeRuntime(impl_->rt);
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+const JsLimits& JsRuntime::limits() const { return impl_->limits; }
|
|
|
+
|
|
|
+size_t JsRuntime::mallocBytes() const { return impl_->mallocBytes(); }
|
|
|
+
|
|
|
+void JsRuntime::updateStackTop() { JS_UpdateStackTop(impl_->rt); }
|
|
|
+
|
|
|
+void JsRuntime::collectGarbage() { JS_RunGC(impl_->rt); }
|
|
|
+
|
|
|
+bool JsRuntime::poisoned() const { return impl_->poisoned; }
|
|
|
+
|
|
|
+std::optional<JsBytecode> JsRuntime::compile(std::string_view source, const std::string& filename,
|
|
|
+ std::string& error_out) {
|
|
|
+ RunState run_state;
|
|
|
+ JSContext* ctx = impl_->newContext(&run_state);
|
|
|
+ if (!ctx) {
|
|
|
+ error_out = "out of memory";
|
|
|
+ return std::nullopt;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Compiling arbitrary source is itself unbounded work (a pathological
|
|
|
+ // regexp or a huge literal), so it runs under the same wall-time ceiling.
|
|
|
+ impl_->armDeadline(impl_->limits.wall_time_ms);
|
|
|
+
|
|
|
+ std::optional<JsBytecode> result;
|
|
|
+ // JS_Eval requires a NUL-terminated buffer, which a string_view is not.
|
|
|
+ const std::string src(source);
|
|
|
+ JSValue obj = JS_Eval(ctx, src.c_str(), src.size(), filename.c_str(),
|
|
|
+ JS_EVAL_TYPE_MODULE | JS_EVAL_FLAG_COMPILE_ONLY);
|
|
|
+ if (JS_IsException(obj)) {
|
|
|
+ error_out = takeException(ctx);
|
|
|
+ } else {
|
|
|
+ size_t size = 0;
|
|
|
+ uint8_t* buf = JS_WriteObject(ctx, &size, obj, JS_WRITE_OBJ_BYTECODE);
|
|
|
+ if (!buf) {
|
|
|
+ error_out = takeException(ctx);
|
|
|
+ } else {
|
|
|
+ JsBytecode bc;
|
|
|
+ bc.bytes.assign(buf, buf + size);
|
|
|
+ js_free(ctx, buf);
|
|
|
+ result = std::move(bc);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, obj);
|
|
|
+
|
|
|
+ impl_->disarmDeadline();
|
|
|
+ JS_FreeContext(ctx);
|
|
|
+ if (!result && error_out.empty()) error_out = "compilation failed";
|
|
|
+ return result;
|
|
|
+}
|
|
|
+
|
|
|
+JsResult JsRuntime::run(const JsBytecode& bytecode, const nlohmann::json& ctx_arg,
|
|
|
+ int64_t wall_time_override_ms, JsHostBindings* host) {
|
|
|
+ JsResult result;
|
|
|
+ const auto started = std::chrono::steady_clock::now();
|
|
|
+ const auto finish = [&] {
|
|
|
+ result.duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
|
+ std::chrono::steady_clock::now() - started)
|
|
|
+ .count();
|
|
|
+ return result;
|
|
|
+ };
|
|
|
+
|
|
|
+ if (bytecode.empty()) {
|
|
|
+ result.error = "no compiled function to run";
|
|
|
+ return finish();
|
|
|
+ }
|
|
|
+ if (impl_->poisoned) {
|
|
|
+ result.error = "this runtime was retired and must not run another function";
|
|
|
+ return finish();
|
|
|
+ }
|
|
|
+
|
|
|
+ // A descriptor may ask for less time than the ceiling, never more.
|
|
|
+ int64_t budget = impl_->limits.wall_time_ms;
|
|
|
+ if (wall_time_override_ms > 0) budget = std::min(budget, wall_time_override_ms);
|
|
|
+
|
|
|
+ RunState run_state;
|
|
|
+ JSContext* ctx = impl_->newContext(&run_state);
|
|
|
+ if (!ctx) {
|
|
|
+ result.error = "out of memory";
|
|
|
+ result.out_of_memory = true;
|
|
|
+ impl_->poisoned = true;
|
|
|
+ return finish();
|
|
|
+ }
|
|
|
+
|
|
|
+ impl_->armDeadline(budget);
|
|
|
+
|
|
|
+ std::string error;
|
|
|
+ if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
|
|
|
+ JSValue ns = JS_GetModuleNamespace(ctx, module);
|
|
|
+ if (JS_IsException(ns)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ } else {
|
|
|
+ JSValue fn = JS_GetPropertyStr(ctx, ns, "default");
|
|
|
+ if (JS_IsException(fn)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ } else if (!JS_IsFunction(ctx, fn)) {
|
|
|
+ error = "the module has no default export function";
|
|
|
+ } else {
|
|
|
+ JSValue arg = toJs(ctx, ctx_arg);
|
|
|
+ if (JS_IsException(arg)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ } else {
|
|
|
+ if (host) {
|
|
|
+ // install() decorates this object in place; it may not
|
|
|
+ // swap the handle, which run() owns.
|
|
|
+ JsBindingTarget target;
|
|
|
+ target.js_context = ctx;
|
|
|
+ target.ctx_object = &arg;
|
|
|
+ std::string host_error;
|
|
|
+ if (!host->install(target, host_error)) {
|
|
|
+ error = host_error.empty() ? "host bindings failed to install"
|
|
|
+ : host_error;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (error.empty()) {
|
|
|
+ JSValue returned = JS_Call(ctx, fn, JS_UNDEFINED, 1, &arg);
|
|
|
+ if (JS_IsException(returned)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ JS_FreeValue(ctx, returned);
|
|
|
+ } else {
|
|
|
+ JSValue settled = impl_->await(ctx, returned, error);
|
|
|
+ if (error.empty()) fromJs(ctx, settled, result.value, error);
|
|
|
+ JS_FreeValue(ctx, settled);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, arg);
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, fn);
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, ns);
|
|
|
+ }
|
|
|
+
|
|
|
+ // The handler fires inside a JS frame; the clock catches the case where the
|
|
|
+ // deadline passed between two microtasks, with no frame to interrupt.
|
|
|
+ const bool out_of_time = impl_->interrupted() || impl_->expired();
|
|
|
+ impl_->disarmDeadline();
|
|
|
+
|
|
|
+ result.console_output = std::move(run_state.console);
|
|
|
+ if (error.empty()) {
|
|
|
+ result.ok = true;
|
|
|
+ } else {
|
|
|
+ result.error = error;
|
|
|
+ if (out_of_time) {
|
|
|
+ result.timed_out = true;
|
|
|
+ result.error = "wall-time limit of " + std::to_string(budget) + " ms exceeded";
|
|
|
+ } else if (impl_->looksLikeOom(error)) {
|
|
|
+ result.out_of_memory = true;
|
|
|
+ // The allocator is at its ceiling with this tenant's data still
|
|
|
+ // reachable; hand this runtime back to nobody.
|
|
|
+ impl_->poisoned = true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ impl_->settleAfterRun();
|
|
|
+ JS_FreeContext(ctx);
|
|
|
+ return finish();
|
|
|
+}
|
|
|
+
|
|
|
+std::optional<nlohmann::json> JsRuntime::readExport(const JsBytecode& bytecode,
|
|
|
+ const std::string& export_name,
|
|
|
+ std::string& error_out) {
|
|
|
+ if (bytecode.empty()) {
|
|
|
+ error_out = "no compiled function to read";
|
|
|
+ return std::nullopt;
|
|
|
+ }
|
|
|
+ if (impl_->poisoned) {
|
|
|
+ error_out = "this runtime was retired";
|
|
|
+ return std::nullopt;
|
|
|
+ }
|
|
|
+
|
|
|
+ RunState run_state;
|
|
|
+ JSContext* ctx = impl_->newContext(&run_state);
|
|
|
+ if (!ctx) {
|
|
|
+ error_out = "out of memory";
|
|
|
+ return std::nullopt;
|
|
|
+ }
|
|
|
+
|
|
|
+ // Module evaluation runs top-level code, so it needs the same ceiling as a
|
|
|
+ // run. The default export is never called: reading a descriptor must not
|
|
|
+ // have side effects.
|
|
|
+ impl_->armDeadline(impl_->limits.wall_time_ms);
|
|
|
+
|
|
|
+ std::optional<nlohmann::json> result;
|
|
|
+ std::string error;
|
|
|
+ if (JSModuleDef* module = impl_->evaluateModule(ctx, bytecode, error); module != nullptr) {
|
|
|
+ JSValue ns = JS_GetModuleNamespace(ctx, module);
|
|
|
+ if (JS_IsException(ns)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ } else {
|
|
|
+ JSValue value = JS_GetPropertyStr(ctx, ns, export_name.c_str());
|
|
|
+ if (JS_IsException(value)) {
|
|
|
+ error = takeException(ctx);
|
|
|
+ } else {
|
|
|
+ nlohmann::json parsed;
|
|
|
+ if (fromJs(ctx, value, parsed, error)) result = std::move(parsed);
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, value);
|
|
|
+ }
|
|
|
+ JS_FreeValue(ctx, ns);
|
|
|
+ }
|
|
|
+
|
|
|
+ const bool out_of_time = impl_->interrupted() || impl_->expired();
|
|
|
+ impl_->disarmDeadline();
|
|
|
+ if (!result) {
|
|
|
+ error_out = out_of_time ? "wall-time limit exceeded while loading the module"
|
|
|
+ : (error.empty() ? "could not read export '" + export_name + "'"
|
|
|
+ : error);
|
|
|
+ if (!out_of_time && impl_->looksLikeOom(error)) impl_->poisoned = true;
|
|
|
+ }
|
|
|
+
|
|
|
+ impl_->settleAfterRun();
|
|
|
+ JS_FreeContext(ctx);
|
|
|
+ return result;
|
|
|
+}
|
|
|
+
|
|
|
+// ---------------------------------------------------------------------------
|
|
|
+// Pool
|
|
|
+// ---------------------------------------------------------------------------
|
|
|
+
|
|
|
+JsRuntimePool::Lease::Lease(JsRuntimePool* pool, std::unique_ptr<JsRuntime> runtime)
|
|
|
+ : pool_(pool), runtime_(runtime.get()), owned_(std::move(runtime)) {}
|
|
|
+
|
|
|
+JsRuntimePool::Lease::Lease(Lease&& other) noexcept
|
|
|
+ : pool_(other.pool_), runtime_(other.runtime_), owned_(std::move(other.owned_)) {
|
|
|
+ other.pool_ = nullptr;
|
|
|
+ other.runtime_ = nullptr;
|
|
|
+}
|
|
|
+
|
|
|
+JsRuntimePool::Lease& JsRuntimePool::Lease::operator=(Lease&& other) noexcept {
|
|
|
+ if (this != &other) {
|
|
|
+ release();
|
|
|
+ pool_ = other.pool_;
|
|
|
+ runtime_ = other.runtime_;
|
|
|
+ owned_ = std::move(other.owned_);
|
|
|
+ other.pool_ = nullptr;
|
|
|
+ other.runtime_ = nullptr;
|
|
|
+ }
|
|
|
+ return *this;
|
|
|
+}
|
|
|
+
|
|
|
+JsRuntimePool::Lease::~Lease() { release(); }
|
|
|
+
|
|
|
+void JsRuntimePool::Lease::release() {
|
|
|
+ if (pool_ && owned_) pool_->give_back(std::move(owned_));
|
|
|
+ pool_ = nullptr;
|
|
|
+ runtime_ = nullptr;
|
|
|
+ owned_.reset();
|
|
|
+}
|
|
|
+
|
|
|
+JsRuntimePool::JsRuntimePool(size_t size, JsLimits limits, size_t recycle_above_bytes)
|
|
|
+ : target_(size), limits_(limits), recycle_above_bytes_(recycle_above_bytes) {
|
|
|
+ if (recycle_above_bytes_ == 0) recycle_above_bytes_ = limits_.memory_limit_bytes / 2;
|
|
|
+}
|
|
|
+
|
|
|
+JsRuntimePool::~JsRuntimePool() = default;
|
|
|
+
|
|
|
+size_t JsRuntimePool::size() const {
|
|
|
+ std::lock_guard<std::mutex> lock(mutex_);
|
|
|
+ return target_;
|
|
|
+}
|
|
|
+
|
|
|
+size_t JsRuntimePool::idle() const {
|
|
|
+ std::lock_guard<std::mutex> lock(mutex_);
|
|
|
+ return idle_.size();
|
|
|
+}
|
|
|
+
|
|
|
+size_t JsRuntimePool::retired() const {
|
|
|
+ std::lock_guard<std::mutex> lock(mutex_);
|
|
|
+ return retired_;
|
|
|
+}
|
|
|
+
|
|
|
+JsRuntimePool::Lease JsRuntimePool::acquire() {
|
|
|
+ std::unique_lock<std::mutex> lock(mutex_);
|
|
|
+ cv_.wait(lock, [this] { return !idle_.empty() || live_ < target_; });
|
|
|
+
|
|
|
+ std::unique_ptr<JsRuntime> runtime;
|
|
|
+ if (!idle_.empty()) {
|
|
|
+ runtime = std::move(idle_.back());
|
|
|
+ idle_.pop_back();
|
|
|
+ } else {
|
|
|
+ // Runtimes are created on demand, so a pool sized for peak load costs
|
|
|
+ // nothing until that load arrives.
|
|
|
+ runtime = std::make_unique<JsRuntime>(limits_);
|
|
|
+ live_++;
|
|
|
+ }
|
|
|
+ lock.unlock();
|
|
|
+
|
|
|
+ // QuickJS measures stack depth against the stack top it recorded at
|
|
|
+ // creation; a pooled runtime almost always runs on a different thread.
|
|
|
+ runtime->updateStackTop();
|
|
|
+ return Lease(this, std::move(runtime));
|
|
|
+}
|
|
|
+
|
|
|
+void JsRuntimePool::give_back(std::unique_ptr<JsRuntime> runtime) {
|
|
|
+ // Decide outside the lock: a GC on a bloated runtime can take a while, and
|
|
|
+ // nothing else may touch this runtime while its lease is being dropped.
|
|
|
+ bool retire = runtime->poisoned();
|
|
|
+ if (!retire && runtime->mallocBytes() > recycle_above_bytes_) {
|
|
|
+ // Only the figure AFTER a full GC means anything. A finished run
|
|
|
+ // normally leaves its whole realm unreachable but not yet collected,
|
|
|
+ // and dropping a perfectly good runtime over that would defeat pooling.
|
|
|
+ runtime->collectGarbage();
|
|
|
+ retire = runtime->mallocBytes() > recycle_above_bytes_;
|
|
|
+ }
|
|
|
+
|
|
|
+ std::lock_guard<std::mutex> lock(mutex_);
|
|
|
+ if (!retire && live_ > target_) retire = true; // the pool shrank while this was out
|
|
|
+ if (retire) {
|
|
|
+ runtime.reset();
|
|
|
+ live_--;
|
|
|
+ retired_++;
|
|
|
+ } else {
|
|
|
+ idle_.push_back(std::move(runtime));
|
|
|
+ }
|
|
|
+ cv_.notify_one();
|
|
|
+}
|
|
|
+
|
|
|
+void JsRuntimePool::resize(size_t size) {
|
|
|
+ std::lock_guard<std::mutex> lock(mutex_);
|
|
|
+ target_ = size;
|
|
|
+ // Only idle runtimes can go now; a leased one is retired by give_back,
|
|
|
+ // because destroying a runtime another thread is executing in would take
|
|
|
+ // the process down with it.
|
|
|
+ while (live_ > target_ && !idle_.empty()) {
|
|
|
+ idle_.pop_back();
|
|
|
+ live_--;
|
|
|
+ retired_++;
|
|
|
+ }
|
|
|
+ cv_.notify_all();
|
|
|
+}
|
|
|
+
|
|
|
+} // namespace svapi::runner
|