mirror of
https://github.com/penpot/penpot.git
synced 2026-11-26 21:00:32 +00:00
✨ Add a warm JVM for backend tests (#12808)
Keep a test JVM running for fast backend test and evaluation cycles. Expose the commands as MCP developer tools and report nREPL failures, timeouts, and stale sessions reliably. Start the lockout tests with the test configuration and document the warm test workflow. The original changes were authored by Álvaro Tejero Cantero. AI-assisted-by: claude-opus-5-5 AI-assisted-by: gpt-6.1-terra
This commit is contained in:
parent
f3fa38ecf6
commit
a421cf0b60
@ -5,4 +5,4 @@
|
||||
- Cold ingest writes graph provenance only after the base projection and derived transforms finish. Incremental sync consumes persisted file changes from file-topic Pub/Sub, not the console WebSocket. A browser reconnect refreshes the view but does not recover lost graph changes. The dropping buffer and revision gaps do not trigger replay; surface drift and reload from PostgreSQL. A failed batch can leave partial graph state; don't treat it as an atomic PostgreSQL transaction. Keep skipped changes and incomplete revisions visible.
|
||||
- A session belongs to a profile, not a tab. Reload/replacement and unload own cleanup; do not assume TTL eviction. Sync, query and export use the same session lock: a long query blocks sync. Teardown closes the channel and resources, but does not take that lock; account for in-flight operations when changing the lifecycle. The Arrow allocator must outlive the Ladybug connection and database because Ladybug can retain staged Arrow buffers. Close the allocator last, including on failure.
|
||||
- The console can read whole projected files and export their data. Keep routes behind both `:graph` and `/dbg` authorization, and preserve the engine's prepare/bind and read-only gate; text matching is not a substitute. Keep graph loading off the flag-disabled boot path. On a Ladybug or JVM upgrade, check graph-enabled startup, Arrow ingest, binder behavior and sync parity. Versions and JVM flags live in `backend/deps.edn` and the launch scripts.
|
||||
- Verification entry points: `backend-tests.graph-sync-parity-test` compares incremental results to a fresh projection; `backend-tests.graph-binder-gate-test` prepares the actual statement templates. Neither replaces checking changes to session or route wiring. Use the focused backend commands with the assert flag in `mem:backend/testing`.
|
||||
- Verification entry points: `backend-tests.graph-sync-parity-test` compares incremental results to a fresh projection; `backend-tests.graph-binder-gate-test` prepares the actual statement templates. Neither replaces checking changes to session or route wiring. Run them with the warm test JVM or the focused backend commands in `mem:backend/testing`.
|
||||
|
||||
@ -6,6 +6,13 @@
|
||||
- Use the workspace's existing `PENPOT_TEST_*` database and Redis URIs, not CI values copied from logs. Confirm the destination before changing it; see `mem:devenv/core`. Test databases can have newer migrations, but never drop or recreate one without explicit permission.
|
||||
- Redirect test output to a file before inspecting or filtering it. For coverage, `clojure -M:dev:test:coverage` instruments all `app.*` namespaces even on focused runs; it is slower and produces reflection warnings. Output in `target/coverage/` includes lcov, HTML and EMMA form counts; use normal tests for routine checks.
|
||||
|
||||
## Warm test JVM
|
||||
|
||||
- For the edit-and-rerun loop, run `backend/scripts/test-repl test [ID ...]` inside the devenv container; IDs are namespaces or namespace/var symbols. Without IDs it selects backend test namespaces. From the host, use `docker exec -u penpot -w /home/penpot/penpot/backend penpot-devenv-ws0-main scripts/test-repl test backend-tests.my-ns-test` (use the matching container for other workspaces). MCP exposes `clj_test` and `clj_eval`.
|
||||
- The script starts an nREPL JVM on port 6067 by default with `enable-backend-asserts`, reloads changed namespaces and runs `clojure.test` in fixed order. Use `./scripts/ci --test backend` for a cold Kaocha run and CI parity; use Kaocha's `--seed` to replay an order.
|
||||
- `test-repl eval '(form)'` evaluates in the same JVM; `start`, `stop` and `status` manage it. Restart after `deps.edn` changes because the classpath is fixed at startup. Never call `(restart)` or `(restart-all)` in this JVM: they start a dev backend inside it. Reloading a namespace discards manually defined vars in it.
|
||||
- Test and eval calls take a lock per port to protect the shared test database. Exit status is 0 on success, 1 on test, evaluation or timeout failure, and 2 if the JVM cannot start. `PENPOT_TEST_REPL_TIMEOUT` sets the timeout in seconds (default 1800); `PENPOT_TEST_NREPL_PORT` overrides the port.
|
||||
|
||||
## Test system and helpers
|
||||
|
||||
- `backend-tests.helpers` builds the system from `main/system-config` and `main/worker-config`, excluding HTTP, srepl, cron, dispatcher, audit consumer loops and every worker runner. Live runners or consumers race tests that drive jobs or audit passes manually. Keep runner removal by key shape, not a fixed profile list.
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
|
||||
- **Read `mem:testing` first** for test design and output discipline. Common tests are CLJC under `common/test/common_tests/`; cover the relevant JVM and JS runtimes. JVM tests alone cannot prove CLJS-specific state or WASM behavior.
|
||||
- From the repo root, `./scripts/ci common` runs lint, tests and format. From `common/`, use `clojure -M:dev:test` for JVM tests and `pnpm run test:quiet` for JS tests. Both support focused runs, e.g. `--focus common-tests.logic.comp-sync-test`; repeat `--focus` for multiple JVM selections.
|
||||
- The warm backend test JVM's default selector covers backend tests, not common tests; use the common commands for its full suite. See `mem:backend/testing`.
|
||||
- JS tests compile before running. Register new namespaces in `common_tests/runner.cljc`; new vars in registered namespaces need no runner change. Direct `node target/tests/test.js` runs the existing build and does not rebuild after edits.
|
||||
- JVM coverage uses `clojure -M:dev:test:coverage`; it instruments all configured namespaces, even for a focused run, and is slower. Its lcov, HTML and EMMA form counts go under `target/coverage/`; see `tests.edn` for exclusions.
|
||||
- Helpers live under `common/src/app/common/test_helpers/`. Tests using label-to-UUID helpers need `(t/use-fixtures :each thi/test-fixture)` to reset labels between tests. Inspect the builders there rather than recreating common file, component or variant setup.
|
||||
|
||||
@ -50,6 +50,7 @@ This is a monorepo. Principles that apply to one module do *not* generally apply
|
||||
- `scripts/clean-node-modules` — Remove stale `node_modules` from all pnpm workspaces (root, modules, member packages). Keeps the shared pnpm store at `<repo>/.pnpm-store` unless `--store`; ignores `external/` and `.opencode/`. Usage and reinstall steps: `mem:workflow/updating-pnpm`.
|
||||
- `scripts/setup-opencode` — Install the opencode CLI in-container as a global pnpm package in `$PNPM_HOME`. Not part of the devenv image; see `mem:devenv/core`.
|
||||
- `scripts/ci` — Per-module lint, tests and format checks. See `mem:scripts/ci` for flags, logs and the backend assert flag.
|
||||
- `backend/scripts/test-repl` — Warm backend test JVM for the edit-and-rerun loop; see `mem:backend/testing` for commands and constraints.
|
||||
|
||||
# Dependency graph
|
||||
|
||||
|
||||
@ -3,6 +3,7 @@
|
||||
- From the repo root, use `./scripts/ci MODULE...` for the selected modules' lint, tests and format check. Build is opt-in. Run `./scripts/ci --help` for flags, modules and commands; `--dry-run` previews them without executing. For test design and output discipline, read `mem:testing`.
|
||||
- Pass every changed module. A `common` change can affect frontend, backend, exporter and library; select affected consumers too. Backend lint includes common sources but its format task does not check common, so include `common` explicitly.
|
||||
- The script appends `enable-backend-asserts` to `PENPOT_FLAGS`. Backend assertions are selected when code loads; running tests without the flag can compile them out. See `mem:backend/testing`.
|
||||
- For the backend edit-and-rerun loop use the warm test JVM; `./scripts/ci --test backend` runs cold Kaocha for CI parity and replaying a CI order. See `mem:backend/testing`.
|
||||
- The library test task builds its bundle before running tests, like GitHub CI. Direct `pnpm run test` does not rebuild it; see `mem:library/core`. `--fix library` uses the package's `fmt` script.
|
||||
- `--build` uses module build commands but does not run by default or package deployable bundles. It avoids some cache-clearing wrappers; consult the command in `scripts/ci` rather than assuming every module's build has identical behavior. Native WASM build scripts serialize through a lock, but manual Cargo commands do not; see `mem:render-wasm/core`.
|
||||
- `mcp` and `media-processor` have no lint task and are reported as skipped. The exporter test task supplies a fallback test secret when absent. `scripts/test_ci.py` tests orchestrator wiring and dry runs, not the module builds themselves.
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
# nREPL eval
|
||||
|
||||
- `scripts/nrepl-eval.mjs` connects to an existing nREPL; use `--help` for options. `--backend` and `--frontend` select fixed ports and override `--port`; they cannot be combined. For browser runtime selection and live CLJS inspection see `mem:frontend/cljs-repl`.
|
||||
- Session IDs are stored under `os.tmpdir()` by host and port, so calls to the same address reuse definitions and namespace state. `--reset-session` removes the locally stored ID before cloning a new session; it does not close the previous server session. Do not assume a session is private to the current shell.
|
||||
- Inspect the evaluation response, not just the process exit code: the script prints `err` and status messages but does not itself turn every evaluation error response into a nonzero exit. `--last-error` evaluates `*e` in the selected session. Connection and timeout failures do exit nonzero.
|
||||
- Session IDs are stored under `os.tmpdir()` by host and port, so calls to the same address reuse definitions and namespace state. `--reset-session` removes the locally stored ID before cloning a new session; it does not close the previous server session. Do not assume a session is private to the current shell. An `unknown-session` response triggers a fresh session and one retry.
|
||||
- Evaluation errors, connection failures and timeouts exit nonzero. On timeout the client sends an interrupt for the running evaluation; `--last-error` evaluates `*e` in the selected session.
|
||||
- To call a private JVM Clojure var, use its fully qualified var quote, e.g. `(#'my.namespace/private-fn args)`. For changed namespaces, use `require` with `:reload` when appropriate. Do not start another server merely to evaluate code against an existing one.
|
||||
- The backend test JVM uses port 6067 by default. Prefer `backend/scripts/test-repl test` or `eval` for its startup and lock; use the raw port for other evaluations. Never call `(restart)` or `(restart-all)` there. See `mem:backend/testing`.
|
||||
|
||||
@ -16,3 +16,4 @@ Every behavior change needs a test. Read the affected modules' testing guidance
|
||||
- Never pipe test output directly to filters. Redirect it to a file first, inspect the full result and exit status, then search the file if needed. Use focused runs to narrow scope, not output filters to hide failures.
|
||||
- Run the affected modules' tests, lint and format checks; use `mem:scripts/ci` for the local CI entry point. A focused test does not replace the required module checks. Register new test namespaces where the module's runner requires it.
|
||||
- For backend direct and focused JVM runs, preserve existing `PENPOT_FLAGS` and append `enable-backend-asserts` before the process starts; otherwise assertions can compile out. Prefer `./scripts/ci backend` for the full checks.
|
||||
- For backend edit-and-rerun cycles use the warm test JVM; use cold Kaocha through `scripts/ci` for CI parity. Its default selector does not cover the common suite. See `mem:backend/testing`.
|
||||
|
||||
@ -86,10 +86,17 @@
|
||||
|
||||
;; --- Development Stuff
|
||||
|
||||
(def ^:private all-tests #"^backend-tests.*-test$")
|
||||
|
||||
(defn- run-tests
|
||||
([] (run-tests #"^backend-tests.*-test$"))
|
||||
"Reload the changed namespaces, then run the tests `o` names: a regex
|
||||
over namespace names, a namespace symbol, or a var symbol. Returns
|
||||
the `clojure.test` counters, and throws when the reload fails."
|
||||
([] (run-tests all-tests))
|
||||
([o]
|
||||
(repl/refresh)
|
||||
(let [result (repl/refresh)]
|
||||
(when (instance? Throwable result)
|
||||
(throw result)))
|
||||
(cond
|
||||
(instance? java.util.regex.Pattern o)
|
||||
(test/run-all-tests o)
|
||||
@ -97,9 +104,25 @@
|
||||
(symbol? o)
|
||||
(if-let [sns (namespace o)]
|
||||
(do (require (symbol sns))
|
||||
(test/test-vars [(resolve o)]))
|
||||
(binding [test/*report-counters* (ref test/*initial-report-counters*)]
|
||||
(test/test-vars [(resolve o)])
|
||||
@test/*report-counters*))
|
||||
(test/test-ns o)))))
|
||||
|
||||
(defn run-tests!
|
||||
"Run `run-tests` on each target in turn, or on every backend test
|
||||
when there is none, and throw when a test fails or errors. A caller
|
||||
over nREPL, such as `scripts/test-repl`, then gets a non-zero exit."
|
||||
[& targets]
|
||||
(let [summary (->> (or (seq targets) [all-tests])
|
||||
(mapv #(select-keys (run-tests %) [:test :pass :fail :error]))
|
||||
(apply merge-with +))]
|
||||
(when (pos? (+ (:fail summary 0) (:error summary 0)))
|
||||
(throw (ex-info (format "%d failures, %d errors in %d tests"
|
||||
(:fail summary 0) (:error summary 0) (:test summary 0))
|
||||
summary)))
|
||||
summary))
|
||||
|
||||
(defn- start
|
||||
[]
|
||||
(try
|
||||
|
||||
124
backend/scripts/test-repl
Executable file
124
backend/scripts/test-repl
Executable file
@ -0,0 +1,124 @@
|
||||
#!/usr/bin/env bash
|
||||
# A warm JVM for the backend tests: an nREPL server on the test
|
||||
# classpath, with the flags CI uses. Meant for the devenv container.
|
||||
#
|
||||
# test-repl test [ID ...] run tests (all backend tests without ID);
|
||||
# ID is a namespace or a namespace/var
|
||||
# test-repl eval [CODE] evaluate CODE (or stdin) in the test JVM
|
||||
# test-repl start|stop|status
|
||||
#
|
||||
# `test` and `eval` start the JVM when nothing listens on the port, and
|
||||
# take turns through a lock, because they share one test database.
|
||||
# Exit status: 0 on success, 1 on failing tests, an evaluation error or
|
||||
# a timeout, 2 when the JVM cannot start.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
|
||||
BACKEND_DIR=$(dirname "$SCRIPT_DIR")
|
||||
ROOT_DIR=$(dirname "$BACKEND_DIR")
|
||||
|
||||
PORT=${PENPOT_TEST_NREPL_PORT:-6067}
|
||||
TIMEOUT=${PENPOT_TEST_REPL_TIMEOUT:-1800}
|
||||
LOG=/tmp/penpot-test-repl-$PORT.log
|
||||
LOCK=/tmp/penpot-test-repl-$PORT.lock
|
||||
|
||||
listening() {
|
||||
(exec 3<>"/dev/tcp/127.0.0.1/$PORT") 2>/dev/null
|
||||
}
|
||||
|
||||
jvm_pids() {
|
||||
pgrep -f "nrepl.cmdline --bind 127.0.0.1 --port $PORT" || true
|
||||
}
|
||||
|
||||
nrepl_eval() {
|
||||
if [ ! -d "$ROOT_DIR/node_modules/nrepl-client" ]; then
|
||||
(cd "$ROOT_DIR" && pnpm install --frozen-lockfile >&2)
|
||||
fi
|
||||
node "$ROOT_DIR/scripts/nrepl-eval.mjs" -p "$PORT" -t "$((TIMEOUT * 1000))" "$@"
|
||||
}
|
||||
|
||||
start_jvm() {
|
||||
listening && return 0
|
||||
echo "[test-repl] starting the test JVM on port $PORT (log: $LOG)" >&2
|
||||
# The JVM must not inherit the lock descriptor, or it keeps the lock.
|
||||
(exec 9>&-
|
||||
cd "$BACKEND_DIR"
|
||||
PENPOT_FLAGS="enable-backend-asserts" nohup clojure \
|
||||
-J-Dlog4j2.configurationFile=log4j2-devenv-repl.xml \
|
||||
-M:dev -m nrepl.cmdline --bind 127.0.0.1 --port "$PORT" \
|
||||
>"$LOG" 2>&1 &)
|
||||
for _ in $(seq 600); do
|
||||
listening && break
|
||||
sleep 0.5
|
||||
done
|
||||
if ! listening; then
|
||||
echo "[test-repl] the test JVM did not start; last lines of $LOG:" >&2
|
||||
tail -20 "$LOG" >&2
|
||||
exit 2
|
||||
fi
|
||||
# Load every namespace now, so the first test run pays only for itself.
|
||||
# The list of reloaded namespaces is noise unless the load fails.
|
||||
local out
|
||||
if ! out=$(nrepl_eval "(let [r (clojure.tools.namespace.repl/refresh)] (when (instance? Throwable r) (throw r)) r)" 2>&1); then
|
||||
echo "$out" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
with_lock() {
|
||||
exec 9>"$LOCK"
|
||||
if ! flock -n 9; then
|
||||
echo "[test-repl] waiting for another run to finish" >&2
|
||||
flock 9
|
||||
fi
|
||||
"$@"
|
||||
}
|
||||
|
||||
run_tests() {
|
||||
local targets=""
|
||||
for id in "$@"; do
|
||||
if [[ ! "$id" =~ ^[A-Za-z0-9.*+!?_/-]+$ ]]; then
|
||||
echo "[test-repl] not a namespace or var: $id" >&2
|
||||
exit 1
|
||||
fi
|
||||
targets+=" '$id"
|
||||
done
|
||||
start_jvm
|
||||
nrepl_eval "(user/run-tests!$targets)"
|
||||
}
|
||||
|
||||
eval_code() {
|
||||
start_jvm
|
||||
nrepl_eval "$@"
|
||||
}
|
||||
|
||||
case "${1:-}" in
|
||||
test)
|
||||
shift
|
||||
with_lock run_tests "$@"
|
||||
;;
|
||||
eval)
|
||||
shift
|
||||
with_lock eval_code "$@"
|
||||
;;
|
||||
start)
|
||||
with_lock start_jvm
|
||||
;;
|
||||
stop)
|
||||
pids=$(jvm_pids)
|
||||
if [ -n "$pids" ]; then kill $pids; fi
|
||||
;;
|
||||
status)
|
||||
if listening; then
|
||||
echo "running on port $PORT"
|
||||
else
|
||||
echo "not running"
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
*)
|
||||
sed -n '2,13p' "$0" | sed 's/^# \{0,1\}//'
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
@ -13,7 +13,7 @@
|
||||
[backend-tests.helpers :as th]
|
||||
[clojure.test :as t]))
|
||||
|
||||
(t/use-fixtures :once (partial th/init-system))
|
||||
(t/use-fixtures :once th/state-init)
|
||||
(t/use-fixtures :each (partial th/init-config [:enable-account-lockout]))
|
||||
|
||||
(t/deftest record-failed-attempt-returns-nil-when-disabled
|
||||
|
||||
@ -20,6 +20,8 @@ import { CljsReplTool } from "./tools/dev/CljsReplTool";
|
||||
import { ImportPenpotFileTool } from "./tools/dev/ImportPenpotFileTool";
|
||||
import { CljsCompilerOutputTool } from "./tools/dev/CljsCompilerOutputTool";
|
||||
import { CljCheckParentheses } from "./tools/dev/CljCheckParentheses";
|
||||
import { CljTestTool } from "./tools/dev/CljTestTool";
|
||||
import { CljEvalTool } from "./tools/dev/CljEvalTool";
|
||||
import { ReadTaigaIssueTool } from "./tools/dev/ReadTaigaIssueTool";
|
||||
import { NreplClient } from "./NreplClient";
|
||||
import { ReplServer } from "./ReplServer";
|
||||
@ -313,6 +315,8 @@ export class PenpotMcpServer {
|
||||
toolInstances.push(new ImportPenpotFileTool(this, nreplClient));
|
||||
toolInstances.push(new CljsCompilerOutputTool(this, nreplClient));
|
||||
toolInstances.push(new CljCheckParentheses(this));
|
||||
toolInstances.push(new CljTestTool(this));
|
||||
toolInstances.push(new CljEvalTool(this));
|
||||
toolInstances.push(new ReadTaigaIssueTool(this));
|
||||
}
|
||||
|
||||
|
||||
72
mcp/packages/server/src/tools/dev/CljEvalTool.ts
Normal file
72
mcp/packages/server/src/tools/dev/CljEvalTool.ts
Normal file
@ -0,0 +1,72 @@
|
||||
import { z } from "zod";
|
||||
import { Tool } from "../../Tool";
|
||||
import "reflect-metadata";
|
||||
import type { ToolResponse } from "../../ToolResponse";
|
||||
import { TextResponse } from "../../ToolResponse";
|
||||
import type { PenpotMcpServer } from "../../PenpotMcpServer";
|
||||
import { NREPL_EVAL_SCRIPT, REPO_ROOT, ScriptRunner, TEST_REPL_SCRIPT } from "./runScript";
|
||||
|
||||
/**
|
||||
* Arguments for the CljEvalTool.
|
||||
*/
|
||||
export class CljEvalArgs {
|
||||
static schema = {
|
||||
code: z.string().min(1, "Code cannot be empty").describe("The Clojure code to evaluate."),
|
||||
target: z
|
||||
.enum(["test", "backend"])
|
||||
.optional()
|
||||
.describe(
|
||||
"`test` (default) evaluates in the warm test JVM: test classpath, CI flags, " +
|
||||
"test database. `backend` evaluates in the live dev backend."
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* The Clojure code to evaluate.
|
||||
*/
|
||||
code!: string;
|
||||
|
||||
/**
|
||||
* The JVM to evaluate in: `test` (default) or `backend`.
|
||||
*/
|
||||
target?: "test" | "backend";
|
||||
}
|
||||
|
||||
/**
|
||||
* Evaluates Clojure code in a warm backend JVM.
|
||||
*
|
||||
* The tool shells out to the scripts that own the JVMs and reports the exit
|
||||
* status with the captured output. It keeps no connection of its own.
|
||||
*/
|
||||
export class CljEvalTool extends Tool<CljEvalArgs> {
|
||||
private readonly runner = new ScriptRunner(REPO_ROOT);
|
||||
|
||||
/**
|
||||
* @param mcpServer - the MCP server instance
|
||||
*/
|
||||
constructor(mcpServer: PenpotMcpServer) {
|
||||
super(mcpServer, CljEvalArgs.schema);
|
||||
}
|
||||
|
||||
public getToolName(): string {
|
||||
return "clj_eval";
|
||||
}
|
||||
|
||||
public getToolDescription(): string {
|
||||
return (
|
||||
"Evaluates Clojure code in a warm backend JVM. `test` (default) uses the test JVM " +
|
||||
"(test classpath, CI flags, test database); `backend` uses the live dev backend. " +
|
||||
"Never call `(user/restart-all)`: the client gets no reply. Do not rely on defs " +
|
||||
"surviving a reload."
|
||||
);
|
||||
}
|
||||
|
||||
protected async executeCore(args: CljEvalArgs): Promise<ToolResponse> {
|
||||
const result =
|
||||
(args.target ?? "test") === "backend"
|
||||
? await this.runner.run(process.execPath, [NREPL_EVAL_SCRIPT, "--backend"], args.code)
|
||||
: await this.runner.run(TEST_REPL_SCRIPT, ["eval"], args.code);
|
||||
|
||||
return new TextResponse(this.runner.format(result, { success: "OK", failure: "ERROR" }));
|
||||
}
|
||||
}
|
||||
63
mcp/packages/server/src/tools/dev/CljTestTool.ts
Normal file
63
mcp/packages/server/src/tools/dev/CljTestTool.ts
Normal file
@ -0,0 +1,63 @@
|
||||
import { z } from "zod";
|
||||
import { Tool } from "../../Tool";
|
||||
import "reflect-metadata";
|
||||
import type { ToolResponse } from "../../ToolResponse";
|
||||
import { TextResponse } from "../../ToolResponse";
|
||||
import type { PenpotMcpServer } from "../../PenpotMcpServer";
|
||||
import { REPO_ROOT, ScriptRunner, TEST_REPL_SCRIPT } from "./runScript";
|
||||
|
||||
/**
|
||||
* Arguments for the CljTestTool.
|
||||
*/
|
||||
export class CljTestArgs {
|
||||
static schema = {
|
||||
ids: z
|
||||
.array(z.string().min(1))
|
||||
.optional()
|
||||
.describe(
|
||||
"Namespace or namespace/var symbols, e.g. backend-tests.db-test or " +
|
||||
"backend-tests.db-test/some-test. Omit to run the whole backend suite."
|
||||
),
|
||||
};
|
||||
|
||||
/**
|
||||
* Test targets: namespaces or namespace/var symbols; empty runs the whole suite.
|
||||
*/
|
||||
ids?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs backend tests in the warm test JVM.
|
||||
*
|
||||
* The tool shells out to `backend/scripts/test-repl` and reports its exit status
|
||||
* with the captured output. It keeps no JVM of its own.
|
||||
*/
|
||||
export class CljTestTool extends Tool<CljTestArgs> {
|
||||
private readonly runner = new ScriptRunner(REPO_ROOT);
|
||||
|
||||
/**
|
||||
* @param mcpServer - the MCP server instance
|
||||
*/
|
||||
constructor(mcpServer: PenpotMcpServer) {
|
||||
super(mcpServer, CljTestArgs.schema);
|
||||
}
|
||||
|
||||
public getToolName(): string {
|
||||
return "clj_test";
|
||||
}
|
||||
|
||||
public getToolDescription(): string {
|
||||
return (
|
||||
"Runs backend tests in the warm test JVM, reloading changed namespaces first. " +
|
||||
"Use this instead of `clojure -M:dev:test` for the edit-and-rerun loop: runs take turns " +
|
||||
"on the shared test database. For CI parity (random order, seed replay) use " +
|
||||
"`scripts/ci backend --test`. Without ids it runs the whole backend suite."
|
||||
);
|
||||
}
|
||||
|
||||
protected async executeCore(args: CljTestArgs): Promise<ToolResponse> {
|
||||
const result = await this.runner.run(TEST_REPL_SCRIPT, ["test", ...(args.ids ?? [])]);
|
||||
|
||||
return new TextResponse(this.runner.format(result, { success: "PASS", failure: "FAIL" }));
|
||||
}
|
||||
}
|
||||
48
mcp/packages/server/src/tools/dev/runScript.test.ts
Normal file
48
mcp/packages/server/src/tools/dev/runScript.test.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { ScriptRunner, truncateMiddle } from "./runScript";
|
||||
|
||||
const LABELS = { success: "PASS", failure: "FAIL" };
|
||||
|
||||
test("output within the limit passes through untouched", () => {
|
||||
const text = "1 tests, 1 assertions, 0 failures";
|
||||
|
||||
assert.equal(truncateMiddle(text, ScriptRunner.MAX_OUTPUT_CHARS), text);
|
||||
});
|
||||
|
||||
test("long output keeps its head and tail and names the omitted count", () => {
|
||||
const head = "H".repeat(15_000);
|
||||
const tail = "T".repeat(15_000);
|
||||
|
||||
const result = truncateMiddle(head + tail, ScriptRunner.MAX_OUTPUT_CHARS);
|
||||
|
||||
assert.equal(result.length, ScriptRunner.MAX_OUTPUT_CHARS);
|
||||
assert.ok(result.startsWith(head.slice(0, 1_000)));
|
||||
assert.ok(result.endsWith(tail.slice(-1_000)));
|
||||
assert.match(result, /10000 characters omitted/);
|
||||
});
|
||||
|
||||
test("a failure keeps its summary tail inside the limit", () => {
|
||||
const result = new ScriptRunner("/tmp").format(
|
||||
{
|
||||
exitCode: 1,
|
||||
stdout: "x".repeat(40_000) + "\nFAIL in (some-test)\n1 tests, 0 assertions, 1 failures",
|
||||
stderr: "",
|
||||
},
|
||||
LABELS
|
||||
);
|
||||
|
||||
assert.ok(result.startsWith("FAIL (exit 1)\n"));
|
||||
assert.ok(result.endsWith("1 tests, 0 assertions, 1 failures"));
|
||||
assert.ok(result.length < ScriptRunner.MAX_OUTPUT_CHARS + 20);
|
||||
});
|
||||
|
||||
test("format puts the status first and appends stderr after stdout", () => {
|
||||
const runner = new ScriptRunner("/tmp");
|
||||
|
||||
assert.equal(runner.format({ exitCode: 0, stdout: "nil", stderr: "" }, LABELS), "PASS\nnil");
|
||||
assert.equal(
|
||||
runner.format({ exitCode: 1, stdout: "", stderr: "[test-repl] boom" }, LABELS),
|
||||
"FAIL (exit 1)\n[test-repl] boom"
|
||||
);
|
||||
});
|
||||
137
mcp/packages/server/src/tools/dev/runScript.ts
Normal file
137
mcp/packages/server/src/tools/dev/runScript.ts
Normal file
@ -0,0 +1,137 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import path from "node:path";
|
||||
|
||||
/**
|
||||
* Repository root, derived from the server package root.
|
||||
*
|
||||
* Assumes the process cwd is the server package root, the same assumption
|
||||
* `ConfigurationLoader` and `ImportPenpotFileTool` make.
|
||||
*/
|
||||
export const REPO_ROOT = path.resolve("../../..");
|
||||
|
||||
/** The warm test JVM wrapper: `test [ID ...]`, `eval [CODE]`, `start`, `stop`, `status`. */
|
||||
export const TEST_REPL_SCRIPT = path.join(REPO_ROOT, "backend", "scripts", "test-repl");
|
||||
|
||||
/** The nREPL client used for one-off evaluations; `--backend` targets the live dev backend. */
|
||||
export const NREPL_EVAL_SCRIPT = path.join(REPO_ROOT, "scripts", "nrepl-eval.mjs");
|
||||
|
||||
/**
|
||||
* Result of a script invocation.
|
||||
*/
|
||||
export interface ScriptResult {
|
||||
/** Exit status, or `null` when a signal killed the process. */
|
||||
exitCode: number | null;
|
||||
|
||||
/** Everything the script wrote to stdout. */
|
||||
stdout: string;
|
||||
|
||||
/** Everything the script wrote to stderr. */
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The first-line labels of a formatted script response.
|
||||
*/
|
||||
export interface ScriptStatusLabels {
|
||||
/** Label for exit status 0. */
|
||||
success: string;
|
||||
|
||||
/** Label for any other exit status; the status follows in parentheses. */
|
||||
failure: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a script in the repository root and formats its result.
|
||||
*
|
||||
* The runner adds no timeout of its own: the scripts it calls bound themselves.
|
||||
*/
|
||||
export class ScriptRunner {
|
||||
/** Upper bound on a formatted response body; longer output keeps its head and tail. */
|
||||
static readonly MAX_OUTPUT_CHARS = 20_000;
|
||||
|
||||
/**
|
||||
* @param repoRoot - the repository root used as the working directory of every script
|
||||
*/
|
||||
constructor(private readonly repoRoot: string = REPO_ROOT) {}
|
||||
|
||||
/**
|
||||
* Runs `command` with `args` without a shell, feeding `stdin` to the process.
|
||||
*
|
||||
* @param command - the executable to run
|
||||
* @param args - its arguments, passed verbatim
|
||||
* @param stdin - text written to the process stdin before it is closed
|
||||
* @returns the exit status and the captured output
|
||||
*/
|
||||
public run(command: string, args: string[], stdin?: string): Promise<ScriptResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const child = spawn(command, args, { cwd: this.repoRoot, shell: false });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
stderr += chunk;
|
||||
});
|
||||
child.on("error", reject);
|
||||
child.on("close", (exitCode) => {
|
||||
resolve({ exitCode, stdout, stderr });
|
||||
});
|
||||
|
||||
// close stdin unconditionally, or a script that reads it waits forever
|
||||
child.stdin.end(stdin ?? "");
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a result as a status line followed by the captured output.
|
||||
*
|
||||
* @param result - the script result to format
|
||||
* @param labels - the first-line labels for success and failure
|
||||
* @returns the response text
|
||||
*/
|
||||
public format(result: ScriptResult, labels: ScriptStatusLabels): string {
|
||||
const status = result.exitCode === 0 ? labels.success : `${labels.failure} (exit ${result.exitCode ?? "none"})`;
|
||||
const body = truncateMiddle(joinOutput(result), ScriptRunner.MAX_OUTPUT_CHARS);
|
||||
|
||||
return body.length > 0 ? `${status}\n${body}` : status;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Joins stdout and stderr into one body, keeping their order of appearance.
|
||||
*/
|
||||
function joinOutput(result: ScriptResult): string {
|
||||
return [result.stdout, result.stderr]
|
||||
.map((part) => part.trimEnd())
|
||||
.filter((part) => part.length > 0)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortens `text` to at most `limit` characters, keeping its head and tail.
|
||||
*
|
||||
* Failures print last in clojure.test summaries and the report header first,
|
||||
* so both ends carry the information worth keeping.
|
||||
*
|
||||
* @param text - the text to shorten
|
||||
* @param limit - the maximum length of the returned text
|
||||
* @returns the text unchanged when it fits, otherwise head, omission marker, and tail
|
||||
*/
|
||||
export function truncateMiddle(text: string, limit: number): string {
|
||||
if (text.length <= limit) {
|
||||
return text;
|
||||
}
|
||||
|
||||
const marker = `\n\n[... ${text.length - limit} characters omitted ...]\n\n`;
|
||||
const budget = Math.max(0, limit - marker.length);
|
||||
const headLength = Math.ceil(budget / 2);
|
||||
const tailLength = budget - headLength;
|
||||
const head = text.slice(0, headLength);
|
||||
const tail = tailLength > 0 ? text.slice(text.length - tailLength) : "";
|
||||
|
||||
return head + marker + tail;
|
||||
}
|
||||
@ -1,6 +1,7 @@
|
||||
#!/usr/bin/env node
|
||||
import nreplClient from "nrepl-client";
|
||||
import { readFileSync, writeFileSync, existsSync, unlinkSync } from "fs";
|
||||
import { randomUUID } from "crypto";
|
||||
import path from "path";
|
||||
import os from "os";
|
||||
|
||||
@ -51,9 +52,15 @@ function nreplSend(con, msg) {
|
||||
});
|
||||
}
|
||||
|
||||
// Grace period for the server to acknowledge an interrupt after a timeout.
|
||||
const INTERRUPT_GRACE = 2000;
|
||||
|
||||
function nreplEval({ host, port, code, sessionId, timeout = DEFAULT_TIMEOUT }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const con = nreplClient.connect({ host, port });
|
||||
const evalId = randomUUID();
|
||||
let sid = sessionId;
|
||||
let evaluating = false;
|
||||
let finished = false;
|
||||
|
||||
const finish = (err, result) => {
|
||||
@ -65,8 +72,16 @@ function nreplEval({ host, port, code, sessionId, timeout = DEFAULT_TIMEOUT }) {
|
||||
else resolve(result);
|
||||
};
|
||||
|
||||
// Closing the connection does not stop the evaluation on the server, so
|
||||
// interrupt it first; return as soon as the interrupt is acknowledged.
|
||||
const timer = setTimeout(() => {
|
||||
finish(new Error(`nREPL eval timed out after ${timeout}ms`));
|
||||
const err = new Error(`nREPL eval timed out after ${timeout}ms`);
|
||||
if (!evaluating) return finish(err);
|
||||
setTimeout(() => finish(err), INTERRUPT_GRACE);
|
||||
con.send({ op: "interrupt", session: sid, "interrupt-id": evalId }, () => {
|
||||
err.message += " (interrupted)";
|
||||
finish(err);
|
||||
});
|
||||
}, timeout);
|
||||
|
||||
con.on("error", (err) => {
|
||||
@ -75,8 +90,6 @@ function nreplEval({ host, port, code, sessionId, timeout = DEFAULT_TIMEOUT }) {
|
||||
|
||||
con.once("connect", async () => {
|
||||
try {
|
||||
let sid = sessionId;
|
||||
|
||||
if (!sid) {
|
||||
const msgs = await nreplSend(con, { op: "clone" });
|
||||
const m = msgs.find((m) => m["new-session"]);
|
||||
@ -84,7 +97,8 @@ function nreplEval({ host, port, code, sessionId, timeout = DEFAULT_TIMEOUT }) {
|
||||
sid = m["new-session"];
|
||||
}
|
||||
|
||||
const messages = await nreplSend(con, { op: "eval", code, session: sid });
|
||||
evaluating = true;
|
||||
const messages = await nreplSend(con, { op: "eval", code, session: sid, id: evalId });
|
||||
finish(null, { messages, sessionId: sid });
|
||||
} catch (err) {
|
||||
finish(err);
|
||||
@ -93,6 +107,15 @@ function nreplEval({ host, port, code, sessionId, timeout = DEFAULT_TIMEOUT }) {
|
||||
});
|
||||
}
|
||||
|
||||
function statusesOf(messages) {
|
||||
return messages.flatMap((m) => m.status || []);
|
||||
}
|
||||
|
||||
// An evaluation failed when it threw or could not be read.
|
||||
function evalFailed(messages) {
|
||||
return messages.some((m) => m.ex) || statusesOf(messages).includes("eval-error");
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Output formatting
|
||||
// ============================================================================
|
||||
@ -116,7 +139,7 @@ function formatEvalMessages(messages) {
|
||||
}
|
||||
}
|
||||
if (!hasContent) {
|
||||
const statuses = messages.map((m) => m.status).filter(Boolean).flat();
|
||||
const statuses = statusesOf(messages);
|
||||
return `Evaluation completed. Status: ${statuses.join(", ") || "done"}`;
|
||||
}
|
||||
return lines.join("\n");
|
||||
@ -193,14 +216,18 @@ function printHelp() {
|
||||
console.log(`Usage: ${bin} [options] [<code>]
|
||||
|
||||
Evaluate Clojure code via a running nREPL server. Session state (defs, in-ns)
|
||||
persists across invocations via a stored session ID.
|
||||
persists across invocations via a stored session ID; a session the server no
|
||||
longer knows (the JVM restarted) is replaced by a fresh one.
|
||||
|
||||
Exits 1 when the evaluation throws or cannot be read, and when it times out,
|
||||
in which case the evaluation is interrupted on the server.
|
||||
|
||||
Options:
|
||||
--backend Connect to backend nREPL on port 6064 (default)
|
||||
--frontend Connect to frontend nREPL on port 3447
|
||||
-p, --port PORT nREPL port (default: 6064; overridden by --backend/--frontend)
|
||||
-H, --host HOST nREPL host (default: 127.0.0.1)
|
||||
-t, --timeout MILLISECONDS Timeout in milliseconds (default: 120000)
|
||||
-t, --timeout MILLISECONDS Timeout in milliseconds (default: 120000); interrupts the evaluation
|
||||
--reset-session Discard stored session and start fresh
|
||||
-e, --last-error Evaluate *e to retrieve the last exception
|
||||
-h, --help Show this help message
|
||||
@ -262,18 +289,21 @@ async function main() {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const storedSession = readSession(args.host, args.port);
|
||||
const evalArgs = { host: args.host, port: args.port, code, timeout: args.timeout };
|
||||
let result = await nreplEval({ ...evalArgs, sessionId: readSession(args.host, args.port) });
|
||||
|
||||
const { messages, sessionId } = await nreplEval({
|
||||
host: args.host,
|
||||
port: args.port,
|
||||
code,
|
||||
sessionId: storedSession,
|
||||
timeout: args.timeout,
|
||||
});
|
||||
// The stored session dies with the JVM: start a fresh one instead of
|
||||
// failing every later call.
|
||||
if (statusesOf(result.messages).includes("unknown-session")) {
|
||||
deleteSession(args.host, args.port);
|
||||
result = await nreplEval({ ...evalArgs, sessionId: null });
|
||||
}
|
||||
|
||||
writeSession(args.host, args.port, sessionId);
|
||||
console.log(formatEvalMessages(messages));
|
||||
writeSession(args.host, args.port, result.sessionId);
|
||||
console.log(formatEvalMessages(result.messages));
|
||||
if (evalFailed(result.messages)) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user