PEP-314: временная база под root — пользователь для базы создаётся, если его нет (PEPPA_PG_USER); тесты под root в проверках
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 50с
peppa/build build: success за 40с
peppa/bundle bundle: success за 0с
peppa/test test: success за 1656с
peppa-ci / ci (pull_request) Successful in 29m49s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
peppa-bot 2026-11-27 10:45:32 +00:00
parent 004b9f3cca
commit 217d0d44ac
2 changed files with 25 additions and 7 deletions

View File

@ -16,6 +16,8 @@ const TOOLS = join(ROOT, "template/.gitea/peppa-tools.sh");
const TMP = mkdtempSync(join(tmpdir(), "peppa-stack-tools-"));
const ARCH = ({ x64: "amd64", arm64: "arm64" } as Record<string, string>)[process.arch] ?? process.arch;
const SYS_PATH = "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
// Checks run as root: the mock cluster runs as the current user (the real one — as postgres).
const ME = process.getuid?.() === 0 ? "root" : "postgres";
function exe(path: string, body: string) {
writeFileSync(path, `#!/usr/bin/env bash\n${body}\n`);
@ -52,7 +54,7 @@ esac`,
/** `source peppa-tools.sh <args>` in a fresh bash; prints PATH, DATABASE_URL and `command -v go`. */
function source(args: string[], env: Record<string, string>, cwd = TMP) {
const script = `source "${TOOLS}" ${args.join(" ")}; code=$?; echo "CODE=$code"; echo "URL=\${DATABASE_URL:-}"; echo "GO=$(command -v go)"; exit 0`;
const r = spawnSync("bash", ["-c", script], { cwd, encoding: "utf8", env: { HOME: TMP, TMPDIR: TMP, PATH: SYS_PATH, ...env } });
const r = spawnSync("bash", ["-c", script], { cwd, encoding: "utf8", env: { HOME: TMP, TMPDIR: TMP, PATH: SYS_PATH, PEPPA_PG_USER: ME, ...env } });
const line = (k: string) => (r.stdout.match(new RegExp(`^${k}=(.*)$`, "m")) ?? [])[1] ?? "";
return { code: Number(line("CODE")), url: line("URL"), go: line("GO"), err: r.stderr };
}
@ -121,7 +123,7 @@ describe("Временная база для тестов", () => {
assert.equal(second.url, first.url);
assert.equal(readFileSync(join(bin, "calls.log"), "utf8").match(/^initdb /gm)?.length, 1, "no second cluster");
// stop removes the cluster; the next call makes a new one
spawnSync("bash", [TOOLS, "stop"], { env: { PATH: SYS_PATH, TMPDIR: TMP, ...env } });
spawnSync("bash", [TOOLS, "stop"], { env: { PATH: SYS_PATH, TMPDIR: TMP, PEPPA_PG_USER: ME, ...env } });
assert.ok(!existsSync(dir));
});
@ -147,7 +149,7 @@ describe("Временная база для тестов", () => {
test("запуск без source печатает export для eval", () => {
const env = { PEPPA_PG_BINDIR: mockPgBin(), PEPPA_PG_DIR: join(TMP, "pg-4") };
const out = execFileSync("bash", [TOOLS, "postgres"], { encoding: "utf8", env: { PATH: SYS_PATH, TMPDIR: TMP, ...env } });
const out = execFileSync("bash", [TOOLS, "postgres"], { encoding: "utf8", env: { PATH: SYS_PATH, TMPDIR: TMP, PEPPA_PG_USER: ME, ...env } });
assert.match(out, /^export DATABASE_URL=postgres:\/\/app@127\.0\.0\.1:\d+\/app\\\?sslmode=disable$/m);
});
});

View File

@ -10,7 +10,8 @@
# проверок под root пакет postgresql ставится через apt-get). Повторный вызов дешёвый: Go берётся
# из кэша, живая база переиспользуется — команды checks могут звать его каждая сама.
# Настройки: PEPPA_GO_VERSION (без go.mod; по умолчанию 1.27.0), PEPPA_TOOLS_CACHE (кэш),
# PEPPA_PG_DIR (каталог базы), PEPPA_PG_BINDIR (каталог initdb/pg_ctl).
# PEPPA_PG_DIR (каталог базы), PEPPA_PG_BINDIR (каталог initdb/pg_ctl), PEPPA_PG_USER (от кого
# запускать базу под root; по умолчанию postgres — нет такого пользователя, он создаётся).
_peppa_say() { echo "peppa-tools: $*" >&2; }
@ -68,6 +69,19 @@ _peppa_pg_install() {
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends postgresql >/dev/null
}
# Под root initdb не работает: база идёт от PEPPA_PG_USER (postgres) — префикс команды в _peppa_as.
_peppa_pg_as() {
_peppa_as=()
[[ $(id -u) == 0 ]] || return 0
local u="${PEPPA_PG_USER:-postgres}"
[[ "$u" == root ]] && return 0
if ! id -u "$u" >/dev/null 2>&1; then
useradd --system --no-create-home --shell /usr/sbin/nologin "$u" >/dev/null 2>&1 ||
{ _peppa_say "нет пользователя $u для базы, и создать его не удалось"; return 1; }
fi
_peppa_as=(runuser -u "$u" --)
}
_peppa_pg_dir() { printf '%s' "${PEPPA_PG_DIR:-${TMPDIR:-/tmp}/peppa-pg-$(id -u)}"; }
_peppa_postgres() {
@ -78,13 +92,14 @@ _peppa_postgres() {
return 1
}
# initdb не работает от root: в задании проверок база идёт от пользователя postgres.
if [[ $(id -u) == 0 ]]; then as=(runuser -u postgres --); fi
_peppa_pg_as || return 1
as=(${_peppa_as[@]+"${_peppa_as[@]}"})
if [[ -s "$dir/url" ]] && "${as[@]}" "$bin/pg_ctl" -D "$dir/data" status >/dev/null 2>&1; then
url=$(cat "$dir/url")
else
rm -rf "$dir"
mkdir -p "$dir" && chmod 700 "$dir" || return 1
((${#as[@]})) && chown postgres "$dir"
((${#as[@]})) && chown "${as[2]}" "$dir"
if ! "${as[@]}" "$bin/initdb" -D "$dir/data" -U app --auth=trust -E UTF8 --no-locale >"$dir/initdb.log" 2>&1; then
_peppa_say "initdb не удался:"; tail -n 20 "$dir/initdb.log" >&2; return 1
fi
@ -110,7 +125,8 @@ _peppa_stop() {
local bin dir as=()
dir=$(_peppa_pg_dir)
bin=$(_peppa_pg_bindir) || return 0
[[ $(id -u) == 0 ]] && as=(runuser -u postgres --)
_peppa_pg_as || return 1
as=(${_peppa_as[@]+"${_peppa_as[@]}"})
[[ -d "$dir/data" ]] && "${as[@]}" "$bin/pg_ctl" -D "$dir/data" -m fast stop >/dev/null 2>&1
rm -rf "$dir"
}