Replace legacy Go project with Rust Bedrock bootstrap
This commit is contained in:
@@ -1,71 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Explicit remote-runner opt-in: invokes real models using the dedicated CLI login.
|
||||
# 此脚本会编译测试并实际调用模型;只用于明确授权的专用远程 runner,普通检查不自动运行。
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
# 在仓库根目录调用,参数一为已构建 Core/worker 二进制;CLI 安装和专用登录由 runner 运维预置。
|
||||
# 下方开关必须显式列出已验证图片输出能力的后端名,避免把图片输入能力误当作图片生成能力。
|
||||
binary=$(realpath "$1")
|
||||
cli=${FOUNDRY_REAL_CODEX_INSTALL:-/opt/endoleap-infra/codex-cli}
|
||||
login=${FOUNDRY_REAL_CODEX_HOME:-/opt/endoleap-infra/foundry/codex/home}
|
||||
: "${FOUNDRY_CANVAS_IMAGE_MODELS:?Set only backend model names verified for image output}"
|
||||
|
||||
# 检查准备条件,不会自动下载 CLI、创建登录或替换生产服务;真实生成可能消耗模型额度。
|
||||
test -x "$binary"
|
||||
test -s "$login/auth.json"
|
||||
test -s "$login/models_cache.json"
|
||||
|
||||
# 随机命名 worker/数据库和临时 socket 目录,退出时一并清理,不复用生产队列。
|
||||
suffix=$(openssl rand -hex 8)
|
||||
database=foundry-real-db-$suffix
|
||||
worker=foundry-real-worker-$suffix
|
||||
scratch=$(mktemp -d /tmp/foundry-real.XXXXXXXX)
|
||||
cleanup(){ docker rm -f "$worker" "$database" >/dev/null 2>&1 || true; rm -rf "$scratch"; }
|
||||
trap cleanup EXIT
|
||||
install -d -m 700 "$scratch/run"
|
||||
chown 1000:1000 "$scratch/run"
|
||||
|
||||
# 临时数据库不开放端口,trust 只用于本次隔离命名空间;应用角色/迁移随后按真实迁移器安装。
|
||||
docker run -d --name "$database" --network none -e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine >/dev/null
|
||||
for attempt in {1..30}; do if docker exec "$database" pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; then break; fi; sleep 1; done
|
||||
|
||||
# 先安装早期认证基线,创建测试角色,再由迁移器补齐其余 schema 与授权。
|
||||
docker exec -i "$database" psql -X -U postgres -v ON_ERROR_STOP=1 < db/001-auth.sql
|
||||
docker exec "$database" psql -X -U postgres -v ON_ERROR_STOP=1 -c 'CREATE ROLE foundry_fixture LOGIN'
|
||||
python3 deploy/migrate.py --container "$database" --database postgres --role foundry_fixture
|
||||
|
||||
# Only the CLI container sees the login. Core/tests receive the private socket,
|
||||
# never the login, runtime configuration or Docker socket.
|
||||
# 只有 CLI 容器只读读取专用登录和模型缓存,测试容器仅挂 socket,不能访问登录或 Docker socket。
|
||||
# worker 的 bridge 网络用于访问远端模型,数据库仍隔离;CLI 登录只给 worker。
|
||||
# 根文件系统只读,临时 CODEX_HOME 和任务目录走 tmpfs;脚本退出会删除测试容器与共享 socket 目录。
|
||||
docker run -d --name "$worker" --init --network bridge --user 1000:1000 \
|
||||
--cap-drop ALL --security-opt no-new-privileges --read-only --pids-limit 128 --memory 1g \
|
||||
--tmpfs /tmp:rw,nosuid,nodev,size=128m --tmpfs /work:ro,nosuid,nodev \
|
||||
--tmpfs /home/node/.codex:rw,nosuid,nodev,size=32m,uid=1000,gid=1000 --workdir /work \
|
||||
-e "FOUNDRY_CANVAS_IMAGE_MODELS=$FOUNDRY_CANVAS_IMAGE_MODELS" \
|
||||
--mount "type=bind,source=$binary,target=/opt/bedrock,readonly" \
|
||||
--mount "type=bind,source=$cli,target=/opt/codex,readonly" \
|
||||
--mount "type=bind,source=$login/auth.json,target=/home/node/.codex/auth.json,readonly" \
|
||||
--mount "type=bind,source=$login/models_cache.json,target=/home/node/.codex/models_cache.json,readonly" \
|
||||
--mount "type=bind,source=$scratch/run,target=/run/foundry-codex" \
|
||||
--mount type=bind,source=/etc/ssl/certs/ca-certificates.crt,target=/etc/ssl/certs/ca-certificates.crt,readonly \
|
||||
node:24-bookworm-slim /opt/bedrock codex-worker >/dev/null
|
||||
for attempt in {1..30}; do if [[ -S "$scratch/run/worker.sock" ]]; then break; fi; sleep 1; done
|
||||
test -S "$scratch/run/worker.sock"
|
||||
|
||||
# 先等私有 socket 出现,再在 runner 编译并仅运行真实 worker 专项用例;与普通单元测试开关分离。
|
||||
CGO_ENABLED=0 go test -mod=readonly -c -o bin/platform-real-tests ./internal/platform
|
||||
|
||||
# 测试可执行文件以普通 uid 运行,只共享数据库网络和 worker socket;没有 Docker socket 和 CLI 登录。
|
||||
# -test.run 仅选真实 worker 专项,不能把本脚本的成功当作已运行所有平台测试。
|
||||
docker run --rm --network "container:$database" --user 1000:1000 \
|
||||
--read-only --cap-drop ALL --security-opt no-new-privileges \
|
||||
--tmpfs /tmp:rw,nosuid,nodev,noexec,size=16m,mode=1777 \
|
||||
--mount "type=bind,source=$(pwd)/bin/platform-real-tests,target=/opt/integration-tests,readonly" \
|
||||
--mount "type=bind,source=$scratch/run,target=/run/canvas-real,readonly" \
|
||||
-e PLATFORM_TEST_DATABASE_URL=postgres://foundry_fixture@127.0.0.1:5432/postgres?sslmode=disable \
|
||||
-e FOUNDRY_REAL_CODEX_SOCKET=/run/canvas-real/worker.sock \
|
||||
--entrypoint /opt/integration-tests postgres:17-alpine -test.v -test.run '^TestCanvasAIRealWorker$' -test.timeout 6m
|
||||
@@ -1,122 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# 远程 runner 的数据库/集成检查,会编译测试二进制并运行容器;不能在未授权本地环境执行。
|
||||
set -euo pipefail
|
||||
|
||||
# 随机隔离数据库容器不映射宿主端口,EXIT 时销毁;trust 认证只用于该临时网络命名空间。
|
||||
# 在调用前应位于仓库根目录,db/、internal/ 和 bin/ 的相对路径都以该位置解析。
|
||||
# 参数和真实生产配置不参与本次测试,生成随机容器名,避免并行检查互相复用数据库。
|
||||
container=foundry-schema-$(openssl rand -hex 8)
|
||||
cleanup() { docker rm -f "$container" >/dev/null 2>&1 || true; }
|
||||
trap cleanup EXIT
|
||||
|
||||
# No host port or shared network. The database is discarded after this check.
|
||||
docker run -d --name "$container" --network none \
|
||||
-e POSTGRES_HOST_AUTH_METHOD=trust postgres:17-alpine >/dev/null
|
||||
|
||||
# 最多等待约三十秒;循环结束不单独宣告就绪,后续 psql 仍会在数据库不可用时失败。
|
||||
for attempt in {1..30}; do
|
||||
if docker exec "$container" pg_isready -h 127.0.0.1 -U postgres >/dev/null 2>&1; then break; fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
# 通过 docker exec 进入隔离容器执行 psql;ON_ERROR_STOP 保证 SQL 断言失败立即终止脚本。
|
||||
psql() { docker exec -i "$container" psql -X -U postgres -v ON_ERROR_STOP=1; }
|
||||
|
||||
# 先安装最早认证版本并植入有效/过期旧会话,模拟部署前已有用户数据。
|
||||
psql < db/001-auth.sql
|
||||
psql <<'SQL'
|
||||
INSERT INTO project_accounts(project,id,google_subject,email)
|
||||
VALUES ('fixture','00000000-0000-0000-0000-000000000001','existing-google','existing@example.invalid');
|
||||
INSERT INTO project_sessions VALUES
|
||||
('existing-session','fixture','00000000-0000-0000-0000-000000000001',now()+interval '1 hour'),
|
||||
('expired-session','fixture','00000000-0000-0000-0000-000000000001',now()-interval '1 hour');
|
||||
SQL
|
||||
|
||||
# 运行角色只用于隔离测试;迁移器随后为它授予应用权限,用它检查应用而不是始终使用 postgres 超级用户。
|
||||
psql <<'SQLROLE'
|
||||
CREATE ROLE foundry_fixture LOGIN;
|
||||
SQLROLE
|
||||
|
||||
# 连续跑两次真实迁移器,验证旧基线接管和校验和重放,而不是仅验证全新数据库建表。
|
||||
python3 deploy/migrate.py --container "$container" --database postgres --role foundry_fixture
|
||||
python3 deploy/migrate.py --container "$container" --database postgres --role foundry_fixture
|
||||
|
||||
# SQL 断言旧 Google 绑定保留、过期会话不复活、绝对期限添加,再在回滚事务中验证资源与跨项目外键。
|
||||
psql <<'SQL'
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (
|
||||
SELECT 1 FROM project_sessions s JOIN project_accounts a
|
||||
ON (s.project,s.account_id)=(a.project,a.id)
|
||||
JOIN account_identities i ON (i.project,i.account_id)=(a.project,a.id)
|
||||
WHERE s.token_hash='existing-session' AND i.provider='google' AND i.subject='existing-google'
|
||||
) THEN RAISE EXCEPTION 'Existing Google login was lost'; END IF;
|
||||
IF EXISTS (SELECT 1 FROM project_sessions WHERE token_hash='expired-session' AND expires_at>now()) THEN
|
||||
RAISE EXCEPTION 'Migration revived expired session';
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM project_sessions WHERE token_hash='existing-session' AND absolute_expires_at>now()+interval '89 days') THEN
|
||||
RAISE EXCEPTION 'Missing absolute session deadline';
|
||||
END IF;
|
||||
END $$;
|
||||
BEGIN;
|
||||
INSERT INTO project_accounts(project,id,email) VALUES
|
||||
('fixture','00000000-0000-0000-0000-000000000002','email@example.invalid');
|
||||
INSERT INTO email_credentials(project,email,account_id,password_hash) VALUES
|
||||
('fixture','email@example.invalid','00000000-0000-0000-0000-000000000002','fixture-hash');
|
||||
INSERT INTO workspaces(project,id,name,owner_id) VALUES
|
||||
('fixture','00000000-0000-0000-0000-000000000010','Fixture','00000000-0000-0000-0000-000000000001');
|
||||
INSERT INTO workspace_members(project,workspace_id,account_id,role) VALUES
|
||||
('fixture','00000000-0000-0000-0000-000000000010','00000000-0000-0000-0000-000000000001','admin');
|
||||
INSERT INTO materials(project,workspace_id,id,kind,title,created_by) VALUES
|
||||
('fixture','00000000-0000-0000-0000-000000000010','00000000-0000-0000-0000-000000000020','article','Article','00000000-0000-0000-0000-000000000001'),
|
||||
('fixture','00000000-0000-0000-0000-000000000010','00000000-0000-0000-0000-000000000021','board','Board','00000000-0000-0000-0000-000000000001');
|
||||
INSERT INTO board_layouts(project,workspace_id,board_id,material_id,x,y,width,height) VALUES
|
||||
('fixture','00000000-0000-0000-0000-000000000010','00000000-0000-0000-0000-000000000021','00000000-0000-0000-0000-000000000020',0,0,320,200);
|
||||
DO $$
|
||||
BEGIN
|
||||
BEGIN
|
||||
INSERT INTO workspace_members(project,workspace_id,account_id,role) VALUES
|
||||
('other','00000000-0000-0000-0000-000000000010','00000000-0000-0000-0000-000000000001','admin');
|
||||
RAISE EXCEPTION 'Cross-project membership unexpectedly accepted';
|
||||
EXCEPTION WHEN foreign_key_violation THEN NULL;
|
||||
END;
|
||||
END $$;
|
||||
ROLLBACK;
|
||||
SQL
|
||||
printf 'Migration preserved existing logins and enforced project isolation.\n'
|
||||
|
||||
# 安装研究库测试语料及只读角色,随后各 Go 包按各自数据库环境变量运行集成用例。
|
||||
psql < internal/research/testdata/corpus.sql
|
||||
|
||||
# runner 编译 Linux 静态测试程序,随后在同数据库网络空间用最小权限容器运行,源码不挂入测试容器。
|
||||
# go test -c 只生成测试可执行文件;真正运行在后面的容器中,不是重复在 runner 上跑一次测试。
|
||||
# --network container:... 共用临时数据库的网络命名空间,所以测试里的 127.0.0.1 指向该临时数据库。
|
||||
for package in platform auth research; do
|
||||
CGO_ENABLED=0 go test -mod=readonly -c -o "bin/$package-tests" "./internal/$package"
|
||||
docker run --rm --network "container:$container" --user 1000:1000 \
|
||||
--read-only --cap-drop ALL --security-opt no-new-privileges \
|
||||
--tmpfs /tmp:rw,nosuid,nodev,noexec,size=16m,mode=1777 \
|
||||
--mount "type=bind,source=$(pwd)/bin/$package-tests,target=/opt/integration-tests,readonly" \
|
||||
-e PLATFORM_TEST_DATABASE_URL=postgres://foundry_fixture@127.0.0.1:5432/postgres?sslmode=disable \
|
||||
-e RESEARCH_TEST_DATABASE_URL=postgres://foundry_research_fixture@127.0.0.1:5432/postgres?sslmode=disable \
|
||||
--entrypoint /opt/integration-tests postgres:17-alpine -test.v
|
||||
done
|
||||
|
||||
# Run the actual pinned Endoleap runtime against this build's authenticated HTTP
|
||||
# routes and the same disposable database. Only this remote container needs Node.
|
||||
# 可选 pinned Endoleap 客户端需要 Node,额外运行一次真实 HTTP 客户端集成;未提供时跳过该阶段。
|
||||
# HEADLESS_CLIENT_SOURCE 应由 CI 指向固定提交的前端源码;本脚本只验证已有路径,不自行下载最新版。
|
||||
# 这一阶段用真实 HTTP handler 与 headless 客户端验证协议,不能替代生产账号或线上部署验收。
|
||||
if [[ -n "${HEADLESS_CLIENT_SOURCE:-}" ]]; then
|
||||
test -f "$HEADLESS_CLIENT_SOURCE/tests/headless/foundry.integration.mjs"
|
||||
docker run --rm --network "container:$container" --user 1000:1000 \
|
||||
--read-only --cap-drop ALL --security-opt no-new-privileges \
|
||||
--tmpfs /tmp:rw,nosuid,nodev,noexec,size=32m,mode=1777 \
|
||||
--mount "type=bind,source=$(pwd)/bin/platform-tests,target=/opt/integration-tests,readonly" \
|
||||
--mount "type=bind,source=$HEADLESS_CLIENT_SOURCE,target=/opt/headless-client,readonly" \
|
||||
-e PLATFORM_TEST_DATABASE_URL=postgres://foundry_fixture@127.0.0.1:5432/postgres?sslmode=disable \
|
||||
-e FOUNDRY_HEADLESS_SOURCE=/opt/headless-client \
|
||||
--entrypoint /opt/integration-tests node:24-bookworm-slim \
|
||||
-test.v -test.run '^TestHeadlessClientHTTPIntegration$' -test.timeout 3m
|
||||
fi
|
||||
@@ -1,42 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# 远程私有 worker 启动器;使用与 Core 同一二进制的 codex-worker 模式,CLI 和登录目录由运维预先提供。
|
||||
set -euo pipefail
|
||||
|
||||
# 参数一是已经构建好的 Go 程序;realpath 把挂载源固定为绝对路径,Docker 不会替这里编译源码。
|
||||
base=/opt/endoleap-infra
|
||||
dir=$base/foundry/codex
|
||||
binary=$(realpath "$1")
|
||||
|
||||
# 启动前检查可执行文件、专用 CLI 登录和项目授权表;本脚本不执行登录流程,也不生成授权令牌。
|
||||
test -x "$binary"
|
||||
test -s "$dir/home/auth.json"
|
||||
test -s "$dir/grants/projects.json"
|
||||
|
||||
# socket 目录归容器 uid 1000,socket 本身由服务设为 0600;不公布宿主 TCP 端口。
|
||||
install -d -m 700 "$dir/run"
|
||||
chown 1000:1000 "$dir/run"
|
||||
|
||||
# 可选目录声明已验证图片输出后端;没有此名单时不根据图片输入能力推测图片生成能力。
|
||||
canvas_env=()
|
||||
if [[ -s "$dir/canvas.env" ]]; then canvas_env=(--env-file "$dir/canvas.env"); fi
|
||||
|
||||
# The host operator supplies an isolated Codex home and starts a single worker.
|
||||
# The Docker default bridge supplies egress independently of Foundry's network.
|
||||
# 单 worker 使用独立 bridge 出网,根文件系统只读;临时任务写 /tmp,登录目录需允许 CLI 自身状态更新。
|
||||
# CLI/二进制只读挂载,Core 只看到 socket,不共享本登录目录。
|
||||
# 容器参数分工:--init 负责子进程收尾,资源上限限制进程数/内存,cap-drop 与 no-new-privileges 收紧权限。
|
||||
# /tmp 可写用于临时任务,/work 只读且设为工作目录;没有 -p,因此不向宿主发布 worker 的 TCP 端口。
|
||||
# 挂载中 /opt/bedrock 是 Go worker,/opt/codex 是预装 Node CLI;执行 CLI 才是这里需要 Node 环境的原因。
|
||||
# 最后一行的 codex-worker 参数选中 main.go 的 worker 分支,而不是启动普通 Foundry HTTP API。
|
||||
docker run -d --name foundry-codex-worker --restart unless-stopped --init \
|
||||
--network bridge --user 1000:1000 --cap-drop ALL --security-opt no-new-privileges \
|
||||
--read-only --pids-limit 128 --memory 1g --tmpfs /tmp:rw,nosuid,nodev \
|
||||
--tmpfs /work:ro,nosuid,nodev --workdir /work \
|
||||
--mount "type=bind,source=$binary,target=/opt/bedrock,readonly" \
|
||||
--mount "type=bind,source=$base/codex-cli,target=/opt/codex,readonly" \
|
||||
--mount "type=bind,source=$dir/home,target=/home/node/.codex" \
|
||||
--mount "type=bind,source=$dir/run,target=/run/foundry-codex" \
|
||||
--mount "type=bind,source=/etc/ssl/certs/ca-certificates.crt,target=/etc/ssl/certs/ca-certificates.crt,readonly" \
|
||||
"${canvas_env[@]}" \
|
||||
node:24-bookworm-slim /opt/bedrock codex-worker
|
||||
@@ -1,104 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Apply checked migrations atomically from the trusted deployment runner."""
|
||||
|
||||
# 部署 runner 入口:组合所有尚未执行的迁移及授权为单个外层事务,失败整体回滚。
|
||||
# db/*.sql 的校验和覆盖原始注释;历史文件不可仅为加注释而改写,中文对象说明见 docs/database-comments.sql。
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
# 数据库/角色会插入 SQL 标识符,先严格限制为小写标识;container 通过 argv 传给 docker。
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--container", default=os.environ.get("FOUNDRY_POSTGRES_CONTAINER", "foundry-postgres"))
|
||||
parser.add_argument("--database", default="foundry_auth")
|
||||
parser.add_argument("--role", default="foundry")
|
||||
args = parser.parse_args()
|
||||
for value in (args.database, args.role):
|
||||
if not re.fullmatch(r"[a-z_][a-z0-9_]{0,62}", value):
|
||||
raise SystemExit("Invalid deployment database or role")
|
||||
|
||||
# 从本脚本位置定位 db/,避免调用目录影响迁移来源;文件名的排序也是版本执行顺序。
|
||||
# 编号命名需延续现有约定,运行脚本会真正访问数据库,不是生成预览文件。
|
||||
migrations = sorted((Path(__file__).resolve().parent.parent / "db").glob("[0-9]*.sql"))
|
||||
if not migrations:
|
||||
raise SystemExit("No migrations found")
|
||||
|
||||
# psql 遇错立即退出,固定 advisory 事务锁串行化同库部署,lock_timeout 防止无限等锁。
|
||||
script = [
|
||||
"\\set ON_ERROR_STOP on",
|
||||
"BEGIN;",
|
||||
"SET LOCAL lock_timeout='30s';",
|
||||
"SELECT pg_advisory_xact_lock(731920164);",
|
||||
"CREATE TABLE IF NOT EXISTS foundry_schema_migrations "
|
||||
"(name text PRIMARY KEY, checksum text NOT NULL, applied_at timestamptz NOT NULL DEFAULT now());",
|
||||
]
|
||||
|
||||
# 迁移清单记录文件名和原文摘要;tables 收集源码中显式 CREATE TABLE 的对象用于后续 DML 授权。
|
||||
# 这是按受信任 SQL 的既有写法提取,不是通用 SQL 解析器。
|
||||
tables = set()
|
||||
for index, path in enumerate(migrations):
|
||||
source = path.read_text()
|
||||
name = path.name
|
||||
if not re.fullmatch(r"[0-9]+-[a-z0-9-]+\.sql", name):
|
||||
raise SystemExit("Invalid migration name")
|
||||
|
||||
# 原文 SHA-256 与已执行记录逐字匹配,禁止同名历史迁移在部署后被静默修改。
|
||||
checksum = hashlib.sha256(source.encode()).hexdigest()
|
||||
tables.update(re.findall(r"CREATE TABLE ([a-z_]+)", source))
|
||||
|
||||
# The first deployed version predates migration tracking.
|
||||
# 第一批历史部署没有迁移账本:只有四张认证基线表都存在才认领首迁移,避免把部分初始化误判完整。
|
||||
if index == 0:
|
||||
script.extend([
|
||||
"SELECT bool_and(to_regclass('public.' || name) IS NOT NULL) AS baseline FROM "
|
||||
"unnest(ARRAY['project_accounts','oauth_attempts','login_grants','project_sessions']) name \\gset",
|
||||
"\\if :baseline",
|
||||
f"INSERT INTO foundry_schema_migrations(name,checksum) VALUES('{name}','{checksum}') ON CONFLICT DO NOTHING;",
|
||||
"\\endif",
|
||||
])
|
||||
|
||||
# psql 的 applied/valid 变量决定跳过或执行:同名已执行但摘要不同直接退出,不重放修改过的历史 SQL。
|
||||
script.extend([
|
||||
f"SELECT EXISTS(SELECT 1 FROM foundry_schema_migrations WHERE name='{name}') AS applied, "
|
||||
f"EXISTS(SELECT 1 FROM foundry_schema_migrations WHERE name='{name}' AND checksum='{checksum}') AS valid \\gset",
|
||||
"\\if :applied",
|
||||
"\\if :valid",
|
||||
"\\else",
|
||||
"\\echo Migration checksum mismatch",
|
||||
"\\quit 1",
|
||||
"\\endif",
|
||||
"\\else",
|
||||
])
|
||||
|
||||
# 每份源文件显式 BEGIN/COMMIT;去除内层边界后放入外层统一事务,而非逐文件部分提交。
|
||||
source = source.strip()
|
||||
if not source.startswith("BEGIN;") or not source.endswith("COMMIT;"):
|
||||
raise SystemExit("Migration must have explicit transaction boundaries")
|
||||
|
||||
# 剥掉的是各文件最外层 BEGIN/COMMIT,正文保持不变;最终与账本登记和角色授权同一个事务提交。
|
||||
script.append(source[len("BEGIN;"):-len("COMMIT;")])
|
||||
script.extend([
|
||||
f"INSERT INTO foundry_schema_migrations(name,checksum) VALUES('{name}','{checksum}');",
|
||||
"\\endif",
|
||||
])
|
||||
|
||||
# 从受信任源码的 CREATE TABLE 清单补应用 DML 权限;identity 序列另授予使用/读取权限。
|
||||
for table in sorted(tables):
|
||||
script.append(f'GRANT SELECT,INSERT,UPDATE,DELETE ON TABLE "{table}" TO "{args.role}";')
|
||||
script.extend([
|
||||
f'GRANT USAGE,SELECT ON SEQUENCE link_clicks_id_seq TO "{args.role}";',
|
||||
"COMMIT;",
|
||||
])
|
||||
|
||||
# SQL 经标准输入交给容器内 psql,不把数据库密码或整段 SQL 拼成 shell 命令参数。
|
||||
# Docker 在服务器的 PostgreSQL 容器中运行 psql,POSTGRES_USER 由容器环境提供。
|
||||
# check=True 将非零退出码传播为部署失败;迁移脚本自身不会启动/切换 Core 容器。
|
||||
subprocess.run(
|
||||
["docker", "exec", "-i", args.container, "sh", "-c",
|
||||
'exec psql -X -U "${POSTGRES_USER:-postgres}" -d "$1" -v ON_ERROR_STOP=1', "sh", args.database],
|
||||
input=("\n".join(script) + "\n").encode(), check=True,
|
||||
)
|
||||
print("Schema migrations and application grants verified.")
|
||||
@@ -1,222 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# 由 main 部署工作流在远程基础设施主机执行,参数一必须是已构建的 Foundry 二进制。
|
||||
# 本脚本会迁移数据库、替换 worker 并启动候选服务,不能当作本地静态检查执行。
|
||||
# -e 遇未处理失败退出,-u 拒绝未定义变量,pipefail 让管道任一失败可见;umask 限制新建配置文件权限。
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
# 本脚本依赖远程基础设施目录和已存在的 Docker 网络,不负责构建二进制或创建整套基础设施。
|
||||
# origin 是外部 HTTPS 地址,candidate 是切流前的临时容器名,network 供 Core 访问数据库/反向代理。
|
||||
base=/opt/endoleap-infra
|
||||
foundry=$base/foundry
|
||||
origin=https://api.foundry.entroia.com
|
||||
candidate=foundry-core-candidate
|
||||
network=endoleap-dev_default
|
||||
|
||||
# 必需凭据仅从环境传入,拒绝换行以保持容器环境参数边界,日志不打印值。
|
||||
for name in GOOGLE_CLIENT_ID GOOGLE_CLIENT_SECRET; do
|
||||
value=${!name-}
|
||||
if [[ -z "$value" || "$value" == *$'\n'* || "$value" == *$'\r'* ]]; then
|
||||
printf 'Missing or invalid %s\n' "$name" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
# Accept formatted JSON from Actions Variables and never print its contents.
|
||||
# 将 Actions 中可多行排版的 JSON 压为单行;这里只校验映射形状,URL 协议由服务启动继续验证。
|
||||
FOUNDRY_PROJECTS=$(python3 - <<'PYCONFIG'
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
raw = os.environ.get("FOUNDRY_PROJECTS", "")
|
||||
if not raw.strip():
|
||||
sys.exit("FOUNDRY_PROJECTS was not injected from Actions Variables")
|
||||
try:
|
||||
projects = json.loads(raw)
|
||||
except ValueError:
|
||||
sys.exit("FOUNDRY_PROJECTS must be valid JSON")
|
||||
if not isinstance(projects, dict) or not projects or any(
|
||||
not isinstance(callback, str) or not callback.strip()
|
||||
for callback in projects.values()
|
||||
):
|
||||
sys.exit("FOUNDRY_PROJECTS must map project names to callback URLs")
|
||||
print(json.dumps(projects, separators=(",", ":")))
|
||||
PYCONFIG
|
||||
)
|
||||
|
||||
# 上面的 Python 只在子进程中整理 JSON;export 让后续容器从当前进程环境取得规范化结果。
|
||||
export FOUNDRY_PROJECTS
|
||||
|
||||
# database.env 由服务器预置并保存数据库连接信息;这里只检查存在,不能把凭据写入源码或日志。
|
||||
test -s "$foundry/database.env"
|
||||
|
||||
# Go's HTTPS client uses the OS trust store, not Node's bundled roots.
|
||||
# The slim Node runtime has no system CA bundle of its own.
|
||||
ca_bundle=/etc/ssl/certs/ca-certificates.crt
|
||||
test -s "$ca_bundle"
|
||||
docker network inspect "$network" >/dev/null
|
||||
|
||||
# 先运行全事务迁移及角色授权,迁移失败立即终止,不让新服务在半升级 schema 上启动。
|
||||
python3 "$(dirname "$0")/migrate.py"
|
||||
|
||||
# 每次发布使用独立二进制目录供只读挂载;本脚本不清除旧 release 目录。
|
||||
release=$(mktemp -d "$foundry/release.XXXXXXXX")
|
||||
install -m 755 "$1" "$release/bedrock"
|
||||
|
||||
# 容器内监听全部接口供同网络的代理访问;端口 8080 没有在此发布到宿主公网,TLS 由 Traefik 处理。
|
||||
export HOST=0.0.0.0 PORT=8080 PUBLIC_ORIGIN="$origin"
|
||||
|
||||
# 邮件/研究配置可选且从受保护文件加载;Slack 优先 Actions 环境,缺省才回退服务器文件。
|
||||
mail_env=()
|
||||
if [[ -s "$foundry/mail.env" ]]; then
|
||||
mail_env=(--env-file "$foundry/mail.env")
|
||||
fi
|
||||
research_env=()
|
||||
if [[ -s "$foundry/research.env" ]]; then
|
||||
research_env=(--env-file "$foundry/research.env")
|
||||
fi
|
||||
slack_env=()
|
||||
if [[ -n "${SLACK_CLIENT_ID:-}" || -n "${SLACK_CLIENT_SECRET:-}" ]]; then
|
||||
for name in SLACK_CLIENT_ID SLACK_CLIENT_SECRET; do
|
||||
value=${!name-}
|
||||
if [[ -z "$value" || "$value" == *$'\n'* || "$value" == *$'\r'* ]]; then
|
||||
printf 'Missing or invalid %s\n' "$name" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
export SLACK_CLIENT_ID SLACK_CLIENT_SECRET
|
||||
slack_env=(-e SLACK_CLIENT_ID -e SLACK_CLIENT_SECRET)
|
||||
elif [[ -s "$foundry/slack.env" ]]; then
|
||||
slack_env=(--env-file "$foundry/slack.env")
|
||||
fi
|
||||
|
||||
# 下面构造可选 IPC 挂载参数;未配置 worker 时数组为空,Core 仍可启动其余业务接口。
|
||||
codex_mounts=()
|
||||
codex_dir=$foundry/codex
|
||||
|
||||
# 存在 worker 配置才启用 IPC;worker 必须先与当前 Core 二进制协议对齐,启动失败恢复旧 worker。
|
||||
if [[ -d "$codex_dir" ]]; then
|
||||
|
||||
# Core and its private worker must speak the same Canvas artifact protocol.
|
||||
# Keep the previous container definition for exact startup rollback.
|
||||
# 保留旧容器本身,确保新 worker 启动/目录检查失败时可以恢复原来的挂载和配置。
|
||||
# 这里先停旧 worker 再启动新 worker,替换期间并非双 worker 无缝接管。
|
||||
worker_backup=
|
||||
if docker inspect foundry-codex-worker >/dev/null 2>&1; then
|
||||
worker_backup=foundry-codex-worker-previous-$(date +%s)-$$
|
||||
docker stop -t 5 foundry-codex-worker >/dev/null
|
||||
docker rename foundry-codex-worker "$worker_backup"
|
||||
fi
|
||||
|
||||
# 用当前 release 的同一份 Go 二进制启动 worker,避免 Core/worker 的画布产物协议不一致。
|
||||
# 目录探测只验证 socket 和非空模型目录,不执行一次真实生成,也不验证模型账户额度。
|
||||
worker_ready=false
|
||||
if bash "$(dirname "$0")/codex-worker.sh" "$release/bedrock" >/dev/null; then
|
||||
for attempt in {1..20}; do
|
||||
if docker exec foundry-codex-worker node -e '
|
||||
const http = require("node:http");
|
||||
const req = http.get({socketPath:"/run/foundry-codex/worker.sock",path:"/canvas/models"}, res => {
|
||||
let body = "";
|
||||
res.on("data", chunk => { body += chunk; if(body.length > 262144) req.destroy(); });
|
||||
res.on("end", () => { try { const value=JSON.parse(body); process.exit(res.statusCode===200 && Array.isArray(value.models) && value.models.length>0 ? 0 : 1); } catch { process.exit(1); } });
|
||||
});
|
||||
req.setTimeout(2000, () => req.destroy());
|
||||
req.on("error", () => process.exit(1));
|
||||
' >/dev/null 2>&1; then worker_ready=true; break; fi
|
||||
sleep 0.25
|
||||
done
|
||||
fi
|
||||
if [[ "$worker_ready" != true ]]; then
|
||||
docker rm -f foundry-codex-worker >/dev/null 2>&1 || true
|
||||
if [[ -n "$worker_backup" ]]; then
|
||||
docker rename "$worker_backup" foundry-codex-worker
|
||||
docker start foundry-codex-worker >/dev/null
|
||||
fi
|
||||
printf 'Canvas worker startup/catalog verification failed; previous worker restored.\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 目录探测成功后删除旧 worker 定义;后续候选/路由失败不会再恢复该 worker,回滚范围需据此理解。
|
||||
if [[ -n "$worker_backup" ]]; then docker rm "$worker_backup" >/dev/null; fi
|
||||
for attempt in {1..20}; do
|
||||
[[ ! -S "$codex_dir/run/worker.sock" ]] || break
|
||||
sleep 0.25
|
||||
done
|
||||
test -S "$codex_dir/run/worker.sock"
|
||||
test -s "$codex_dir/grants/projects.json"
|
||||
|
||||
# API 容器只拿 socket 和项目授权表;只读目录挂载允许连接 socket,但禁止修改目录内容。
|
||||
# 这不把 worker 的 CLI 登录目录提供给 Core,两个进程仍使用各自的文件系统与环境。
|
||||
codex_mounts=(
|
||||
--mount "type=bind,source=$codex_dir/run,target=/run/foundry-codex,readonly"
|
||||
--mount "type=bind,source=$codex_dir/grants,target=/etc/foundry-codex,readonly"
|
||||
-e FOUNDRY_CODEX_SOCKET=/run/foundry-codex/worker.sock
|
||||
-e FOUNDRY_CODEX_GRANTS=/etc/foundry-codex/projects.json
|
||||
)
|
||||
fi
|
||||
|
||||
# 使用现成 node 镜像作为运行载体,实际启动 /opt/bedrock 这个 Go 可执行文件,不在此 docker build。
|
||||
# Node 供就绪探测使用;CA bundle 供 Go 的 HTTPS 客户端使用,二者的证书来源不能混为一谈。
|
||||
# Core 只挂载 IPC/授权表,不挂载 CLI 登录;以非 root、只读根文件系统和裁剪能力运行。
|
||||
docker run -d --name "$candidate" "${codex_mounts[@]}" "${mail_env[@]}" "${slack_env[@]}" "${research_env[@]}" --network "$network" \
|
||||
--env-file "$foundry/database.env" -e HOST -e PORT -e PUBLIC_ORIGIN \
|
||||
-e GOOGLE_CLIENT_ID -e GOOGLE_CLIENT_SECRET -e FOUNDRY_PROJECTS -e FOUNDRY_ONBOARDING \
|
||||
--user 1000:1000 --cap-drop ALL --security-opt no-new-privileges \
|
||||
--read-only --memory 1g \
|
||||
--mount "type=bind,source=$ca_bundle,target=/etc/ssl/certs/ca-certificates.crt,readonly" \
|
||||
-e SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt \
|
||||
--mount "type=bind,source=$release/bedrock,target=/opt/bedrock,readonly" \
|
||||
node:24-bookworm-slim /opt/bedrock >/dev/null
|
||||
|
||||
# 候选或路由失败时删除本次新 Core;旧 Core 由 route 成功探测后才停止。
|
||||
cleanup_candidate() {
|
||||
docker rm -f "${live:-$candidate}" >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
# 从候选 Core 启动后的阶段安装清理器;后续检查失败会移除本次 Core,不能据此推断前面的迁移/worker 也回滚。
|
||||
trap cleanup_candidate EXIT
|
||||
|
||||
# 容器内 smoke 只验证 CA 文件、数据库就绪及匿名请求被拒,不执行真实 OAuth 或付费模型。
|
||||
docker exec "$candidate" node -e '
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
async function verify() {
|
||||
assert.ok(fs.readFileSync(process.env.SSL_CERT_FILE, "utf8").includes("-----BEGIN CERTIFICATE-----"));
|
||||
const base = "http://127.0.0.1:8080";
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
const ready = await fetch(base + "/readyz", {signal: AbortSignal.timeout(3000)});
|
||||
if (ready.ok) break;
|
||||
} catch (error) {
|
||||
if (attempt === 9) throw error;
|
||||
}
|
||||
assert.ok(attempt < 9);
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
}
|
||||
const project = Object.keys(JSON.parse(process.env.FOUNDRY_PROJECTS))[0];
|
||||
const route = base + "/projects/" + encodeURIComponent(project) + "/auth";
|
||||
assert.equal((await fetch(route + "/me")).status, 401);
|
||||
if (process.env.FOUNDRY_CODEX_SOCKET) {
|
||||
const exec = base + "/projects/" + encodeURIComponent(project) + "/codex/exec";
|
||||
assert.equal((await fetch(exec, {method: "POST"})).status, 401);
|
||||
}
|
||||
}
|
||||
verify().catch(() => { console.error("Foundry readiness or anonymous access check failed"); process.exit(1); });
|
||||
'
|
||||
|
||||
# Keep the previous running container until the new candidate has passed checks.
|
||||
# Traefik reads the route atomically from its watched config directory.
|
||||
# 使用容器 ID 前缀命名新 live,route.sh 负责原子路由写入、外部就绪检查和失败恢复路由。
|
||||
id=$(docker inspect -f '{{.Id}}' "$candidate")
|
||||
live=foundry-core-${id:0:12}
|
||||
docker rename "$candidate" "$live"
|
||||
|
||||
# 只有候选内部检查通过才设为长期容器并请求切流;重启策略保证 Docker 重启后继续运行。
|
||||
docker update --restart unless-stopped "$live" >/dev/null
|
||||
bash "$(dirname "$0")/route.sh" "$live"
|
||||
|
||||
# route.sh 成功返回后解除本脚本的候选清理,保留新 Core;旧 release 目录仍由单独运维策略管理。
|
||||
trap - EXIT
|
||||
printf 'Foundry readiness and unauthenticated rejection verified.\n'
|
||||
@@ -1,25 +0,0 @@
|
||||
-- 运维手动索引步骤:对已发布 research schema 执行,不能由只读服务角色调用,也不能包进事务。
|
||||
-- 不属于 db/ 版本迁移;CREATE INDEX CONCURRENTLY 需要独立顶层语句,避免长时间阻塞语料读取。
|
||||
-- Manual operator step against the published Paper Atlas schema, outside a
|
||||
-- transaction. Core's SELECT-only runtime role must never execute this file.
|
||||
-- These indexes support the actual author search and exact category filter;
|
||||
-- the migration already owns the title/abstract English GIN index.
|
||||
-- 调整的是当前运维会话的等待/维护预算,不会修改运行时服务连接池的配置。
|
||||
-- 数据库迁移器只扫描 db/,不会自动执行这个文件;必须由有权限的运维会话单独运行。
|
||||
SET lock_timeout = '2s';
|
||||
SET statement_timeout = '20min';
|
||||
SET maintenance_work_mem = '32MB';
|
||||
SET max_parallel_maintenance_workers = 0;
|
||||
|
||||
-- (tag_id,paper_id) 支持纯主题页直接走关联索引,在 LIMIT 前避免读所有宽论文行。
|
||||
-- 先按 tag_id 找命中的 paper_id,适配按主题过滤的访问方向;不是对论文全文字段建立索引。
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS paper_tags_tag_paper
|
||||
ON research.paper_tags(tag_id,paper_id);
|
||||
|
||||
-- simple 配置匹配作者查询的表达式,不对姓名做 english 词干化;索引表达式须与查询一致。
|
||||
-- GIN 索引支持作者全文检索,使用 simple 配置保留姓名词项;与查询表达式不同就不能假设会命中本索引。
|
||||
CREATE INDEX CONCURRENTLY IF NOT EXISTS papers_authors_search_gin
|
||||
ON research.papers USING gin(to_tsvector('simple'::regconfig,authors_json));
|
||||
|
||||
-- After an interrupted concurrent build, inspect pg_index.indisvalid before
|
||||
-- reuse. IF NOT EXISTS alone does not repair an invalid index.
|
||||
-103
@@ -1,103 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# 远程部署的路由切换阶段,参数必须是本次已通过内部就绪检查的 Core 容器名。
|
||||
set -euo pipefail
|
||||
umask 077
|
||||
|
||||
# 固定工作目录供下面 Compose 与动态配置使用;这里只接受 release.sh 生成的容器名,避免随意写路由目标。
|
||||
cd /opt/endoleap-infra
|
||||
live=$1
|
||||
[[ "$live" =~ ^foundry-core-[a-f0-9]{12}$ ]]
|
||||
|
||||
# 动态路由和 ACME 证书状态在服务器持久目录内;该目录会挂给 Traefik 的 file provider。
|
||||
install -d -m 700 dev/foundry-edge
|
||||
edge=dev/foundry-edge
|
||||
route=$edge/foundry.yml
|
||||
|
||||
# 从现有动态配置提取旧容器;仅在新路由完成 HTTPS 探测后才停止它。
|
||||
previous=
|
||||
if [[ -f "$route" ]]; then
|
||||
previous=$(sed -n 's@.*url: http://\(foundry-core-[a-f0-9]\{12\}\):8080.*@\1@p' "$route")
|
||||
fi
|
||||
|
||||
# 先备份现有路由,再安装 EXIT 恢复器;切流探测失败时可恢复旧目标,但不会撤销外部数据库副作用。
|
||||
backup=$(mktemp)
|
||||
if [[ -f "$route" ]]; then cp "$route" "$backup"; fi
|
||||
|
||||
# EXIT trap 只恢复动态路由文件或删除新路由,不回滚已执行的数据库迁移/worker/Compose 配置。
|
||||
rollback() {
|
||||
if [[ -s "$backup" ]]; then
|
||||
cp "$backup" "$edge/.restore"
|
||||
mv "$edge/.restore" "$route"
|
||||
else
|
||||
rm -f "$route"
|
||||
fi
|
||||
rm -f "$backup"
|
||||
}
|
||||
trap rollback EXIT
|
||||
|
||||
# ACME 文件保存证书状态,限制权限;动态路由先写隐藏临时文件再 mv,避免 watcher 读到半文件。
|
||||
touch "$edge/acme.json"
|
||||
chmod 600 "$edge/acme.json"
|
||||
|
||||
# 这个 heredoc 生成 Traefik 动态配置:域名路由、证书解析器、限流和新容器的内部 HTTP 地址。
|
||||
# 它需要展开 $live,所以结束标记未加引号;先写临时文件,后面的 mv 才使新配置可见。
|
||||
cat > "$edge/.foundry.yml" <<YAML
|
||||
http:
|
||||
routers:
|
||||
foundry:
|
||||
entryPoints: [websecure]
|
||||
rule: Host(\`api.foundry.entroia.com\`)
|
||||
middlewares: [foundry-limit]
|
||||
service: foundry
|
||||
tls:
|
||||
certResolver: public
|
||||
middlewares:
|
||||
foundry-limit:
|
||||
rateLimit:
|
||||
average: 30
|
||||
burst: 60
|
||||
services:
|
||||
foundry:
|
||||
loadBalancer:
|
||||
servers:
|
||||
- url: http://$live:8080
|
||||
YAML
|
||||
mv "$edge/.foundry.yml" "$route"
|
||||
|
||||
# Compose 覆盖文件保持 Traefik 入口、证书与目录 provider 配置,不重建其他服务。
|
||||
# 这个 heredoc 生成 Compose 覆盖配置,固定宿主 443 -> Traefik 8443 的映射。
|
||||
# 标记加引号以保留 YAML 原文;这里的 Node/Go 应用端口并未直接发布。
|
||||
cat > foundry-edge.yml <<'YAML'
|
||||
services:
|
||||
traefik:
|
||||
command:
|
||||
- --entrypoints.web.address=:8080
|
||||
- --entrypoints.websecure.address=:8443
|
||||
- --ping=true
|
||||
- --ping.entrypoint=web
|
||||
- --api.dashboard=false
|
||||
- --providers.file.directory=/edge
|
||||
- --certificatesresolvers.public.acme.storage=/edge/acme.json
|
||||
- --certificatesresolvers.public.acme.tlschallenge=true
|
||||
ports:
|
||||
- "443:8443"
|
||||
volumes:
|
||||
- ./dev/foundry-edge:/edge
|
||||
YAML
|
||||
|
||||
# Compose 文件中的入口/挂载变化在此应用,只更新 traefik;不会重新构建或重建其他服务。
|
||||
docker compose -p endoleap-dev --env-file dev/env -f compose.yml -f dev.yml -f foundry-edge.yml up -d --no-deps traefik
|
||||
|
||||
# --resolve 在本机回环命中 Traefik,同时保留公开域名 Host/TLS 验证,探测真正的 HTTPS 路由。
|
||||
curl --fail --silent --show-error --output /dev/null --max-time 6 \
|
||||
--retry 15 --retry-delay 4 --retry-all-errors \
|
||||
--resolve api.foundry.entroia.com:443:127.0.0.1 \
|
||||
https://api.foundry.entroia.com/readyz
|
||||
|
||||
# HTTPS 就绪后解除回滚并删除备份;旧容器停止失败仅提示手工清理,不能误报新路由失败。
|
||||
trap - EXIT
|
||||
rm -f "$backup"
|
||||
if [[ "$previous" =~ ^foundry-core-[a-f0-9]{12}$ && "$previous" != "$live" ]]; then
|
||||
docker stop "$previous" >/dev/null || printf 'Previous container needs manual cleanup.\n' >&2
|
||||
fi
|
||||
Reference in New Issue
Block a user